c - gcc 说“来自不兼容指针类型的赋值 [默认启用]

标签 c pointers gcc

好吧,我一直收到这个错误:

$ gcc -Wall -g translate.c support.c scanner.c -o translate
translate.c: In function ‘main’:
translate.c:22:16: warning: assignment from incompatible pointer type [enabled by default]
     dictionary = createArray(count);
            ^
support.c: In function ‘readTokens’:
support.c:66:18: warning: assignment from incompatible pointer type [enabled by default]
         a[count] = token;
              ^

我也不知道为什么。

这是我的主要功能:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "support.h"

int main(int argc, char** argv) {
    int i;
    int count;
    char** dictionary;

    if (argc != 3) {
        printf("need two arguments!\n");
        exit(-1);
    }

    count = countTokens(argv[1]);
    printf("there are %d tokens and strings\n", count);

    dictionary = createArray(count);

    readTokens(argv[1], dictionary);

    printf("The dictionary:\n");
    for (i = 0; i < count; ++i) {
        printf("%s\n", dictionary[i]);
    }
    return 0;
}

和我的创建数组函数:

char* createArray(int count) {
    char* a;
    a = malloc(sizeof(char*) * count);
    if (a == 0) {
        fprintf(stderr, "memory allocation failed\n");
        exit(1);
    }

    return a;
}

及其标题

char * createArray(int);

我不知道如何让它消失。我试过去掉和添加星号,并将等号从一个等号改为两个,但没有用。二年级 cs 学生,c 第一年。任何帮助将不胜感激。谢谢!

最佳答案

您的 createArray 函数声明和实现有误。您需要一个类型为 (char **) 的 char 指针数组,因此创建并返回这样一个数组:

char** createArray(int count) {
    char** a;
    a = malloc(sizeof(char*) * count);
    if (a == 0) {
        fprintf(stderr, "memory allocation failed\n");
        exit(1);
    }

    return a;
}

关于c - gcc 说“来自不兼容指针类型的赋值 [默认启用],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25750511/

相关文章:

c - 如何将一个字符分配给数组?

c - 使用引用调用时,main 中动态分配的 char 指针不返回字符串

c - 将值赋给 ScanF 中的 char *

go - go中“无法分配给取消引用”是什么意思?

c++ - 编译器错误 : memset was not declared in this scope

c - 可以在 C 中返回和释放动态分配的数组吗?

c - 父进程和子进程的内存映射文件问题

C - 如何将多个值分配给 HashMap 中的同一个键?

c - ld : _start not found defaulting to

c++ - Thread Sanitizer - 如何解释读取与先前写入警告