>I'm reading in an unknown number of characters into a char pointer using fgets...
Really, are you sure? You might want to consider playing around with a toy program that does what you want to do. The results may surprise you.
>If I have a pointer instead of an array, how do I express the size of it since I don't know the size yet?
sizeof p, but that's probably not what you want since a pointer is 4 bytes and your input is probably more than that. If you're reading an unknown number of characters then why use fgets at all since you have to know the size?
Here were my results based on your description of the problem:
Code:
int main(void)
{ char *p = NULL;
fgets( p, sizeof p, stdin );
printf( "%s", p );
return EXIT_SUCCESS;
}
Result: Big time assertion error in fgets()
Code:
int main(void)
{ char *p = malloc( 255 * sizeof(char) );
fgets( p, sizeof *p, stdin );
printf( "%s", p );
free( p );
return EXIT_SUCCESS;
}
Result: fgets didn't even accept input despite compiling fine.
Code:
int main(void)
{ char *p = malloc( 255 * sizeof(char) );
fgets( p, sizeof p, stdin );
printf( "%s", p );
free( p );
return EXIT_SUCCESS;
}
Result: Reads great, saves 3 characters and a nul. Care to guess why?
Code:
int main(void)
{ char *p = NULL,
array[256];
p = fgets( array, sizeof array, stdin );
printf( "%s", p );
return EXIT_SUCCESS;
}
Result: Works great, but requires a buffer
Conclusion: You might want to reconsider your method of input and/or your method of saving that input.
-Prelude