C pass int array pointer as parameter into a function
In your new code,
int func(int *B){ *B[0] = 5;}
B
is a pointer to int
, thus B[0]
is an int
, and you can't dereference an int
. Just remove the *
,
int func(int *B){ B[0] = 5;}
and it works.
In the initialisation
int B[10] = {NULL};
you are initialising anint
with a void*
(NULL
). Since there is a valid conversion from void*
to int
, that works, but it is not quite kosher, because the conversion is implementation defined, and usually indicates a mistake by the programmer, hence the compiler warns about it.
int B[10] = {0};
is the proper way to 0-initialise an int[10]
.
Maybe you were trying to do this?
#include <stdio.h>int func(int * B){ /* B + OFFSET = 5 () You are pointing to the same region as B[OFFSET] */ *(B + 2) = 5;}int main(void) { int B[10]; func(B); /* Let's say you edited only 2 and you want to show it. */ printf("b[0] = %d\n\n", B[2]); return 0;}
If you actually want to pass an array pointer, it's
#include <stdio.h>void func(int (*B)[10]){ // ptr to array of 10 ints. (*B)[0] = 5; // note, *B[0] means *(B[0]) //B[0][0] = 5; // same, but could be misleading here; see below.}int main(void){ int B[10] = {0}; // not NULL, which is for pointers. printf("b[0] = %d\n\n", B[0]); func(&B); // &B is ptr to arry of 10 ints. printf("b[0] = %d\n\n", B[0]); return 0;}
But as mentioned in other answers, it's not that common to do this. Usually a pointer-to-array is passed only when you want to pass a 2d array, where it suddenly looks a lot clearer, as below. A 2D array is actually passed as a pointer to its first row.
void func( int B[5][10] ) // this func is actually the same as the one above! { B[0][0] = 5;}int main(void){ int Ar2D[5][10]; func(Ar2D); // same as func( &Ar2D[0] )}
The parameter of func may be declared as int B[5][10]
, int B[][10]
, int (*B)[10]
, all are equivalent as parameter types.
Addendum: you can return a pointer-to-array from a function, but the syntax to declare the function is very awkward, the [10] part of the type has to go after the parameter list:
int MyArr[5][10];int MyRow[10];int (*select_myarr_row( int i ))[10] { // yes, really return (i>=0 && i<5)? &MyArr[i] : &MyRow;}
This is usually done as below, to avoid eyestrain:
typedef int (*pa10int)[10];pa10int select_myarr_row( int i ) { return (i>=0 && i<5)? &MyArr[i] : &MyRow;}