【发布时间】:2018-11-13 16:50:57
【问题描述】:
我是 C 编程的初学者,我构建了一个接收字符串 "HodHasharon,frozenYogurt,100" 的函数。该函数将字符串切成 3 段,每段都是我的 City 结构的一个字段。
我想将"HodHasharon" 放入
城市pcity.name(城市名称),"frozenYogurt" 转换为pcity.popularFood(流行食品)和居民数量(100)转换为pcity.residents。
当我在我的函数中调试输出时,输出是正确的,但是当我从 main.c 打印时,我得到了一个串联的字符串。
例如,当我打印pcity.name 时,我得到"HodHashafrozenYod" 而不是"HodHasharon",但如果我在我的函数 printf->name 中执行 printf,我会得到正确的输出 "HodHasharon"
我做错了什么?
城市结构:
typedef struct City
{
char *name;
char * popluarFood;
int numberOfPeople;
} City;
功能:
City * cutCityData (char *singleLine)
{
City* pcity=(City*)malloc(sizeof(City));
int firstIndex=1;
int endIndex=1;
int checkItarion=0;
while(endIndex<strlen(singleLine))
{//while
while (singleLine[endIndex] != ',')
{//while2
endIndex++;
}//while2
checkItarion++;
char cityDetails[endIndex - firstIndex +1];
memcpy(cityDetails,&singleLine[firstIndex], endIndex);
cityDetails[endIndex - firstIndex] = '\0';
if (checkItarion == 1) {
pcity->name = (char *) malloc(cityDetails);
strcpy(&(pcity->name), cityDetails);
endIndex++;
firstIndex = endIndex;
}
if (checkItarion == 2) {
pcity->popluarFood = (char *) malloc(cityDetails);
strcpy(&(pcity->popluarFood), cityDetails);
endIndex++;
firstIndex=endIndex;
break;
}
}//while
char cityDetails[strlen(singleLine) - firstIndex + 1];
memcpy(cityDetails, &singleLine[firstIndex], sizeof(singleLine-1));
int resdints=atoi(cityDetails);
pcity->numberOfPeople=resdints;
return pcity;
}
来自主:
City* pCity=cutCityData(singLine);
printf("%s\n", &(pCity->name));
【问题讨论】:
-
阅读ericlippert.com/2014/03/05/how-to-debug-small-programs 了解调试代码的一些技巧。如果您仍需要帮助,请edit 您的问题包括minimal reproducible example。
-
&(pCity->name)应该只是pCity->name -
您可以使用
strchr()来搜索,,而不是自己编写循环。 -
数组索引从
0开始。为什么将firstIndex设置为1?