首页 > 解决方案 > C - 将数组分配给指针时出现“不兼容的类型”警告

问题描述

我有两个单词列表。

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

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

问题似乎与p = list1.

但是,两者p都有list1一个 type 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;
}

标签: carrayspointers

解决方案


list1是一个数组const char*
p是一个char**

您不能将指向指针的指针分配给指向非指针const的指针const

您需要声明pconst char**.


浏览CannedMoose在评论中发布的链接。
另外,使用双指针时要小心。const


推荐阅读