在C中,可以在声明中使用字符串文字,如下所示:
char s[] = "hello";
Run Code Online (Sandbox Code Playgroud)
或者像这样:
char *s = "hello";
Run Code Online (Sandbox Code Playgroud)
那么区别是什么呢?我想知道在编译和运行时的存储持续时间实际发生了什么.
可能重复:
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)
任何人都能解释导致这种行为差异的原因吗?
可能重复:
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的新手,我正在尝试将日期/时间字符串拆分为单独的变量.但是,当我逐行遍历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)