Man, pointers continue to give me trouble. I thought I understood the concept.(Basically, that you would use *ptr when you want to manipulate the actual memory saved at the location that ptr points to. You would just use ptr if you would like to move that pointer by doing things such as ptr++ or ptr–.) So, if that is the case, if you use the asterisk to manipulate the files that the pointer is pointing to, how does this work:
char *MallocAndCopy( char *line ) {
char *pointer;
if ( (pointer = malloc( strlen(line)+1 )) == NULL ) {
printf( "Out of memory!!! Goodbye!\n" );
exit( 0 );
}
strcpy( pointer, line );
return pointer;
}
malloc returns a pointer, so I understand why the “pointer” in the if condition does not utilize the asterisk. However, in the strcpy function, it is sending the CONTENTS of line to the CONTENTS of pointer. Shouldn’t it be:
strcpy( *pointer, *line);
????? Or is my understanding of pointers correct and that is just the way that the strcpy function works?
A C-style string is an array of character bytes. When you pass an array around as a pointer to the array type, the pointer contains the address of the first element of the array.
The
strcpyfunction takes the pointer to the firstcharof the source array (which is the start of the string) and the pointer to the firstcharin the destination array, and iterates over the source until it reaches a'\0'character, which terminates the string.That’s also why when you call
malloc, the size that you pass to it isstrlen(line)+1, because you need to allocate one more byte for the termination character (as far as I know).