gpt4 book ai didi

C - 将数组分配给指针时出现 "incompatible type"警告

转载 作者:行者123 更新时间:2023-12-02 08:07:41 25 4
gpt4 key购买 nike

我有两个单词列表。

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

代码工作正常,但我得到一个 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;
}

最佳答案

您的代码中有多个问题:

  • p应定义为 const char **pconst 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;
    }

    关于C - 将数组分配给指针时出现 "incompatible type"警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50083729/

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