EXPLANATION
In your code, you have declared two char *
pointers char *month
and char *string
, and trying to store string values in them. You have to understand that these two are mere pointers. All they can store are memory addresses to char
arrays. It is true that an array variable is interchangeable with a pointer in C. But an array declaration also involves a size attribute.
When you declare a character array as:
char str[10];
It actually reserves a block of size 10 in memory, implicitly creates char *str
, and stores the base address of the newly created block in str
. But when you just declare char *str
, all it does is create a pointer. This doesn't have any associated memory block for the array.
That's why you have to declare a character array of some size before storing strings in it with scanf()
. Or you have to dynamically allocate memory with calloc
or malloc
after declaring the char *
pointer. Only then can you store a string input in it.
I have modified your code to work properly. It produces the desired output now. Hope this helps.
WORKING CODE
#include <stdio.h>
#include <stdlib.h>
struct Date
{
int date;
char month[10];
int year;
};
int main()
{
struct Date date[1];
char string[20];
scanf("%[^\n]s",string);
sscanf(string,"%d %s %d",&date[0].date,date[0].month,&date[0].year);
printf("%d %s %d",date[0].date,date[0].month,date[0].year);
return 0;
}
EDIT
They themselves are integers actually (as are all pointers).
As mentioned by anastaciu, pointers are not equivalent to integers per se. You can follow the links given in his comments for more knowledge. I had mentioned that statement to assert the difference between pointers and array declarations.