2015-01-04 130 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]); 
    } 
}