简体   繁体   中英

Passing and assigning pointer in C

I'm having trouble on how to assign information while using a pointer.

I can't assign any values in the readName function. and can you check if I malloc the structs correctly? OR Is there another way to do this without changing the struck and the function parameter?

typedef struct name
{ 
    char info[];
    int number;
    //some more codes
} name;

typedef struct Data
{
    name ** n;
    //some more codes
} Data;


int readName(FILE *const fp, name **const names)
{
    (*names)->number = 1; // no idea what to put here to store
    strcat ((*names)->info, "aBC");
    //codes
}

int read(FILE *const fp, Data *const data)
{
    data->n = malloc(sizeof(name*)*1);   // am I mallocing correctly?
    data->n[0]=malloc(sizeof(name));
    i = readName(fp, &data->n[Data->n]);
    //codes
}

int main ()
{
    Data * d;
    d = malloc (sizeof (Data));
    i = read(fp, d);  //assume fp is decleared
    //codes that usses the struct
}
  data->n = malloc(sizeof(name*)*1);   // am I mallocing correctly?
  data->n[0]=malloc(sizeof(name));

you have only allocated space for 1 pointer data->n = malloc(sizeof(name*)*1); therefore you have 1 pointer to a name struct.

i = readName(fp, &data->n[filep->ncards]);

but then you do the above, you can only do &data->n[0] you cannot do &data->[1] or higher subscripts. if you want more than 1 pointer to pointer to name, you must allocate space for the pointer and then make the pointer point to some valid memory.

try this

data->n = malloc((struct name*)how many pointers you want); 
for(int i =0;i<how many pointers you want;i++)
data->n[i] = malloc(sizeof(struct name));

from you code since its not complete, I think ncards = how many pointers you want.

int readName(FILE *const fp, name **const names)
try
int readName(FILE *const fp, name ** names)

you wont be able to change data through a const** pointer, remove the const and try again

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM