在C中的函数调用内为指针分配内存

Tho*_*mas 4 c

我做了一个示例程序来说明问题.在test我分配内存foo以存储两个整数.然后,我将每个整数设置为一个值,然后我打印它们.非常简单,除非我只能在整数中为整数赋值main- 当我在里面做它时它将无法工作test.


此代码有效:

#include <stdio.h>
#include <stdlib.h>

void test(int **foo) {
    *foo = malloc(2 * sizeof(int));
}

int main() {
    int *foo;

    test(&foo);

    foo[0] = 4;  // <---
    foo[1] = 3;  // <---

    printf("foo[0]: %d\n", foo[0]);
    printf("foo[1]: %d\n", foo[1]);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

foo[0]: 4
foo[1]: 3
Run Code Online (Sandbox Code Playgroud)

此代码不会:

#include <stdio.h>
#include <stdlib.h>

void test(int **foo) {
    *foo = malloc(2 * sizeof(int));  // 3.
    *foo[0] = 4;  // 4. <---
    *foo[1] = 3;  // 5. <---
}

int main() {
    int *foo;  // 1.

    test(&foo);  // 2.

    printf("foo[0]: %d\n", foo[0]);
    printf("foo[1]: %d\n", foo[1]);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

foo[0]: 4        // This is only 4 because it was already
                 //   4 from running the previous example
foo[1]: 5308612  // And this is obviously garbage
Run Code Online (Sandbox Code Playgroud)

发生什么了?这个答案非常有用(或者我认为至少是这样),但它没有解决为什么分配工作main但没有test.

这是我对第二个例子中的代码应该如何工作的理解(我在代码中加上脚注来表示我在这里引用的行):

  1. 该计划始于main.我创建了整数点foo,在(为简单起见)地址分配了一个4字节的内存块1000.

  2. 我发送了一个对foo函数的引用test.因此,它1000作为参数传递.

  3. 分配大小(8字节)的两个整数的内存块foo.

  4. 4 存储在地址 1000

  5. 3 存储在地址 1004

那么,我误解了什么,以及如何修复第二个例子中的代码,以便我可以foo在一个test而不是main

谢谢!

Jon*_*ler 8

优先!

你需要:

(*foo)[0] = 4;  // 4. <---
(*foo)[1] = 3;  // 5. <---
Run Code Online (Sandbox Code Playgroud)

没有括号,*foo[0]*(foo[0]),实际上是相同的(*foo)[0],但 *(foo[1])写的是谁知道在哪里.该*运营商结合不太紧密比[]运营商做,所以你必须使用括号.

char *arr[];   // array of pointers to char
char (*arr)[]; // pointer to array of char
Run Code Online (Sandbox Code Playgroud)