我是 C 编程的初学者,我构建了一个接收字符串的函数"HodHasharon,frozenYogurt,100"。该函数将字符串切成 3 段,其中每段都是我的City结构的一个字段。
我想将"HodHasharon"City pcity.name(城市名称)、(流行食物)和居民人数()"frozenYogurt"放入.pcity.popularFood100pcity.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));