pointer to pointer that points to a char array

This is a discussion on pointer to pointer that points to a char array within the C Programming forums, part of the General Programming Boards category; Hello, I have been experimenting with pointer to pointers that point to an int. That bit I understand. However, when ...

  1. #1
    UK2
    Join Date
    Sep 2003
    Posts
    112

    pointer to pointer that points to a char array

    Hello,

    I have been experimenting with pointer to pointers that point to an int. That bit I understand.

    However, when I try and dereference the pointer to get the string value, the program crashes.
    Code:
    void error_msg(char **msg)
    {
                    printf("**msg: %s\n", **msg); //dereference to get the string
    	printf("*msg: %p\n", *msg); //display the address
    }
    I am calling the function like this:
    Code:
    	char msg_error[] = "Message";
    	char *msg = msg_error;
    	error_msg(&msg);
    When I was experimenting with integers I was doing like this:
    Code:
    void error_int(int **myInt)
    {
                    //**myInt dereferences and *myInt displays the address
    	printf("*myInt address: %p value: %p\n", myInt, *myInt);
    	printf("**myInt address: %p value: %d\n", *myInt, **myInt);
    }
    I guess for arrays you have to do something different.

    Many thanks,

    Steve

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,702
    When you have a
    char **msg
    then type of
    *msg == char*
    and the type of
    **msg == char

    So you are using %s format specifier, but passing in a char. printf() is interpreting the char you passed in as a pointer to a null-terminated array of chars. Boom.

    gg

  3. #3
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,058
    The %s conversion specification expects a pointer to a NULL terminated string but the argument you supplied is **msg which is a char.
    Either change the conversion specification to %c or make the argument to printf() a pointer to char *msg.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 04:36 AM
  2. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 10:54 AM
  3. typedef for pointer to array of char
    By curlious in forum C++ Programming
    Replies: 1
    Last Post: 12-13-2003, 04:21 PM
  4. Creating 2D arrays on heap
    By sundeeptuteja in forum C++ Programming
    Replies: 6
    Last Post: 08-16-2002, 12:44 PM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21