2015-01-04 129 views
0

我想構建一個程序,使用動態分配來構建一個字符串數組。 用戶完成輸入他想要到陣列中的單詞後,我想將一個單詞一個接一個地打印出來。我使用指針的指針,但它似乎不工作:從二維數組打印字符串使用指針指針

#define SIZE 256 
void paintWords(char **words, int count_words); 

void main() { 
    char **words = NULL; 
    int flag = 1; 
    char buffer[SIZE]; 
    int count_words = 0; 
    char *curr_word; 
    while (flag) 
    { 
     _flushall(); 
     printf("Enter a word:"); 
     gets(buffer); 
     words = (char**)realloc(words,++count_words*sizeof(char*)); 
     curr_word = (char*)malloc(strlen(buffer) + 1); 
     words[count_words - 1] = curr_word; 
     printf("Do you wish to continue(0-no, 1-yes):"); 
     scanf("%d", &flag); 
    } 
    paintWords(words, count_words); 
} 

void paintWords(char **words, int count_words) { 
    int j = 0; 
    for (int i = 0; i < count_words; i++) 
    { 
     printf("%s\n", words[i][j]); 
    } 
} 
+1

'無效main'哎喲.... – Ankur

回答

0
  1. 複製buffermalloc「版塊與strcpy

    strcpy(curr_word, buffer); 
    

    你丟棄,因爲讀字你不要把它放在任何地方

  2. 不要使用gets使用fgets而不是

    fgets(buffer, sizeof(buffer), stdin); 
    

    這將防止緩衝區溢出。

  3. 這只是j ST而你的情況是詞

    printf("%s\n", words[i][j]); 
    

    改變它的0個字符

    printf("%s\n", words[i]); 
    

    ,它會告訴你關於轉編譯器警告代替printf代替char *並接收char

還要考慮以下幾點:

  1. main()應該返回int
  2. 您無需投下malloc
  3. 請勿使用realloc覆蓋指針,請使用臨時指針並僅在成功時將其指定給array。否則,如果realloc返回NULL您將無法以free(array)爲例。
+0

給定的代碼甚至沒有編譯...此外,我們應該使用免費的' – Ankur

+0

你的strcpy()是錯誤的修復它。單詞是雙指針指針是單詞[idx] – Gopi

0
++count_words 
words = realloc(words,count_words*sizeof(char*)); 
words[count_words-1] = malloc(strlen(buffer) + 1); 

strcpy(words[count_words-1],buffer); 

後來打印陣列

printf("%s\n",words[i]); 

realloc()可以失敗,因此

char *temp = realloc(words,count_words*sizeof(char*)); 

if(temp != NULL) 
words = temp; 

很少有其他的修復將是

你不應該使用gets這是毫無更多是一種標準。使用fgets()並注意fgets()帶有一個換行符

檢查下面的代碼:

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 

#define SIZE 256 
void paintWords(char **words, int count_words); 

void main() { 
    char **words = NULL,ch; 
    int flag = 1; 
    char buffer[SIZE]; 
    int count_words = 0; 
    //char *curr_word; 
    while (flag) 
    { 

     printf("Enter a word:"); 
     fgets(buffer,sizeof(buffer),stdin); 

     words = (char**)realloc(words,++count_words*sizeof(char*)); 

     words[count_words - 1] = (char*)malloc(strlen(buffer) + 1); 
     strcpy(words[count_words-1],buffer); 
     printf("Do you wish to continue(0-no, 1-yes):"); 
     scanf("%d", &flag); 
     while((ch = getchar()) != '\n'); 
    } 
    paintWords(words, count_words); 
} 

void paintWords(char **words, int count_words) { 
    int i; 
    for (i=0; i < count_words; i++) 
    { 
     printf("%s", words[i]); 
    } 
}