An error occurred while passing a pointer to an array of structures

#include <stdio.h> #include <stdlib.h> struct Point { double x; }; void test(struct Point **a, int len) { int i; printf("a = %p\n", a); for (i = 0; i < len; ++i) printf("%f\n", a[i]->x); } int main() { int i; int len = 4; struct Point *P; P = malloc(len*sizeof(struct Point)); for (i = 0; i < len; ++i) { P[i].x = i; printf("%f\n", P[i].x); } printf("&P = %p\n", &P); test(&P, len); return 0; } 

I am trying to pass an array of structures to a function (I want to pass a pointer to an array, not make a copy). When I try to use an array inside a function, I get an access violation. What is the right way to do this? What am I doing wrong? a == &P , so it should work, right?

+7
c function arrays pointers struct
source share
5 answers

Why do you want struct Point ** ? You can rewrite the same as

 void test(struct Point *a, int len) { //some stuff printf("%f\n", a[i].x); } 

and name it like

  test(P, len); 

Therefore, IMHO, the requirement

I want to pass a pointer to an array

also found # .


(#) NOTE. To be strict, here we pass a pointer to the first element of the array, however, the behavior is compared to equal. Thanks to Mr. @alk for the comment.

+5
source share

Passing &p to the test function means that you are passing a pointer to the first element of the array from one element of type struct Point * . Therefore, only a[0] (and therefore a[0]->x ) is valid, and all the other a[i] not available. This will cause undefined behavior.

Change a[i]->x to a[0][i].x or (*a)[i].x to test .

Using a pointer to a pointer in this case is unacceptable. This would be useful if the passed pointer needs to be changed in a function, and this modification is expected to be visible in the caller.

+3
source share

An array must be passed using the struct Point *a parameter. When you increment a , the pointer will move to sizeof(struct Point) .

 void test(const struct Point *a, int len) { ... } 
+1
source share

Other answers offer you better alternatives. But I will put this here to help someone understand why this is wrong.

enter image description here

+1
source share

I want to pass a pointer to an array,

Taking your requirement literally, you do it like this:

 void test(size_t len, struct Point (*a)[len]) { size_t i; printf("a = %p\n", (void *) a); for (i = 0; i < len; ++i) printf("%f\n", (*a)[i].x); } 

And name it as follows:

 size_t len = 4; struct Point * p = malloc(len * sizeof *p); for (i = 0; i < len; ++i) { p[i].x = i; printf("%f\n", p[i].x); } printf("p = %p\n", (void *) p); printf("&p = %p\n", (void *) &p); test(len, &p); 

You can also implement the same functionality (loop through array elements) by choosing the method suggested by Sourav Ghosh answer . Then you pass the pointer to the array 1 st but the pointer to the array itself.

0
source share

All Articles