C - 将数组赋给指针时出现“不兼容类型”警告

时间:2018-04-29 05:40:10

标签: c arrays pointers

我有两个单词列表。

我的代码随机选择一个列表,然后随机选择列表中的一个单词。

代码工作正常,但我收到incompatible pointer type警告。

问题似乎出现在p = list1

但是,plist1都有char*类型,所以我不理解这个警告。

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>

void test() {

    srand(time(NULL));  // seed the random number generator.

    const char *list1[3] = { "one", "two", "three" }; // first list
    int len1 = 3;

    const char *list2[4] = { "uno", "dos", "tres", "quatro" }; // second list
    int len2 = 4;

    char **p;                  // variable to hold chosen list
    int pcount;                // size of the chosen list
    char word[64] = "none";    // chosen word

    int ran1 = rand() % 2;    // random number 0 or 1

    if (ran1 == 0) { p = list1; pcount = len1; } // warning: assignment from incompatible pointer type
    if (ran1 == 1) { p = list2; pcount = len2; } // warning: assignment from incompatible pointer type

    strcpy(word, p[rand() % pcount]);
    printf("The word is %s.\n", word);

    return;
}

2 个答案:

答案 0 :(得分:3)

list1const char*的数组 pchar**

您无法将指针指针指向 - const指向指向非指针的指针 - const

您需要将p声明为const char**

<小时/> 在评论中完成CannedMoose发布的the link 此外,be careful使用带有双指针的const

答案 1 :(得分:3)

您的代码中存在多个问题:

  • p应定义为const char **p以与const char *list[]兼容。
  • 您可以将len1len2变量初始化为计算出的数组长度,以避免较大集合上的潜在差异。
  • ran1上用于选择集合的测试既冗余又可能不完整。您应确保涵盖ran1的所有值并让编译器知道。已启用所有警告的正确配置的编译器会抱怨ppcount可能未初始化。
  • 你应该在你的程序中只使用一次随机数生成器,否则在同一秒内多次调用test()会选择相同的单词。

以下是修改后的版本:

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

void test(void) {
    const char *list1[] = { "one", "two", "three" }; // first list
    int len1 = sizeof(list1) / sizeof(list1[0]);

    const char *list2[] = { "uno", "dos", "tres", "quatro" }; // second list
    int len2 = sizeof(list2) / sizeof(list2[0]);

    const char **p;            // variable to hold chosen list
    int pcount;                // size of the chosen list
    char word[64];             // chosen word

    int ran1 = rand() % 2;     // random number 0 or 1

    if (ran1 == 0) {
        p = list1; pcount = len1;
    } else {
        p = list2; pcount = len2;
    }

    strcpy(word, p[rand() % pcount]);
    printf("The word is %s.\n", word);
}

int main() {
    srand(time(NULL));  // seed the random number generator.

    test();
    test();
    test();
    test();
    return 0;
}
相关问题