pointer problems, help!

Noam Mendelson c60b-1eq at web-4h.berkeley.edu
Sat Mar 23 05:34:45 AEST 1991


In article <1991Mar22.082225.24948 at bronze.ucs.indiana.edu> mitchemt at silver.ucs.indiana.edu (Terry Mitchem) writes:
>
>        I am having some major problems getting a piece of code to work.
>It seems that everytime I change the contents of one string, it affects
>another one. For example, when I build the filename below, it gets wiped
>out when I null the members of "target_player". The code is below, and below
>that is the datafile I am using.
>
>void edit_category()
>{
>  struct
>  {
>    char *card_number;
>    char *quantity;
>    char *first_name;
>    char *last_name;
>    char *price_mint;
>    char *price_ex;
>  } target_player;
>
>  char filename[80],carriage_return[5];
>  int infile,bytes;
>
>  *filename=NULL;
>
>  ...misc code deleted...
>
>  *target_player.card_number=NULL; *target_player.quantity=NULL;
>  *target_player.first_name=NULL; *target_player.last_name=NULL;
>  *target_player.price_mint=NULL; *target_player.price_ex=NULL;
>
>  infile=open(filename,O_RDONLY);
>  if (infile==-1) exit(1);
>
>  read(infile,target_player.card_number,5);
>  read(infile,target_player.quantity,3);
>  read(infile,target_player.first_name,21);
>  read(infile,target_player.last_name,21);
>  read(infile,target_player.price_mint,7);
>  read(infile,target_player.price_ex,7);
>}
>----------------------------------------------------------------------------
>Here is the datafile:
>
>8    2  joe                  montana              .75    .40
>9    2  christian            okoye                .20    .10    
>
>        Any and all help is appreciated. I don't seem to be able to get
>anything useful out of K&R to help me. I am compiling with turbo-c.

You declared pointers without assigning them to an address!  Therefore,
the random memory location that each one is pointing to when the struct
is declared is initialized with NULL (a no-no).  Furthermore, you are loading
the data into those random memory locations.
What you need to do is to malloc() memory and assign each of the pointers
to those blocks of memory _before_ you use them.  In your case, however,
it will probably be much easier to declare:
  struct
  {
    short int card_number;
    short int quantity;
    char first_name[40];
    char last_name[40];
    float price_mint;
    float price_ex;
  }
or something along those lines.  This will simplify your code.

===========================================================================
| Noam Mendelson    ..!ucbvax!web!c60b-1eq  | "I haven't lost my mind,    |
| c60b-1eq at web.Berkeley.EDU                 |  it's backed up on tape     |
| University of California at Berkeley      |  somewhere."                |



More information about the Comp.lang.c mailing list