2017-03-01 84 views
0

代碼應該採取儘可能多的字符串作爲用戶想要放入,直到他們進入EOF。它是這樣做的,但在我嘗試輸出代碼後,它出現了這些小半框而不是字符串。數組輸入錯誤使用strcpy

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

INT主要(){

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]); 
    } 

回答

2

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

不,它不需要。 strcpy(dest, src),所以它複製s[count](這是一個充滿「隨機垃圾」的緩衝區)到buff

+0

非常感謝你讓我的自我在牆上尋找問題。 –