c - 动态分配的字符串数组

标签 c pointers dynamic-memory-allocation

该程序应该动态存储输入到指针中的每个字符串。每个指针都是指针数组的一部分,这些指针将共同保存所有字符串。当用户输入空词或 NULL 时,它应该退出。我的问题是代码只是跳过了 NULL 条件语句。我看到了一些类似的帖子,已经研究了几个小时,但就是无法解决。

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

void readWord(char wordChar[], int MAX_CHARS);

int main()
{
    int MAX_CHARS = 20;
    int wCount = 0;

    char *wordArray[wCount]; // Array of pointers that will each point to wordChar
    char wordChar[MAX_CHARS];

    int i;
    for(i = 0;;i++)
    {
        wCount++;

        printf("Enter word: ");
        readWord(wordChar, MAX_CHARS); //Reads one word at a time


        //Dynamically store each 
        wordArray[i] = (char*) malloc((int) strlen(wordChar) * (int) sizeof(char));
        wordArray[i] = wordChar;
        printf("%s \n", wordArray[i]); //Troubleshooting *********************

        // If loop ends scanning when word is NULL 
        if(wordArray[i] == 'NULL')
        {   
            printf("if loop");
            break;
        }
        else printf("no loop");
    }

}


/***********************************************************/

void readWord(char wordChar[], int MAX_CHARS)
{
    int letter, i = 0;

    while((letter = getchar()) != '\n')
    {
        if(i < MAX_CHARS)
        {
            wordChar[i] = letter; 
            i++;
        }
    }

    wordChar[i] = '\0';
}

最佳答案

简短而无用的总结是:你正在#includeing string.h;使用它!


您正在尝试直接比较两个指针。

if(wordArray[i] == 'NULL')

这一行查看 wordArray[i] 的 指针 值到多字 rune 字 'NULL' 的值(注意我没有说字符串: 您在这里使用了单引号,所以 'NULL' 的整数值为 0x4e554c4c;请参阅 https://stackoverflow.com/a/7459943/510299 )。如果 wordArray[i] 指向地址 0x12345678,则这是将 0x12345678 与 0x4e554c4c 进行比较,发现它们不相等。

你想要的是比较字符串。在 C 语言中,您不能使用 == 执行此操作,因为 C 字符串是字符数组或指向字符的指针; == 比较指针(地址)值,正如我上面提到的。

解决方法,使用strcmp

if(strcmp(wordArray[i], "NULL") == 0)

(注意双引号的使用。)

编辑:另请注意 char *wordArray[wCount]; 是在 wCount == 0 时声明的。这名义上意味着您试图声明一个长度为 0 的数组,这是未定义的行为。您需要声明具有一定长度(可能是您可以存储的最大单词数)的 wordArray。 [感谢 riodoro1 在评论中指出这一点。]


你在这里用 C 语言操作字符串时犯了类似的错误:

wordArray[i] = (char*) malloc((int) strlen(wordChar) * (int) sizeof(char));

此行将指针 wordArray[i] 设置为一些新分配的内存。

wordArray[i] = wordChar;

此行然后继续更改指针 wordArray[i] 以指向存储读取单词的原始位置。哎呀。下次您执行此循环时,wordChar 发生变化,wordArray[i] 指向 wordChar...所以新单词“替换”之前的所有单词。

解决方案?您需要将字符串复制到刚刚 malloc 的内存中。使用 strcpy()

printf("if loop");

条件 (if) 语句不是一种循环。

关于c - 动态分配的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31321122/

相关文章:

c - 如何在c中使用文件中的信息

c - 为什么strcmp不返回0

c++ - 为什么任何一个函数的指针总是显示一个?

c - 如何引用嵌套结构中的指针?

c - 服务器/客户端的 C 指针问题

c - c中的两个不同的命令行参数

objective-c - 将 i 和 &i 传递给函数之间的区别

c - 将 CSV 解析为动态分配的结构数组 (ANSI 89)

c - C 中的激活记录是在堆栈还是堆上创建的?

c - 如何确定结构数组的大小并分配内存 C 编程