The problem is you are using a pointer before it has been initialized. It does not yet point at valid memory. These leads to program crashes or other kinds of unexpected behavior, such as "segmentation faults".
So you should edit it to:
char* my_string = malloc(size+1);
The %c
format specifier is used whenever we want to be specific that the variable that we are going to printf
or scanf
is of type char
.
On the other hand the %s
format specifier is used to specify to the printf
or scanf
functions that contents of the address that is specified as the next parameter are to considered as string
.
You are taking char
as input, not the whole string
.
scanf("%s",&a[i]);
, will be scanf("%c",&a[i]);
printf("%s",a[3]);
, will be printf("%c",a[3]);
printf("%s",a[2]);
, will be printf("%c",a[2]);
The following code worked fine:
#include<stdio.h>
#include<stdlib.h>
int main(){
char* a = malloc(size+1); // where size is max string length
int i;
printf("\n enter value ");
for (i=0;i<5;i++){
printf("%d Name :\n",i);
scanf("%c",&a[i]);
printf("%c\n",a[i]);
}
printf("%c\n",a[2]);
printf("%c\n",a[3]);
free(a);
}