小编The*_*man的帖子

为什么strsep()不使用指向堆栈的指针?

似乎使用该函数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,
Run Code Online (Sandbox Code Playgroud)

我不明白这个问题。该程序使用的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); …
Run Code Online (Sandbox Code Playgroud)

c string heap stack strsep

2
推荐指数
1
解决办法
88
查看次数

如何最好地在C中格式化很长的字符串常量?

我有这个:

char * str = "hahahahahihihihihohohohohahahahahihihihihohohohohahahahahihihihihohohohohahahahahihihihihohohohohahahahahihihihihohohohohahahahahihihihihohohoho\0";
Run Code Online (Sandbox Code Playgroud)

我该如何正确设置其格式,以80列中断?使用方法:

char * str = "foo\
    bar";
Run Code Online (Sandbox Code Playgroud)

似乎是一个非常糟糕的主意,它导致未定义的行为,使strlen()返回的废话值

编辑:这是我正在谈论的未定义的行为:

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

int main(void)
{
    char *s = "haha\
               hihi\0";

    unsigned i = strlen(s);

    printf("Length: %i\n", i);

    return 0;
}

imperator@RomaAeterna ~/P/C/undefined> gcc -Wall -Wextra undefined.c 
imperator@RomaAeterna ~/P/C/undefined> ./a.out
Length: 14
Run Code Online (Sandbox Code Playgroud)

c string formatting strlen

1
推荐指数
1
解决办法
66
查看次数

标签 统计

c ×2

string ×2

formatting ×1

heap ×1

stack ×1

strlen ×1

strsep ×1