使用strcpy输入错误的数组

时间:2017-03-01 03:07:43

标签: c arrays pointers

代码应该接收用户想要输入的字符串,直到它们进入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]);
   }

1 个答案:

答案 0 :(得分:2)

ViewBag

不,不。 strcpy(buff, s[count]);//adds the string in buff to s[count].,因此它将strcpy(dest, src)(这是一个充满“随机垃圾”的缓冲区)复制到s[count]