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; ^
而且我不知道为什么。
这是我的主要function:
#include #include #include #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; }
您的createArrray
具有错误的签名。 试试吧
char** createArray(unsigned count) { char** a = malloc(sizeof(char*) * count); if (a == NULL) { perror("createArray"); exit(EXIT_FAILURE); } return a; }
当然,相应地更改头文件中的声明:
char** createArray(unsigned);
顺便说一下,你正好用gcc -Wall -g
进行编译。 现在尝试在gdb
调试器中逐步运行您的程序。
注意:将count
声明为int
是没有意义的(道德上,它不能是负数)。
你不算数星星。
Foo* foo = // 1 star malloc(sizeof(Foo)); // 0 stars Foo** foo = // 2 stars malloc(sizeof(Foo*)); // 1 star Foo******* foo = // N stars malloc(sizeof(Foo******)); // N-1 stars
如果你的计数不同,你做错了。
当然这只是一个安全检查。 您需要了解每个*
在代码中的作用。
字典是char**
。 为什么? 它是一个数组(第一个*
)的字符串(第二个*
)。 所以它不能是char
或char*
或char***
。 因此,在赋值的右侧,您也需要char**
,因此createArray
必须返回char**
,并且必须是char**
,并且在malloc内的sizeof内需要N-1 = 1星。