Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't understand why its not working when using two variables, the same works if i use just a single variable

#include <stdio.h>

int main()
{
char *a,*b;
scanf("%s %s",a,b);
printf("%s %s",a,b);
return 0;
} 

It works like this,

#include <stdio.h> 
int main(){
    char *a;
    scanf("%s",a);
    printf("%s",a);
    return 0;
}

I think its something with memory becoz when i use malloc and assign some memory it works.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is undefined behaviour (UB) in both cases as you pass the pointer which was not assigned with reference to the allocated valid memory, large enough to accommodate the scanned strings. As it is a UB it does not have to express itself in any particular way. So single variable version does not work as well.

int main(void)
{
   char x[10], y[10];
   char *a = x,*b = y;
   /* .... */
}
int main(void)
{
   
   char *a = malloc(10),*b = malloc(10);
   /* .... */
   free(a);
   free(b);
}
int main(void)
{
   char a[10], b[10;
   /* .... */
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading