对于嵌入式代码(avr-gcc),我试图减少堆栈内存的使用。所以我想做的是创建一个指针,将其传递给函数,然后在函数中,将指针指向的地址更改为堆分配变量的地址。这样一来,就不会有内部分配的不具有堆栈内存main()
的testPointer
。
我正在尝试使用以下代码
#include <stdio.h>
char hello[18] = "Hello cruel world";
char* myfunc2() {
return hello;
}
void myfunc(char *mypointer) {
mypointer = myfunc2();
}
int main(){
char *testPointer;
printf("hello: %p\n", &hello);
printf("test: %p\n", &testPointer);
myfunc(testPointer);
printf("test: %p\n", &testPointer);
printf("test value: %s\n", testPointer);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但不会重新分配testPointer地址。当然在现实世界中的用例的myfunc2
不会是那么简单的,但它是返回一个指向堆中分配的字符数组。
输出:
hello: 0x404030
test: 0x7ffe48724d38
test: 0x7ffe48724d38
test value: (null)
Run Code Online (Sandbox Code Playgroud)
您将指针传递到要写入的位置。与之比较:
#include <stdio.h>
char hello[18] = "Hello cruel world";
char* myfunc2() {
return hello;
}
void myfunc(char **mypointer) {
*mypointer = myfunc2();
}
int main(){
char *testPointer;
printf("hello: %p\n", &hello);
printf("test: %p\n", &testPointer);
myfunc(&testPointer);
printf("test: %p\n", &testPointer);
printf("test value: %s\n", testPointer);
return 0;
}
Run Code Online (Sandbox Code Playgroud)