Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
Say you have
void foo ( const char *param );
You can call it with ALL of these
char buff[100];
const char cbuff[] = "hello";
char *pbuff = buff;
const char *pcbuff = cbuff;
foo ( buff );
foo ( cbuff );
foo ( pbuff );
foo ( pcbuff );
foo( "hello world" );
In the context of a function formal parameter (or a prototype), what it is telling you is that the function will NOT change it.
void bar ( const int *p, int *q ) {
*p = 0; // NOT allowed, p is a pointer to const
*q = 0; // this one is OK
}
It means that whatever was in your array before the call will still be there after the call.
What you call it with doesn't have to be const as well.
Similarly, when you call a function expecting an int pointer (for example), then this is what it usually means
int result;
func ( &result );
Now you can declare a pointer it you want, but you need to initialise it.
int result;
int *pa = &result;
func ( pa );
But this is definitely wrong
int *pa;
func ( pa );
Wherever you have a pointer, you need to be thinking about where the memory is, and have you initialised it to point to some suitable memory. Simply declaring variables with the correct type will keep the compiler from complaining (sure the types are right), but it will always blow up as soon as you run it.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
You declare your strings as char arrays.
When you pass your strings to a function, they will be compatible with "const char *" without you having to do anything special.
Just look at how you use strcpy() for example.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
Probably the "\n" which is at the end of the line returned by fgets().
Remove the \n (plenty of examples of how to do this are around).
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
Do you call any other input routines like say scanf ?
Because that can mess you up as well.
Eg.
scanf( "%d", &myint );
fgets( buff, sizeof buff, stdin ); // this will "appear" to be skipped.
Ideally, you should use fgets() for ALL input, then use say sscanf(), or whatever else to parse the input.
But in the absense of that, try calling this between scanf() and fgets() calls.
int skipToEOL ( FILE *s ) {
int ch;
while ( (ch=fgetc(s)) != EOF && ch != '\n' );
return ch;
}
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953