【问题标题】:array input wrong using strcpy使用 strcpy 的数组输入错误
【发布时间】:2017-03-01 03:07:42
【问题描述】:

在用户输入 EOF 之前,该代码应该接受用户想要输入的尽可能多的字符串。它正在这样做,但是在我尝试输出代码后,它会出现这些小半盒而不是字符串。

void sortString(char *s[], int count);

int main(){

    int i;
    char buff[BUFSIZ];
    int count;
    char** s = (char**)malloc(sizeof(char*));

    //allows user to keep typing until EOF is reached.
    printf("Here is the list of unsorted names: \n\n");
    for (count = 0; fgets(buff, sizeof(buff), stdin); count++)
    {
        s[count] = malloc((sizeof(buff))*sizeof(char));//allocats memory at s[count].
        strcpy(buff, s[count]);//adds the string in buff to s[count].
        s = (char**) realloc(s, ((sizeof(s) + sizeof(buff)) * sizeof(char*)) + 1);//then reallocats memeory for s to take another string.
    }

    printf("\nCount is %d\n\n", count);
   // Now sort string using sortString function
   // Step 4: implement sortString function for the above-mentioned function declaration
   for (i = 0; i < count; i++){
            printf("%s \n",s[i]);
   }
   sortString(s, count);
   printf("Here is the list of sorted names: \n\n");
   for (i = 0; i < count; i++){
            printf("%s",s[i]);
   }

【问题讨论】:

    标签: c arrays pointers


    【解决方案1】:

    strcpy(buff, s[count]);//adds the string in buff to s[count].

    不,它没有。 strcpy(dest, src),所以它将s[count](这是一个充满“随机垃圾”的缓冲区)复制到buff

    【讨论】:

    • 非常感谢,我一直在努力寻找问题。
    猜你喜欢
    • 2019-03-19
    • 2015-02-28
    • 2016-12-21
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 2020-04-20
    • 2013-04-05
    • 2023-03-10
    相关资源
    最近更新 更多