De-referencing char pointer run-time error

Question

Why does the below code cause a run-time crash?

The code itself is not very useful, but , by creating a pointer to a char pointer and pointing to string literals in main, passing this pointer to my function and trying to read the strings causes problems. Why is that exactly?

By creating an array of strings instead in main however (commented out) , there are no problems in passing and reading the strings. Thanks in advance for your knowledge.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* GetString(char** strs, int strsSize);

char* GetString(char** strs, int strsSize)
{
    return *strs;
}

int main()
{

    char** stringArr = {"ab", "abc", "abcd"};
    //char* stringArr [] = {"ab", "abc", "abcd"};

    char* resultStr;
    resultStr = GetString(stringArr, 3);

    printf("%s\n", resultStr);

    return 0;
}

Show source
| C   | string   | char   | pointers   2017-01-04 16:01 1 Answers

Answers ( 1 )

  1. 2017-01-04 16:01

    The initializer for stringArr is not valid. You have a pointer to a pointer, not an array. A pointer cannot be initialized with the {} syntax.

    When compiling with -Wall -Wextra, the following warnings are produced:

    /tmp/x1.c: In function ‘main’:
    /tmp/x1.c:15: warning: initialization from incompatible pointer type
    /tmp/x1.c:15: warning: excess elements in scalar initializer
    /tmp/x1.c:15: warning: (near initialization for ‘stringArr’)
    /tmp/x1.c:15: warning: excess elements in scalar initializer
    /tmp/x1.c:15: warning: (near initialization for ‘stringArr’)
    

    The commented out declaration you have is the correct one.

    Both declarations are valid to be passed to GetString because an array decays into a pointer to the first element when passed to a function. However, a pointer and an array are not the same thing.

◀ Go back