c - 为结构化指针分配内存

标签 c pointers memory malloc structure

最近正在处理这个练习:

Count the size of each element in an array. Create a function my_count_on_it, which receives a string array as a parameter and returns an array with the length of each string.

结构:

typedef struct s_string_array {
    int size;
    char **array;
} string_array;

typedef struct s_integer_array {
    int size;
    int *array;
} integer_array;

所以正确的答案是:

#include <string.h>

integer_array *my_count_on_it(string_array *a) {
    integer_array *ptr;

    ptr = (integer_array *)malloc(sizeof(integer_array));
    ptr->size = a->size;
    ptr->array = (int*)malloc(ptr->size * sizeof(int));

    for (int i = 0; i < a->size; i++) {
        ptr->array[i] = strlen(a->array[I]);
    }

    return ptr;
}

我知道指针存储某个变量的地址,但我不明白为什么在这种情况下我无法创建 integer_array 的变量类型并执行所有操作(在循环中)它,然后才将其地址存储在integer_array * ptr 中?还有一个问题,如果是这样,为什么我们要创建一个指针 sizeof(integer_array)

例如:

int variable = 5;
int *ptr = &variable;

在这个简单的例子中,我分别创建变量和指针并存储地址。第一个代码中令人困惑的事情是,在我看来,我们只是创建了一个指针,它没有指向某个地址。

最佳答案

why in this case I can't create a variable type of integer_array and do all operations(in the loop) with it, and only then store its address in integer_array * ptr?

那是无效的。如果您创建一个局部变量,如下所示:

integer_array* my_count_on_it(string_array* a) {
    integer_array local_arr;

    // ...

    return &local_arr;
}

那么你就不能返回指向它的指针,因为该变量只有在定义的函数返回之前才有效。它在函数的栈上,当函数返回时,函数的栈就失效了。因此,返回类似 &local_arr 的内容是错误的,因为它引用了从函数返回后不应使用的某些内存(这也是未定义的行为)。正确的方法是使用 malloc(),它在堆上分配内存,该内存可以在程序中的任何其他地方使用,并且不会自动释放(您必须使用以下命令手动释放内存) free())。

if so why we are creating a pointer sizeof(integer_array)?

这只是因为您想为刚刚使用 typedef 定义的结构体 integer_array 分配足够的空间。这不是指针本身的大小,而是该指针指向的内存块的大小。

The confusing thing in the first code is it seems to me like we are creating only a pointer, which is not pointing to some address.

最初,在声明时,指针并未指向有效的内容。然后,执行此操作后:

ptr = malloc(sizeof(integer_array));

指针现在指向堆中的某个有效地址。在该地址,malloc() 保留了足够的空间来保存 integer_array 结构大小的变量。

=== Before malloc(): =========================

ptr = ????? -------> INVALID

=== After malloc(): ==========================

                      Memory
                      |   ...         | ...
ptr = 0x120 ------->  +---------------+ 0x120
                      | space for     | 
                      | integer_array |
                      +---------------+ 0x128
                      |   ...         | ...

还有一件事:转换 malloc() 的返回值是不必要的,也是错误的,see here以获得解释。

关于c - 为结构化指针分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61357178/

相关文章:

c - C-如果我不将窗口最小化超过15分钟,程序就会崩溃

java - java 的 sleep() 和 c 的 sleep() 之间有什么区别?

c - 如果使用函数 i 返回一个在其中创建的指针,函数结束后指针在函数中创建的 4 个字节是否会被释放?

c++ - 第二个 IntObject.getValue() 的返回值错误

pointers - Go内存地址改变

c++ - 在销毁对象之前锁定对象的互斥体将释放内存或其他一些意外的

c - 变量中存在无法解释的垃圾值

C 编程 pthread 打印段错误

c - 为什么 strcmp 或 strncmp 不适用于 C 编程语言?

c - 通过递归将指针传递给结构(迷宫求解)