문제

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top