#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
char *str;
int len;
printf("Enter the expression: \n");
scanf("%[^\n]", &str);
printf("%s\n", str);
len = strlen(str);
printf("%d\n", len);
}
I am trying input a string into a string pointer but it keeps giving me a segmentation error, however when i initialize it as char array it works fine.
>Solution :
It looks like you are trying to get scanf to allocate the necessary memory for the string. That option is only available as an extension in some implementations, but here’s how that would work:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) { // note the proper declaration
char *str = NULL;
int len;
printf("Enter the expression: \n");
if(scanf("%m[^\n]", &str) == 1) { // add `m` to malloc memory for the string
printf("%s\n", str);
len = strlen(str);
printf("%d\n", len);
free(str); // and `free` it after use
}
}