consider the code
#include<stdio.h>
int main(void)
{
char* a;
scanf("%s",a);//&a and &a[0] give same results-crashes
printf("%s",a);
return 0;
}
why does this code results in crashing?whereas this code using character array works fine?
#include<stdio.h>
int main(void)
{
char a[100];
scanf("%s",&a[0]);//works fine
printf("%s",a);
return 0;
}
the difference being character array and pointer?but i knew that pointer just points to the first element that is &a[0] should work fine but upper code crashes for all three that is a,&a and &a[0]?
the main thing i would to gather is how can i take input of a character pointer if i insist on using scanf only?
i apologize if i am not clear.
thanks in advance:)
Because
char* a;allocates space on the stack for a character pointer whilstchar a[100];allocates space for 100 characters.In the former case, you need to allocate some actual memory for the pointer to point to. What’s happening to cause your crash is that
ais being set to some arbitrary value (you don’t initialise it) and, when youscanf, that’s where the data is being written. That’s if you just usea, let’s call that crash type number one.If you use
&a, it will write your input over the pointer itself which will leave you with a pointer that points who-knows-where, leading to crash type number two. That’s assuming you haven’t entered more characters than will overflow the pointer – that would corrupt the call stack leading to yet another crash situation (type three).And as a word of advice, please don’t use input functions that don’t have bounds checking unless you’re absolutely in control as to what data is presented to them. Even with a
char[100], someone could cause a stack overflow in your code by entering more characters than will fit in your buffer.I find the best thing to do is to use
fgets(which can limit the characters read) in conjunction withsscanf(although if all you’re getting is a string,sscanfis not really needed).