0

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 ?!?

Toan Le
  • 412
  • 1
  • 6
  • 17
  • 1
    C does not support function parameters of array type. Read section 6 of the [comp.lang.c FAQ](http://www.c-faq.com/). – Keith Thompson Mar 24 '15 at 23:40
  • @KeithThompson I guessed that was the case and changed the address in struct to pointer type instead, however, I ended up having and the process point to the same address because it all point to address array in main. And address in main will keep changing until the last Process is read. Could you suggest how I can efficiently copy the values? I can do a loop but that does not seem like the right way. – Toan Le Mar 24 '15 at 23:46

2 Answers2

2

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, i.e. 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?

Community
  • 1
  • 1
juhist
  • 4,210
  • 16
  • 33
  • thank you! I added newProcess->address = malloc(sizeof(int) * 10); memcpy(newProcess->address, d, 10*sizeof(d[0])); and it works as intended!! I know memory manipulation methods are pretty much the basic stuffs in C and I will definitely explore them later – Toan Le Mar 25 '15 at 00:08
0

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.

Cherry
  • 153
  • 11