【问题标题】:wrong output, can't understand why C错误的输出,不明白为什么是C
【发布时间】: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));

【问题讨论】:

标签: c function


【解决方案1】:

&amp;(pcity-&gt;name) 是指针变量的地址。您想将字符串复制到它指向的内存,而不是复制指针。所以改变:

strcpy(&(pcity->name), cityDetails);

strcpy(pcity->name, cityDetails);

您还给malloc() 提供了错误的参数。 cityDetails 是一个数组,但参数应该是您要分配的字节数。所以改变

pcity->name = (char *) malloc(cityDetails);

到:

pcity->name = malloc(strlen(cityDetails) + 1);

也需要对填写pcity-&gt;popularFood的代码进行这些更改。

这是错误的:

memcpy(cityDetails, &singleLine[firstIndex], sizeof(singleLine-1));

singleLine 是一个指针,所以sizeof(singleLine-1) 是指针中的字节数,而不是字符串的长度。这应该是:

memcpy(cityDetails, &singleLine[firstIndex], endIndex + 1);

【讨论】:

    猜你喜欢
    • 2016-03-31
    • 1970-01-01
    • 2022-12-14
    • 2023-02-07
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多