0

Hello I have some trouble with pointer !

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

void test(char **str)
{
    *str = (char *)malloc(sizeof(char) * 2);
    *str[0] = 'b';
    *str[1] = '\0';
}

int     main(void)
{
    char *str;

    test(&str);
    printf("%s\n", str);
    return (0);
}

So I pass a pointer of an non allocated string in my function test, then I allocate my string in the function and try to manipulate it but this code segfault so I guess I miss something on my pointer lesson :)

Can you help me to figure out what is happening here ? thank you a lot !

edit : when I remove my return (0) in the main, the code compile and display my char * ! super weird

decarte
  • 410
  • 1
  • 7
  • 17
  • To avoid array indexing try using this (**str = 'b'; *(*str+1) = '\0';) in your code – Sudipta Kumar Sahoo Feb 29 '16 at 18:44
  • Maybe you were taught otherwise, but [don't cast the result of `malloc()`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). Also, checking the return value is a good idea. – e0k Feb 29 '16 at 18:47

3 Answers3

3

The array subscript operator [] has higher precedence than the indirection operator *. So the assignment to str is effectively this which is incorrect:

*(str[0]) = 'b';
*(str[1]) = '\0';

You need to add parenthesis:

(*str)[0] = 'b';
(*str)[1] = '\0';
dbush
  • 205,898
  • 23
  • 218
  • 273
2

You must write:

(*str)[0]= 'b';

You must first dereference the str and now the indexing will work on the target, the memory allocated by malloc.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
0

Actually, just 'str' itself means he address of character array. But 'str' means the value of str. So the str[0] contains the value of 'b' but as you added '' before str[0] (*str[0]), computer trying to find the value where the address is 'b'. But this address is not allowed for this process. So this program returns segment fault. Thank you.

Jeungwoo Yoo
  • 1,059
  • 1
  • 10
  • 17