相关疑难解决方法(0)

char s []和char*s有什么区别?

在C中,可以在声明中使用字符串文字,如下所示:

char s[] = "hello";
Run Code Online (Sandbox Code Playgroud)

或者像这样:

char *s = "hello";
Run Code Online (Sandbox Code Playgroud)

那么区别是什么呢?我想知道在编译和运行时的存储持续时间实际发生了什么.

c string constants char

495
推荐指数
6
解决办法
33万
查看次数

strtok - char数组与char指针

可能重复:
strtok不接受:char*str

使用该strtok功能时,使用char *而不是char []导致分段错误.

这运行正常:

char string[] = "hello world";
char *result = strtok(string, " ");
Run Code Online (Sandbox Code Playgroud)

这会导致分段错误:

char *string = "hello world";
char *result = strtok(string, " ");
Run Code Online (Sandbox Code Playgroud)

任何人都能解释导致这种行为差异的原因吗?

c arrays pointers strtok

10
推荐指数
2
解决办法
2万
查看次数

Strtok segfault

可能重复:
strtok给出分段错误

为什么我使用此代码获得段错误?

void test(char *data)
{
    char *pch;
    pch = strtok(data, " ,.-"); // segfault
    while (pch != NULL)
    {
        printf("%s\n", pch);
        pch = strtok(NULL, " ,.-");
    }

    return NULL;
}

char *data = "- This, a sample string.";
test(data);
Run Code Online (Sandbox Code Playgroud)

c

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

strtok导致段错误,但不是在单步执行代码时

我是C的新手,我正在尝试将日期/时间字符串拆分为单独的变量.但是,当我逐行遍历gdb中的代码时,它可以工作,但是,当我让它正常运行而没有断点时它会出错并且我看不清楚原因.

以下是代码:

char * dateTimeString = "2011/04/16 00:00";
char dateVar[11];
char timeVar[6];

if (splitTimeAndDateString(dateVar, timeVar, dateTimeString))
{
    exit(1);
}

printf("Date: %s\tTime: %s\n", dateVar, timeVar);
Run Code Online (Sandbox Code Playgroud)

以下是功能

int splitTimeAndDateString(char date[11], char time[6], char * dateString)
{
    char *token;
    token = strtok(dateString, " ");
    int i = 0;
    while (token != NULL)
    {
        if (i == 0)
        {
            strcpy(date, token);
        }
        else if (i == 1)
        {
            strcpy(time, token);
        }
        else
        {
            printf("Overrun date time string\n");
            return 1;
        }
        token = strtok(NULL, " …
Run Code Online (Sandbox Code Playgroud)

c strtok

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

标签 统计

c ×4

strtok ×2

arrays ×1

char ×1

constants ×1

pointers ×1

string ×1