gpt4 book ai didi

c - 使用指针到指针从二维数组打印字符串

转载 作者:行者123 更新时间:2023-11-30 17:23:03 25 4
gpt4 key购买 nike

我正在尝试构建一个使用动态分配来构建字符串数组的程序。用户完成将他想要的单词输入到数组中后,我想一个接一个地打印数组。我正在使用指向指针的指针,但它似乎不起作用:

#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. 使用 strcpybuffer 复制到 malloc 的 block

    strcpy(curr_word, buffer);

    您正在丢弃已读单词,因为您没有将其放在任何地方

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

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

    这可以防止缓冲区溢出。

  3. 这只是第 jst,在您的情况下是单词的第 0 个字符

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

    更改为

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

    打开编译器警告,它会告诉您 printf 期望 char * 并接收 char

    <

另请考虑以下因素:

  1. main() 应返回 int
  2. 您不需要强制转换 malloc
  3. 不要用realloc覆盖指针,使用临时指针并仅在成功时将其分配给array。否则,如果realloc返回NULL,您将无法free(array)

关于c - 使用指针到指针从二维数组打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27768869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com