gpt4 book ai didi

c - 在主函数中初始化指针并在不同函数中保留内存

转载 作者:行者123 更新时间:2023-11-30 15:16:07 25 4
gpt4 key购买 nike

在我的 main 函数中,我初始化了一个 char 指针。我给这个指针一个函数 setMemory(char *ptr) 作为参数,在其中分配一些内存。另外,一些数据应存储在该函数中。回到主函数,我尝试读出指针显示的数据,但没有输出正确的数据。为什么?

int main(int argc, char *argv){
char *ptr;
setMemory(ptr);
printf("String: %s", ptr); //Should print c
return 0;
}

void setMemory(char *ptr){
ptr = (char*)malloc(sizeof(char)*10);
*(ptr) = 'c';
}

最佳答案

基于 ameyCU 的回答

char* setMemory(int size){
char *ptr = calloc(size, sizeof(char)); //Used calloc instead of malloc + memeset to \0
*ptr = 'c';
return ptr;
}

并打电话

char *ptr = setMemory(10);

关于c - 在主函数中初始化指针并在不同函数中保留内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33219736/

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