Home > front end >  Difference between int* a and int (*a)[N] in functions?
Difference between int* a and int (*a)[N] in functions?

Time:12-10

I can pass int arrays to both of these functions (1d and 2d arrays). What is the difference between them? With the second function you need to specify the size of the array. Why?

void foo(int *a, int cols) 
void bar(int (*a)[N])

I have a program where I want to pass 2d int arrays to functions. Which is the better one to use and does it matter?

CodePudding user response:

While int* a is is a pointer to int, int (*b)[N] is a pointer to an array of N ints. These are different types, and are not compatible.

For example, b can only point to an array of N elements while a can point to a flat array of any size, if you increment b it will point to the next block of N ints while if you increment a it will just point to the next int.

For a 2D array you should use b. Example:

#define N 5
#define M 5


void bar(int (*a)[N]) { 
        
}

int main() {

    int(*a)[N] = malloc(sizeof *a * M);

    bar(a);
    
}

The above is a 2D array N x M.

CodePudding user response:

The main difference between these methods is the fact that cols is an int argument in the first prototype, whereas it is a constant in the second one. You will need to write the index computations explicitly in the first case and you can use a[row][col] in the second, which will be both simpler and compile to more efficient code.

  • Related