简体   繁体   English

通过传递给函数的指针修改结构数组

[英]Modifying a structure array through a pointer passed to a function

I am trying to pass a structure array pointer and a pointer to a structure array pointer into a function and then have it modified rather than using a return. 我试图将一个结构数组指针和一个指向结构数组指针的指针传递给一个函数,然后对其进行修改,而不是使用返回值。

This example code is indeed pointless, its just a learning example for me. 这个示例代码确实毫无意义,对我来说只是一个学习示例。

Basically I want to create array[0]...array[1]..array[2] and so on and have a pointer that points to these while using a different index...such as array_ref[2] points to array[0] and array_ref[3] points to array[1]. 基本上,我想创建array [0] ... array [1] .. array [2]等,并在使用不同的索引时有一个指向这些的指针...例如array_ref [2]指向array [0]和array_ref [3]指向array [1]。

The code below compiles, but immediately crashes. 下面的代码可以编译,但立即崩溃。 Any suggestions? 有什么建议么?

typedef struct unit_class_struct {
    char *name;
    char *last_name;
} person;




int setName(person * array, person ***array_ref) {
   array[0].name = strdup("Bob");
   array[1].name = strdup("Joseph");
   array[0].last_name = strdup("Robert");
   array[1].last_name = strdup("Clark");

*array_ref[2] = &array[0];
*array_ref[3] = &array[1];

    return 1;
}



int main()
{
    person *array;
    person **array_r;

   array = calloc (5, sizeof(person));
   array_r = calloc (5, sizeof(person));

   setName(array,&array_r);

    printf("First name is %s %s\n", array_r[2]->name, array_r[2]->last_name);
    printf("Second name is %s %s\n", array_r[3]->name, array_r[3]->last_name);

    return 0;
}

You are allocating an array of structures but declaring an array of pointers. 您正在分配结构数组,但声明了一个指针数组。

Calloc() and malloc() return a void * object that can be assigned to everything. Calloc()和malloc()返回一个可以分配给所有对象的void *对象。 So, even with -Wall your program will compile with no warnings. 因此,即使使用-Wall您的程序也将在没有警告的情况下进行编译。

However, when it runs, it tries to deal with what you said was an array of pointers, in fact, an array of pointers to pointers to pointers. 但是,当它运行时,它会尝试处理您所说的指针数组,实际上是指向指针的指针数组。 None of these pointers are ever created. 这些指针均未创建。 All you start with are one-level pointers to an array of objects. 您所开始的只是指向对象数组的一级指针。 Depending on what you really want, you may need something more like... 根据您的实际需求,您可能需要更多类似...

    array_ref[2] = &array[0];
    array_ref[3] = &array[1];

    return 1;
}


int main()
{
    person *array, *array_r_real;
    person **array_r;

    array = calloc(5, sizeof(person));
    array_r_real = calloc(5, sizeof(person));
    array_r = calloc(5, sizeof(struct unit_class_struct *));
    int i;
    for (i = 0; i < 5; ++i)
        array_r[i] = &array_r_real[i];

    setName(array, array_r);

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

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