C, Pointers, Sizeof

Started by
4 comments, last by Nitage 17 years, 5 months ago
Hi guys, im working on my project again and I found an interesting error. Ive already solved what it is I just need help finding another way of doing what I want. Basicly im passing a pointer around for a string that I call name_ptr. char name[16]; char *name_ptr = name; now in a function that i passed the pointer of name to im trying to do an fgets on it. fgets(name_ptr, size(name_ptr), stdin); Now when I do this, if i use name_ptr as the sizeof it returns what ever the sizeof the datatype which is a pointer, basicly not really more then 2 most times. and if I do *name_ptr theres no data in name_ptr yet so its always zero. Is there any way to pass to sizeof the actuall string size of 16chars with out declaring a fixed string in side of the function thats doing this fgets?
Do or do not there is no try -yoda
Advertisement
You can either initialise the string with a null character in name[15] (and non-null character in name[0]-name[14]) and use strlen, or explicitly pass around the size of the array.
Quote:Original post by Xloner12
Now when I do this, if i use name_ptr as the sizeof it returns what ever the sizeof the datatype which is a pointer, basicly not really more then 2 most times. and if I do *name_ptr theres no data in name_ptr yet so its always zero. Is there any way to pass to sizeof the actuall string size of 16chars with out declaring a fixed string in side of the function thats doing this fgets?


Nope. If you're using C++, use std::string or std::vector or std::tr1::array. If you're in C, you need to pass the size of the array around explicitly when you pass the pointer.

Stephen M. Webb
Professional Free Software Developer

If I go with the null at start and end of the array is there any draw backs, because I like that idea.
Do or do not there is no try -yoda
Nvm, I realized that when I fill up the string the point is still only pointing to that first char slot and not the entire string. I'll just pass around the int equivlent for the size of the string.

Well cool. Thanks guys.
Do or do not there is no try -yoda
Drawbacks:

  • You need to spend time initializing your array so that the only null character in in appears at the end

  • You need to spend time reading every character in the array until you find the null

  • Once you've called fgets() on the array, you've lost the information



char name[16];memset(name,UINT_MAX,sizeof(name));name[15] = 0;char* name_ptr = name;...fgets(name_ptr,strlen(name_ptr)+1, stdin);


Basically, only use this method if you're unable to change the parameter lists of the functions in between allocating the array and using the array.

This topic is closed to new replies.

Advertisement