Pointer

Hi all

I have a question regarding pointer. Hope someone can help me. Below are my codes, I have tagged:

========================================

int main (int argc, const char * argv[]) {

if ( fp == NULL )
DoError( "Couldn't open file!" ); //<<<<
}

void DoError( char *message ) { // <<<<
printf( "%s\n", message );
exit( 0 );
}
=========================================

Looking at the //<<<< line of codes which I have tagged, can someone explain to me why void DoError (char *message) function requires a pointer (*message)?

Thanks and much appreciated
Without being able to gauge your experience, I'll approach it from the very basics up ;-)

1. The function DoError() needs to know what you want displaying, so you have to give it a string parameter, which it can then use.

2. C-style strings are formed as arrays of char, for example char aString[];.

You can either access the content by using the [] operator, for example aString[0] would be the first character of the string.

Another way of accessing a C-style array is via a pointer to the first element (in our case, the 1st character), which you can then use to move from array element to element (character to character). A pointer to the first element of our aString array would be declared using the address-of operator '&' of the 1st element [0], char* aPointer = &aString[0];.

Additionally, a handy shortcut with arrays is that you can use just the array name to mean the address of the first element, so our pointer declaration and assignment can also be written char* aPointer = aString;, which will have exactly the same result.

What the 1st highlighted line is doing is using the shortcut version to send the address of the 1st element of the temporarily created string "Couldn't open file!".

Cheers,
Jim
Thanks Jim for the very detailed explanation.
Topic archived. No new replies allowed.