C 打印函数变量时,打印输出不同
我曾尝试解决一个练习,其中我们必须返回一个包含第一个空格分隔的单词及其给定字符串长度的结构。示例:“测试字符串”返回{“Test”,4} 为了解决这个问题,我实现了以下功能:C 打印函数变量时,打印输出不同,c,strcpy,strncpy,C,Strcpy,Strncpy,我曾尝试解决一个练习,其中我们必须返回一个包含第一个空格分隔的单词及其给定字符串长度的结构。示例:“测试字符串”返回{“Test”,4} 为了解决这个问题,我实现了以下功能: struct string whitespace(char* s){ char* t = s; size_t len = 0; while(*t != ' '){ len++; t++; } char out[len+1]; strncpy(o
struct string whitespace(char* s){
char* t = s;
size_t len = 0;
while(*t != ' '){
len++;
t++;
}
char out[len+1];
strncpy(out, s, len);
if(len>0){
out[len] = '\0';
}
//printf("%d\n",len);
struct string x = {out, len};
return x;
}
int main(){
char* s = "Test string";
struct string x = whitespace(s);
printf("(%s, %d)\n", x.str, x.len);
return 0;
}
结构定义如下:
struct string{
char* str;
size_t len;
};
如果我运行以下主功能:
struct string whitespace(char* s){
char* t = s;
size_t len = 0;
while(*t != ' '){
len++;
t++;
}
char out[len+1];
strncpy(out, s, len);
if(len>0){
out[len] = '\0';
}
//printf("%d\n",len);
struct string x = {out, len};
return x;
}
int main(){
char* s = "Test string";
struct string x = whitespace(s);
printf("(%s, %d)\n", x.str, x.len);
return 0;
}
我得到这个输出:
(, 4)
其中,当我删除注释//printf(“%d\n”,len)时代码>我得到:
4
(Test, 4)
事实上,每当我在函数空白(char*s)
中打印给定变量时,就会输出字符串(Test,4)
。此外,当使用不同的gcc
优化标志,如-O3
或-Ofast
时,即使不在函数中打印变量,结果也是正确的
我有没有碰到什么不确定的行为?有人能解释一下这里发生了什么吗?返回的结构包含一个char*
,指向局部变量out
。当函数返回时,该变量超出范围,因此取消对该指针的引用将调用
与其使用VLA,不如将out
声明为指针,并为其分配指向的内存。然后可以安全地将struct成员设置为该地址,并且在程序运行期间内存将保持良好状态
char *out = malloc(len+1);
另外,在退出程序之前,请确保释放该内存。返回的结构包含一个字符*
,指向局部变量out
。当函数返回时,该变量超出范围,因此取消对该指针的引用将调用
与其使用VLA,不如将out
声明为指针,并为其分配指向的内存。然后可以安全地将struct成员设置为该地址,并且在程序运行期间内存将保持良好状态
char *out = malloc(len+1);
另外,在退出程序之前,请确保释放此内存