-1

Why does it print out the new word minus the first character when i printf("%s\n",array[0]) and not "Hello". Any tips for how to do solve that ? Thanks in advance !

#include <stdio.h>
#include <string.h>

int main()
{
  char newword;
  char array[100][20]={
    {'H','e','l','l','o'},
    {'W','o','r','l','d'},
 };
    printf("%s\n",array[0]);
    printf("%s\n",array[1]);

    printf("Type a new word: ");
    scanf("%s",&newword);

    strcpy(array[1],&newword);
    printf("%s\n",array[0]);
    printf("%s\n",array[1]);

   return 0;
 }
llllllllll
  • 16,169
  • 4
  • 31
  • 54
Nick Green
  • 11
  • 3
  • This statement scanf("%s",&newword); overwrites the memory beyond the character object newword. – Vlad from Moscow Apr 17 '18 at 10:46
  • @4386427 No it is there (by accident?), just sneakily hidden. – Lundin Apr 17 '18 at 10:52
  • @4386427 You have a point though, that it would be much better to write `{'H','e','l','l','o', '\0'},` as self-documenting code, demonstrating to the reader that "yes indeed I know what I'm doing". Or well... just write `"Hello"`... – Lundin Apr 17 '18 at 14:14
  • @Lundin agree ... but still my comment was incorrect so I removed it – Support Ukraine Apr 17 '18 at 14:15

2 Answers2

2

Of course newword is not capable of holding a string (except the empty string) since it's just a single character, not an array. Using that with scanf() like you do is undefined behavior.

Make it:

char newword[20];

for instance, and preferably also scanf(" %19s", newword);, and check that scanf() succeeded.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

Your code char newword; ... scanf("%s",&newword) yields undefined behaviour; you read in a string into a variable holding a single character; From that point on, all bets are off.

Write char newword[100]; ... and things should do better.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58