gpt4 book ai didi

c - C 中的指针。函数行为不当

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:45 25 4
gpt4 key购买 nike

void allocateMemory(char* pString, int length) { 
pString = (char*)malloc(length);
}

void test() {
char* pString = NULL;
allocateMemory(pString, 20);
strcpy(pString, "Hello world.");
}

为什么这个程序会崩溃?我已经使用 malloc 分配了内存。当函数返回时,我希望 pString 指向堆上的内存?这不是正在发生的事情吗?似乎 pString 仍然指向 null?

我们不能将地址更改为指针指向的地址吗?

最佳答案

在C中,它应该是这样的

void allocateMemory(char** pString, int length) { 
*pString = (char*)malloc(length);
}

void test() {
char* pString = NULL;
allocateMemory(&pString, 20);
strcpy(pString, "Hello world.");
}

关于c - C 中的指针。函数行为不当,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25824824/

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