I'm trying to allocate a string in one function and return it through a pointer of type char **
. If I just do the trivial thing of creating a pointer of type char **
, passing it to a function and letting the function changing the value to the pointer to the string, the program compiles but returns Program returned: 139
.
However, if I simply assign a value before calling the function, it works!
#include <stdio.h>
#include <stdlib.h>
#include<stdbool.h> // Include bool type
void getString(char **str_ptr){
char * my_str = "String I passed." ;
*str_ptr = my_str ;
}
void printMyStr(char **str_ptr){
int i = 0;
char *str = *str_ptr;
printf("Print starts \n\t" );
// looping till the null character is encountered
while(str[i] != '\0')
{
printf("%c", str[i]);
i++;
}
printf("\nPrint ends \n" );
}
int main() {
char *str = "My great String";
char **str_ptr;
str_ptr = &str; \\ If this is commented, errors with 139
getString(str_ptr);
printMyStr(str_ptr);
return 0;
};
The above program returns 0
outputs
Print starts
String I passed.
Print ends
However if I comment out the line str_ptr = &str;
, then it returns 139
and prints nothing.
So, why does it fail and when I comment that line?
And why does it work with that line? How does that line change anything (but still "String I passed." is what is outputed)