【发布时间】:2019-08-27 20:22:45
【问题描述】:
使用函数strsep 查找字符串的第一个单词似乎存在指针兼容性问题。到目前为止,我一直认为char *s 和char s[] 是完全可以互换的。但似乎他们不是。我在堆栈上使用数组的程序失败并显示以下消息:
foo.c: In function ‘main’:
foo.c:9:21: warning: passing argument 1 of ‘strsep’ from incompatible pointer type [-Wincompatible-pointer-types]
char *sub = strsep(&s2, " ");
^
In file included from foo.c:2:0:
/usr/include/string.h:552:14: note: expected ‘char ** restrict’ but argument is of type ‘char (*)[200]’
extern char *strsep (char **__restrict __stringp,
我不明白这个问题。使用malloc 的程序有效。
这行得通:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char s1[] = "Hello world\0";
char *s2 = malloc(strlen(s1)+1);
strcpy(s2, s1);
char *sub = strsep(&s2, " ");
printf("%s\n", sub);
return 0;
}
这不是:
#include <stdio.h>
#include <string.h>
int main(void)
{
char s1[] = "Hello world\0";
char s2[200];
strcpy(s2, s1);
char *sub = strsep(&s2, " ");
printf("%s\n", sub);
return 0;
}
有什么问题? (对不起strcpy)。为什么函数指针指向堆栈或堆很重要?我明白为什么你不能访问二进制/文本段中的字符串,但是堆栈有什么问题?
【问题讨论】:
-
我很确定您第二个示例中的
&s2会返回char **?打开编译器警告。 -
您应该只使用
s2,或者如果您愿意,可以使用&s2[0]。数组已经转换为指针。 -
@YoYoYonnY 这些将导致
char *。strsep的第一个参数是char **。 -
您需要为
strsep提供一个char **,以便它可以修改它。在第二个示例中,&s2具有类型char (*)[200],这是完全不同且不兼容的。它需要修改指针,在这种情况下它显然不能这样做。 -
@YoYoYonnY 不正确。第二个示例中的
&s2具有char (*)[200]类型,它从不 与char **兼容。
标签: c string heap-memory stack-memory strsep