pointer problems, help!

D'Arcy J.M. Cain darcy at druid.uucp
Sat Mar 23 10:13:35 AEST 1991


In <1991Mar22.082225.24948 at bronze.ucs.indiana.edu> Terry Mitchem writes:
>        I am having some major problems getting a piece of code to work.
>  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;
Don't do this.  NULL does not mean 0 on all systems (although the opposite
*is* true) but may instead mean "(void *)(0)."  Use "*filename = 0" or
"filename = '\0'" for this.  Better yet see my comments below and don't
bother with this line at all.

>  strcat(filename,".\\"); strcat(filename,category.brand);
>  strcat(filename,"\\");  strcat(filename,category.type);
>  strcat(filename,"\\");  strcat(filename,category.year);
>  strcat(filename,"\\");  strcat(filename,category.other);
>  strcat(filename,"\\data");
I assume category is a structure of strings or string pointers defined
previously.  Why not use:
  sprintf(filename, "./%s/%s/%s/%s/data",
    category.brand, category.type category.year, category.other);

Side note: DOS accepts the forward slash and the above makes you portable
to Unix.

>  *target_player.card_number=NULL; *target_player.quantity=NULL;
etc.
Even assuming that NULL is 0, you can't do this.  The strings you are
writing to do not have any space allocated to them.  They are simply
uninitialized pointers.  You either have to malloc space for each
pointer or declare the structure elements as follows:
    char card_number[6];
etc.  Note the extra character for the 0 terminator.

>  read(infile,target_player.card_number,5);
etc.
Same problem as above.  The fix for above will fix this.  You may also
want to check out fscanf(3) to fill the structure all at once.  Note
that it may not be suitable for you, I don't know what your data file
specs are from looking at two lines from it, but it may simplify the
input.

>        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.

Check out the FAQ for comp.lang.c.  It explains the use of pointers very
well and talks about a lot of misconceptions regarding them.

-- 
D'Arcy J.M. Cain (darcy at druid)     |
D'Arcy Cain Consulting             |   There's no government
Toronto, Ontario, Canada           |   like no government!
+1 416 424 2871                    |



More information about the Comp.lang.c mailing list