我不明白为什么第二个printf循环输出的数据不同于在函数作用域内完成的第一个printf循环。难道是指针在函数内部以某种方式改变,所以当它返回时它会返回一个不同的值?使用函数内部的calloc,更改指针作为函数参数传递
输出:
第一个printf内部功能:
零件TMP | 01245
零件X | 40001
零件Y | 98760
第二个printf以外的功能,在主:
它返回jiberish并且与在函数内打印时不一样。 我试着fprintf,这样我就可以在这里快速粘贴结果,但后来我收到了一个无法解释的调用堆栈错误。
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
void ProtocolParse_Start(int *numParts,char **parts, char *str, const char* partsDelim)
{
int partCount = strChrCount(str,'~');
*numParts = partCount;
parts = (char**)calloc(partCount,sizeof(char));
char *tempPart;
tempPart = strtok (str,partsDelim);
parts[0] = (char*)calloc(strlen(tempPart),sizeof(char));
strcpy(parts[0],tempPart);
int i =1;
for(; i < partCount; i++)
{
tempPart = strtok (NULL, partsDelim);
parts[i] = (char*)calloc(strlen(tempPart),sizeof(char));
strcpy(parts[i],tempPart);
}
i =0;
for(; i < partCount; i++)
{
printf ("%Parts %s\n",parts[i]);
}
}
void ProtocolParse_End(int numParts,char **parts)
{
int i = 0;
for (; i < numParts; i++)
free (parts[i]);
free (parts);
}
int main()
{
char proto[32] = "TMP|01245~X|40001~Y|98760~";
char **parts;
int numParts;
ProtocolParse_Start(&numParts, parts,proto,"~");
int i =0;
for(; i < numParts; i++)
{
printf ("%Parts %s\n",parts[i]);
}
ProtocolParse_End(numParts,parts);
return 0;
}
任何人都可以请说明我的问题。因为我不确定我在做什么错误?
删除了C++标记,以避免每个人都告诉你使用'std :: string',因为这显然是C代码。 – Borgleader 2014-10-10 18:44:49
抱歉,只需快速点击自动建议的标签。 – 2014-10-10 18:49:09