-2

so every time i run my code in c only the second name is displayed,but the first one is never here

#include <stdio.h>
#include <stdlib.h>

int  main(void)
{

char name[5];
printf("Enter your name:");
scanf("%s",name);
char secondname[6];
printf("enter your second name:\n");
scanf("%s",&secondname);
printf("hello %s\n",name);
printf("%s how old are you",secondname);


return 0;


//%d is for integersf
//%s is for strings



}

The output is usually like this:

enter your name:
john
enter your second name:
smith
hello hisham how old are you?
Martin James
  • 24,453
  • 3
  • 36
  • 60
adham
  • 5
  • 1
  • 3
  • The code shown does not have any print statement for the second name. If that's not the problem then please show the exact run log - the exact input and output. – kaylum Jan 06 '21 at 10:53
  • the code has been updated! – adham Jan 06 '21 at 10:58
  • Can you please be clearer and more precise in your description? You say "only the second name is displayed,". But that's not what the output shows - there is something shown but it is not the second name that was entered. Can you please clarify? – kaylum Jan 06 '21 at 10:59
  • but the secondname variable is the only one that gets printed this is the problem. – adham Jan 06 '21 at 10:59
  • The program does work with the input `John Smith`. You are entering something else which overflows the tiny buffers, but it's not `John Smith`. – Weather Vane Jan 06 '21 at 11:02
  • i understand what you mean one second – adham Jan 06 '21 at 11:02
  • Make sure you put a closing bracket and add '&' to the scanf of second name.Alos give maybe more arrayval for char String just to be safe. – Abdodt Jan 06 '21 at 11:04
  • 1
    Are you getting that exact output from running the program or are you typing it from memory? – kaylum Jan 06 '21 at 11:05
  • The program does not output what you say, even after the edit. – Weather Vane Jan 06 '21 at 11:05
  • thank you @WeatherVane , but what is the meaning of buffer overflow. – adham Jan 06 '21 at 11:06
  • Please see [Explanation of C buffer overflow](https://stackoverflow.com/questions/52003862/explanation-of-c-buffer-overflow). It is focused on `gets()` but the same applies to `scanf("%s", name)`. But, you changed the input given to the original code, which was stated to output `hello hisham`. This input does exactly what is expected, with `hello john` and `smith how old are you` output on separate lines. – Weather Vane Jan 06 '21 at 11:09
  • This Q&A,is a mess now. You should delete it, ask again without the errors and misleading test conditions. It could then be closed as a dupe. – Martin James Jan 06 '21 at 11:33

1 Answers1

1

scanf("%s",&name); you didnt use & for the first input

BingoYoan
  • 56
  • 2
  • 6