gpt4 book ai didi

c - 为什么 strsep() 不适用于指向堆栈的指针?

转载 作者:行者123 更新时间:2023-12-04 12:19:30 26 4
gpt4 key购买 nike

使用函数 strsep 查找字符串的第一个单词似乎存在指针兼容性问题。到目前为止,我一直认为 char *schar 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)。为什么函数指针指向堆栈或堆很重要?我明白为什么你不能访问二进制/文本段中的字符串,但是堆栈有什么问题?

最佳答案

 note: expected ‘char ** restrict’ but argument is of type ‘char (*)[200]’

您的警告准确地告诉您问题所在。你有两种不同的类型。

char *s2;        /* declares a character pointer */

同时

char s2[200];   /* declares an array of char[200] */

当你把地址作为一个指针,结果是一个pointer-to-pointer。当您将地址设为一个数组时,结果是一个指向数组的指针。当您取消引用 pointer-to-pointer 时,结果是 一个指针。当你取消引用 pointer-to-array 时,结果是 一个数组

strsep 并非旨在将 pointer-to-array 作为参数(这会阻止它根据需要重新分配)

关于c - 为什么 strsep() 不适用于指向堆栈的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55543717/

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