0
#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.

  • 2
    Hint: where is `str` pointing? – dbush Jan 20 '23 at 17:19
  • 1
    Welcome to Stack Overflow. In your own words, where the code says `char *str;`, exactly what do you think this means? What is your understanding of what a pointer is? **Where** do you think this pointer is pointing, and why? What do you expect to happen, if data is written to that location? – Karl Knechtel Jan 20 '23 at 17:19
  • 1
    I think the declaration of `main` would be the first thing a normal C compiler would complain about. Sam: What is the name of the compiler you use? – Ted Lyngmo Jan 20 '23 at 17:20
  • `str` is of type `char *`, so `&str` is of type `char **`, but the `%[` conversion specifier needs a `char *`, and you are giving it a `char **` – William Pursell Jan 20 '23 at 17:26
  • 1
    sam tenison, Save time and enable all warnings. – chux - Reinstate Monica Jan 20 '23 at 17:28
  • @WilliamPursell Thank You so much, I just grasped that it was all because it was a double pointer.I am a student and what you pointed out about %[ was new to me, so thanks a lot. – sam tenison Jan 20 '23 at 17:37

2 Answers2

3

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
    }
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
2

This is because you are using the scanf function to write to an uninitialized pointer str. The & is also uneeded for passing a pointer for scanf. A better way to handle the input would be to use fgets() or getline() and allocating memory dynamically using malloc() to store the input string.

xingharvey
  • 131
  • 6