gpt4 book ai didi

c - 运行代码后没有输出产生。空白,一无所获。为什么?

转载 作者:行者123 更新时间:2023-12-04 07:24:16 25 4
gpt4 key购买 nike

运行代码后没有输出产生。空白,一无所获。问题是什么 ?

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

char* foo(){
char temp[] = "World";
char *result;
strcpy(result, temp);
return result;
}

int main(){
printf("%s", foo());
return 0;
}

最佳答案

指针result这里没有分配任何内存。因此,您首先需要为其分配一些内存,否则,您将遇到段错误。
一种方法是使用 calloc 动态分配内存。或 malloc这里。它位于 stdlib.h头文件。所以,你必须包括它。然后,

char *result = malloc(strlen(temp)+1);
会做的伎俩。

关于c - 运行代码后没有输出产生。空白,一无所获。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68305485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com