c - How to access a structures' members outside of its original function? -
i working on project creating structures inside of separate function main()
. after being created , added member (variable) information structure variable, need able return
pointer structure in can access reference , printing.
i including code , please simple possible new structures.
#include <stdio.h> #include <stdlib.h> #include<string.h> typedef struct _car { char color[20]; char model[20]; char brand[20]; int year; struct _car *eptr; } car; car* readcars(char* filename); /* * */ int main(int argc, char** argv) { car *cars; car *eptr; cars = readcars(argv[1]); printf("%s%s%s%s", cars->color, cars->brand, cars->model, cars->color); return (exit_success); } car* readcars(char* filename) { file *file = fopen(filename, "r"); int year; char color [20], model [20], brandx[20]; car car1; car car2; car *carptr; car *car2ptr; if (file == null) { printf("file cannot opened\n"); } while(file != eof) { fscanf(file, "%s%s%s%d", color, model, brandx, &year); strcpy(car1.color, color); strcpy(car1.model, model); strcpy(car1.brand, brandx); car1.year = year; carptr = &car1; fscanf(file, "%s%s%s%d", color, model, brandx, &year); strcpy(car2.color, color); strcpy(car2.model, model); strcpy(car2.brand, brandx); car2.year = year; car2ptr = &car2; if (fscanf(file, "%s%s%s%d", color, model, brandx, &year) == eof) { break; } } return carptr; }
to answer main question in post, in car* readcars(char* filename)
function, you're storing address of local variable pointer
carptr = &car1;
and trying return
it
return carptr;
in case, readcars()
function finisihes execution, existence of car
ceased , you'll invoking undefined behaviour accessing returned pointer.
if want memory valid outside scope of it's allocation (in case, outside readcars()
function), need allocate same using dynamic memory allocation, example, malloc()
, family.
fwiw, once you've done using returned pointer, need free()
memory avoid memory leak.
that said,
- you never effectively checked success of
fopen()
or offscanf()
. if either of them failed, continuing normally ideal scenario invoking ub. while ( !feof (fp) )
bad- pointer arithmetic(s) in code is(are) meaningless.
- you've got syntax errors...and maybe more.
Comments
Post a Comment