thedeg123
thedeg123

Reputation: 438

C how to pass pointer to struct array pointer

I realize this is most likely a syntax issue, however, I have a struct:

struct pixel{
int pixel_num;
double lowest_dist;
int centroid;
double * location;
};

and an array of these structs struct pixel * pixel_data[10] and a method: void foo(double ** arr) and am trying to pass the address of the location pointer in an instance of the struct to update the pointer in the method foo.

I attempted to pass it like so foo(&(pixel_data[0]->location)) however this is clearly not correct as when I run through gdb the *arr values are different in foo than what they were in main() where I call foo.

Thanks.

An Example:

#define DIMENSIONS 5
//Struct is declared in header.
//max 10 pixels
struct pixel * pixel_data[10];

int main(){
    double newLoc[DIMENSIONS]={1.1,2.2,3.3,4.4, 5.5};
    pixel_data[0]=add_pixel(newLoc);
    update_centroid_location(&(pixel_data[0]->location), 0, DIMENSIONS);
}
void update_centroid_location(double **centroid, int centroid_num, int numpix){
    double * old_cent=malloc(DIMENSIONS*sizeof(double));
    if(!old_cent){
    perror("couldnt allocate memory");
    exit(4);
    }   
    for(int i=0;i<DIMENSIONS;i++){
    old_cent[i]=*centroid[i]; //segfaults here as cannot access memory address
    }   
}
struct pixel * add_pixel(double * location){
    struct pixel * new=malloc(sizeof(struct pixel));
    if(!new){
    perror("Could not allocate space for pixel");
    exit(4);
    }   
    new->lowest_dist=DBL_MAX;
    new->centroid=0;
    new->location=location;
    return new;
}

Upvotes: 1

Views: 73

Answers (1)

PeterT
PeterT

Reputation: 8294

In the line old_cent[i]=*centroid[i]; there is a misunderstanding about operator precedence.
The * operator has a lower precedence than the [].
So you are essentially doing old_cent[i]=*(centroid[i]);

Try to use parenthesis to explicitly express that you want to first dereference then add the offset for the second dereference like so:

old_cent[i]=(*centroid)[i];

Upvotes: 3

Related Questions