函数’strtok_r’的隐式声明尽管包括
我有以下代码来标记包含由\n
分隔的行的字符串,每行包含由\t
分隔的整数:
void string_to_int_array(char file_contents[BUFFER_SIZE << 5], int array[200][51]) { char *saveptr1, *saveptr2; char *str1, *str2; char delimiter1[2] = "\n"; char delimiter2[2] = " "; char line[200]; char integer[200]; int j; for(j = 1, str1 = file_contents; ; j++, str1 = NULL) { line = strtok_r(str1, delimiter1, &saveptr1); if (line == NULL) { break; } for (str2 = line; ; str2 = NULL) { integer = strtok_r(str2, delimiter2, &saveptr2); if (integer == NULL) { break; } } } }
(此处仅包含相关function,如果需要,则完整在此处 。)
但是,当我尝试使用以下代码编译此代码时:
gcc -m64 -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes file_read.c
我收到以下警告:
file_read.c:49:5: warning: implicit declaration of function 'strtok_r' [-Wimplicit-function-declaration] line = strtok_r(str1, delimiter1, &saveptr1); ^ file_read.c:49:10: error: incompatible types when assigning to type 'char[200]' from type 'int' line = strtok_r(str1, delimiter1, &saveptr1); ^ file_read.c:59:15: error: incompatible types when assigning to type 'char[200]' from type 'int' integer = strtok_r(str2, delimiter2, &saveptr2); ^
第49和59行对应于strtok_r
调用。
正如您所看到的,我在我的文件中包含了string.h
(这是声明strtok_r
地方),我仍然得到strtok_r
的隐式声明警告。
任何关于我如何删除警告的见解表示赞赏。
我在ubuntu 14.04 64位桌面上使用gcc 4.8.2。
strtok_r
不是标准的C函数。 您通过使用-std=c99
编译器标志仅要求C99,因此(glibc)头文件只能使您在string.h
使用标准C99函数。
使用-std=gnu99
启用扩展,或者通过定义strtok的联机帮助页中显示的一个扩展,在包含string.h
之前支持strtok_r。 例如
#define _GNU_SOURCE #include
请注意,代码也有其他问题, strtok_r
返回一个char *
,但是你试图将它分配给integer = strtok_r(str2, delimiter2, &saveptr2);
的char数组integer = strtok_r(str2, delimiter2, &saveptr2);
。 你的integer
变量应该是一个char *
与Debian上的GCC 7.4.2相同的问题
使用__strtok_r
或-std=gnu99
解决或在包含以下内容后添加原型:
#include #include #include #define BUFFER_SIZE 1024 extern char *strtok_r(char *, const char *, char **);
问题是函数strtok_r
返回一个指向char的指针,你试图将其分配给一个char数组,所以为了使它工作,你必须将你的line
和integer
变量声明为char的指针,然后分配内存与malloc。
void string_to_int_array(char file_contents[BUFFER_SIZE << 5], int array[200][51]) { char *saveptr1, *saveptr2; char *str1, *str2; char delimiter1[2] = "\n"; char delimiter2[] = " "; char *line; char *integer; int j; line = (char*)malloc(200); integer = (char*)malloc(200); for(j = 1, str1 = file_contents; ; j++, str1 = NULL) { line = strtok_r(str1, delimiter1, &saveptr1); printf("%s\n", line); if (line == NULL) { break; } printf("end of first\n"); for (str2 = line; ; str2 = NULL) { printf("begin of second\n"); printf("asdf%s\n", line); integer = strtok_r(str2, delimiter2, &saveptr2); if (integer == NULL) { break; } printf("%s\n", integer); } } }
我也使用4.8.2和ubuntu 14.04 64位。 但我得到了不同的错误。
incompatible types when assigning to type 'char[200]' from type 'char *' line = strtok_r(str1, delimiter1, &saveptr1); ^
这里, line
被声明为’char [200]’但是strtok_r
返回char*
。
integer = ...
行的相似错误integer = ...
要摆脱这些编译错误,你可以声明像char *line;
这样的东西char *line;
。
有关隐式声明的警告,请检查此项
我可以在Linux内核模块中使用strtok()吗?