简体   繁体   English

数组输入使用strcpy错误

[英]array input wrong using strcpy

The code is supposed to take in as many string as the user wants to put in until they enter EOF. 该代码应该在用户输入EOF之前接受用户想要输入的尽可能多的字符串。 and it is doing that but after i try to ouput the code it comes out with these little half boxes instead of the string. 它就是这样做的,但是在我尝试输出代码之后,它是用这些小半框而不是字符串输出的。

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

int main(){ 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]);
   }

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

No it doesn't. 不,不是。 strcpy(dest, src) , so it is copying s[count] (which is a buffer full of "random junk") to buff . strcpy(dest, src) ,因此它将s[count] (这是一个充满“随机垃圾”的缓冲区)复制到buff

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM