简体   繁体   中英

passing array (not pointer) to a struct in c

I am trying many ways to pass an array to a functions but it keeps determining the type I pass into the function as pointer. Could anyone please help?

typedef struct Process 
{
int id;
int arrival;
int life;
int address[10]; //contain address space(s) of the Process
struct Process *next;
} Process_rec, *Process_ptr;

Process_ptr addProcess(Process_ptr old,int a, int b, int c, int d[10]) 
{
...
Process_ptr newProcess = (Process_ptr) malloc(sizeof(Process_rec));
newProcess->address = d;
...
}

main()
{
int address[10] = { 0 };
...
for loop
{
address[i] = something
}
p = addProcess(p, id,arrival,life,address);

I attempted to change the array in constructor to pointer, however, all the process I created would end up having the same array as the last Process I create.

If I use the above code, which should paste the array address[10] in main to function and then from function to struct. I keep encountering an error "incompatible types when assigning to type 'int[10]' from type 'int *'", which means it considers the array d[10] in function as pointer, but I did use array instead of pointer ?!?

As explained by @Keith Thompson, if you define:

Process_ptr addProcess(Process_ptr old,int a, int b, int c, int d[10])

...then d is actually a pointer, ie completely equivalent to int *d .

What you want to do is this:

memcpy(newProcess->address, d, 10*sizeof(d[0]));

By the way, you don't need to cast the result of malloc . See Do I cast the result of malloc?

d is a pointer as above, and the core should be:

newProcess->address = d;

address is a static array, not pointer. array name means the array's address, and it can't be modified.

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