Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 打印函数变量时,打印输出不同_C_Strcpy_Strncpy - Fatal编程技术网

C 打印函数变量时,打印输出不同

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

我曾尝试解决一个练习,其中我们必须返回一个包含第一个空格分隔的单词及其给定字符串长度的结构。示例:“测试字符串”返回{“Test”,4}

为了解决这个问题,我实现了以下功能:

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);
另外,在退出程序之前,请确保
释放
此内存