I’m trying to pass a char* and change it in another function but somehow it keeps giving seg fault.
Full code is:
#include <stdio.h>
void getString(char** str) {
*str[0] = '$';
char c;
int i = 1;
while ((c = getchar()) != '$') {
if (c != '\n') {
*str[i-1] = c;
i++;
}
}
*str[i] = '\0';
}
int main (int argc, char *argv[]) {
char* str = (char*)malloc(200 * sizeof(char));
while (1) {
getString(&str);
printf("String: %s\n",str);
}
return 0;
}
If I take the * from str[0] = ‘$’ it gives a warning passing pointer to integer.
Dunno where I’m messing up.
the array index , [], operator has lower precedence than the dereference operator, *
So you’d have to change your code to do
In your case, you don’t need to pass in the address of your pointer, just pass the pointer:
And access it as
Since you’re using malloc(), be sure to add
#include <stdlib.h>If you didn’t cast the return value of malloc, which is not needed in C, you should have
gotten a warning regarding this.