简体   繁体   中英

Getting the address of a statically allocated array into a pointer inside a struct

The simplified version of my code is the following:

struct args {
    int p;
    int *A;
};

typedef struct sort_args sort_args;

void func(int A[], int p) 
{
    args new_struct = {&A, p};
    args *args_ptr = &new_struct;
}

I'm trying to convert a statically (I think that's the term) allocated array into a pointer, but the compiler keeps throwing these warnings:

warning: initialization makes integer from pointer without a cast [enabled by default] args new_struct = {&A, p, r};

warning: (near initialization for 'new_struct.p') [enabled by default] warning: initialization makes pointer from integer without a cast [enabled by default] warning: (near initialization for 'new_struct.A') [enabled by default]

What am I doing wrong?

You got the parameters backwards.

args new_struct = {&A, p};

=>

args new_struct = {p, A};

You need to initialize the members of a struct in exactly the same order as they appear in the structs declaration, or you need to use named syntax like this:

args new_struct = { .A = A, .p = p };

But this is usually only used to improve code clarity with larger structs who have more members.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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