0
#include<stdio.h>

int main()
{
    char *string1;
    scanf("%s",string1);
    printf("\n\nstring 1 is %s\n",string1);
} 

whenever I run this program it takes the input, but then stops working. How do I take direct inputs in char pointers in C ?

2 Answers2

0

You didn't allocate memory for string1.

You can do it using malloc() function this way:

 size_t string_size = 16;
 char *string1 = (char*)malloc(string_size * sizeof(char));

This, the length of provided string should not exceed 15 characters.

Enrico
  • 120
  • 5
  • So this means that we cannot allocate dynamic memory during while entering a string to a char pointer. ? like, before entering some string the user must specify its length before hand during runtime ? – Devansh Shah Aug 27 '20 at 07:47
  • In that case you have already declared variable `string1`. In that case please just type `string1 = (char*)malloc(string_size * sizeof(char));`. And do not forget to free allocated memory by calling `free(string1)` before the end. – Enrico Aug 27 '20 at 07:52
  • We can dynamically allocate the memory buffer long enough to store the string. Or we can do this statically in char array, as @paladin proposed. – Enrico Aug 27 '20 at 07:54
0

You need to allocate memory for your string.

#include<stdio.h>

int main()
{
    char string1[100];
    scanf("%s",string1);
    printf("\n\nstring 1 is %s\n",string1);
}

PS Strings in C are just arrays of chars, terminated with '\0' (null).

paladin
  • 765
  • 6
  • 13