我正在尝试构建一个使用动态分配来构建字符串数组的程序。 在用户完成将他想要的单词输入到数组中之后,我想要一个接一个地打印数组。我正在使用指针指针,但它似乎不起作用:
#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]);
}
}
答案 0 :(得分:0)
使用buffer
malloc
复制到strcpy
'ed区块
strcpy(curr_word, buffer);
你丢弃了读取的单词,因为你没有把它放在任何地方
请勿使用gets
使用fgets
代替
fgets(buffer, sizeof(buffer), stdin);
这可以防止缓冲区溢出。
这只是j
st,在你的情况下是0
字的<{p}}字符
printf("%s\n", words[i][j]);
将其更改为
printf("%s\n", words[i]);
打开编译器警告,它会告诉您printf
期待char *
并收到char
。
还要考虑以下事项:
main()
应该返回int
。malloc
。realloc
覆盖指针,使用临时指针并仅在成功时将其指定给array
。否则,如果realloc
返回NULL
,您将无法以free(array)
为例。答案 1 :(得分: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]);
}
}