简体   繁体   English

如何分配内存并取消引用结构中的数组数组?

[英]How to allocate memory and dereference an array of arrays within a struct?

I was wondering how I would access a double pointer inside of a struct, for example:我想知道如何访问结构内的双指针,例如:

typedef struct Example {
   char **set;
   int size;
 }Example;

The struct is called inside the function as:该结构在函数内部被调用为:

struct Example exmpl;

If I needed to create a new array within that array of arrays, how would I call it in a function/main?如果我需要在该数组数组中创建一个新数组,我将如何在函数/main 中调用它? Or is it just the same as regular, exmpl->set ?或者它与常规的exmpl->set吗?

It doesn't matter what the type of set is, you access it with exmpl.set . set的类型无关紧要,您可以使用exmpl.set访问它。 If you need to access a single element it would be exmpl.set[0][0] for example.例如,如果您需要访问单个元素,它将是exmpl.set[0][0]

If you need to allocate memory for it, you need to allocate memory for the outer array and then for each inner array independently, like this to create an array of 10x20:如果需要为其分配内存,则需要为外部数组分配内存,然后为每个内部数组独立分配内存,像这样创建一个 10x20 的数组:

struct Example exmpl;
exmpl.set = malloc(10 * sizeof(char*));       // 10 "arrays" in the set
for (int i = 0; i < 10; i++)
    exmpl.set[i] = malloc(20 * sizeof(char)); // 20 chars within each "array"

Then for setting each element's value:然后设置每个元素的值:

for (int i = 0; i < 10; i++)
    for (int j = 0; j < 20; j++)
        exmpl.set[i][j] = calculate(i, j);

And, an array and a pointer are different, so what you have here is a pointer to a pointer to char (which works similarly to a 2-dimensional array of chars)而且,数组和指针是不同的,所以这里有一个指向 char 指针的指针(其工作方式类似于二维字符数组)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM