Reputation: 17
I'm very new to programming so I'm sorry if this will sound as a bad question.
My Code:
#include <stdio.h>
void Order(int *waiterList){
printf("Number is %d", *waiterList[0][1]);
}
int main(){
int waiterList[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
Order(&waiterList);
return 0;
}
This code is giving me this error:
pointer.c: In function 'Order':
pointer.c:5:39: error: subscripted value is neither array nor pointer nor vector
printf("Number is %d", *waiterList[0][1]);
pointer.c: In function '`enter code here`main':
pointer.c:13:8: warning: passing argument 1 of 'Order' from incompatible pointer type [-
Wincompatible-pointer-types]
Order(&waiterList);
pointer.c:3:6: note: expected 'int *' but argument is of type 'int (*)[3][3]'
void Order(int *waiterList){
Sorry I've never used array before but our final project is requiring us to use array and I'm finding it difficult to understand the articles I found on google... Hope you could help a student out, It's also my first time posting here because I'm kinda desperate.
Upvotes: 0
Views: 43
Reputation: 409166
Arrays decay to a pointer to its first element, for a generic array a
it decays to &a[0]
.
In the case of an arrays like your waiterList
in the main
function, when it decays to a pointer to its first element (&waiterList[0]
) it will have the type "pointer to an array". More specifically for waiterList
the type becomes int (*)[3]
. Which has to be the type of the argument for the Order
function:
void Order(int (*waiterList)[3]){
printf("Number is %d", waiterList[0][1]);
}
You call it simply passing the array as any other variable, no pointer or address-of operator needed:
Order(waiterList);
Upvotes: 0
Reputation: 134286
The simple way to achieve this would be
#include <stdio.h>
void Order(int waiterList[3][3]){ // receive an array of type `int [3][3]`
printf("Number is %d", waiterList[0][1]);
}
int main(){
int waiterList[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
Order(waiterList); // just pass the array name
return 0;
}
If you must use pointers, use proper types:
#include <stdio.h>
void Order(int (*waiterList)[3][3]){ // pointer to an array of type `int[3][3]`
printf("Number is %d", (*waiterList)[0][1]);
}
int main(){
int waiterList[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
Order(&waiterList); // pass the address of the array
return 0;
}
Upvotes: 1