Reputation: 581
When the arguments of dyn_mat are constants, the code runs through without any error and s1 and s2 do store the input values.
#include<stdio.h>
int main(int argc, char const *argv[])
{
char *s1, *s2;
int n1=7, n2=8;
printf("Enter, %d \n", n1);
scanf("%s", s1);
scanf("%s", s2);
int dyn_mat[155][347];
return 0;
}
but with arguments as variables, say n1 and n2, scanf reading s1 gives segmentation fault.
Upvotes: 1
Views: 129
Reputation: 70971
why does c allow initialization of string without declaration?
There is no data type string
in C.
In C one possible way to store a string of characters is using an array of characters, with the last element of this array carring a 0
to indicate the end of this string.
You program does not declare any array, but just pointers to characters, which have no memory assigned to which you copy data using scanf()
.
Your just lucky the program does not crash with the first call to scanf()
.
Upvotes: 0
Reputation: 477444
The code simply has undefined behaviour, since s1
and s2
are not valid pointers. scanf
expects a pointer to an array of chars that's large enough to hold the read data, and you are not providing such pointers.
The usual way would be something like this:
char s1[1000];
char s2[1000];
scanf("%s", s1);
scanf("%s", s2);
(Though you should use a safer version that specifies the available buffer size rather than hoping for the input to be sufficiently short; for example, scanf("%999s", s1);
.)
Upvotes: 7