c语言 - 为什么 strsep() 不能与指向堆栈的指针一起使用?



使用函数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";
    char *s2 = malloc(strlen(s1)+1);
    strcpy(s2, s1);
    char *sub = strsep(&s2, " ");
    printf("%sn", sub);
    return 0;
}

这不会:

#include <stdio.h>
#include <string.h>
int main(void)
{
    char s1[] = "Hello world";
    char s2[200];
    strcpy(s2, s1);
    char *sub = strsep(&s2, " ");
    printf("%sn", 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] */

当您获取指针的地址时,结果是指针到指针。当您获取数组的地址时,结果是指向数组的指针。取消引用指针到指针时,结果是指针。取消引用指向数组的指针时,结果是一个数组

strsep 并非旨在将指向数组的指针作为参数(这会阻止它根据需要重新分配(

@DavidRankin为什么它不起作用是正确的。但是您仍然可以编写代码,以便它可以在堆栈上使用变量。

要使用数组代替 malloc((,您可以创建另一个指向该数组的指针,并将其用作 strsep(( 的参数,如 version1(( 函数所示。

我知道这可能只是一个示例,但是您提供的带有malloc((和strsep((的示例可能会导致内存错误,因为strsep((将更新指针(它会修改它指向的地址(。因此,您必须保存 malloc(( 返回的原始地址才能正确释放该内存。请参阅版本 2(( 示例。

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

void version1(void)
{
    char s1[] = "Hello world";
    char s2[200];
    char* s3 = s2;
    char *sub;
    strcpy(s3, s1); // or s2 in place of s3
    while ((sub = strsep(&s3, " ")))
    {
        printf("%sn", sub);
    }
}
void version2(void)
{
    char s1[] = "Hello world";
    char *mymem = malloc(strlen(s1)+1);
    char *s2 = mymem;
    char *sub;
    strcpy(s2, s1);
    while ((sub = strsep(&s2, " ")))
    {
        printf("%sn", sub);
    }
    free(mymem);
}
int main(int argc, char* argv[])
{
    printf("Version1n");
    version1();
    printf("nVersion2n");
    version2();
    return 0;
}

最新更新