2

Hi guys I am a beginner in C, and I have trouble when testing array pointer and allocating dynamic memory.

int x,i=0;
char *myChar;

printf("Please enter the length: ");
scanf("%d",&x);
myChar = (char*)malloc(x*sizeof(char));
printf("Please enter %d characters:",x);
for(i=0;i<x;i++){
    scanf("%c ",&myChar[i]);
}

for(i=0;i<x;i++){
    printf("%c",myChar[i]);
}
free(myChar);

If I enter 5 for length, and "hello" for character array, I get "hell" instead of "hello", which is not fun. Anybody can help me with this? Thanks

  • To store `"hello"` *as a string* you need 6 bytes, with the last holding the terminating `'\0'`. You're storing and accessing individual characters in an array, so you don't need the `'\0'`, but it's a somewhat odd approach. – Keith Thompson Feb 12 '15 at 17:13
  • There is a danger lurking, but not met here, but if you decide to print the whole string in one go with `printf("%s", myChar);` or use one of the library string functions, it would fail for two reasons. First it has no zero-terminator, and even if you put one after the input loop with `myChar[i]=0;` it would fail because the buffer is not big enough unless you did `myChar=malloc(x+1);`. And note, your other frills in `malloc()` call are uneccessary. – Weather Vane Feb 12 '15 at 17:15

4 Answers4

3

The problem is with your scanf() change it to

scanf(" %c",&myChar[i]);

The space before the %c will consume the newline character in the buffer because of the enter key following the value of x else the newline character will be fetched as by %c in the loop. So have a space before %c not after it.

Gopi
  • 19,784
  • 4
  • 24
  • 36
3

The most likely culprit is the following scanf call:

scanf("%c ",&myChar[i]);

Change it to the following:

scanf(" %c", &myChar[i]);

Note that I switched the blank space to before the %c conversion specifier.

Here's what's happening: when you enter your array size, the input stream will contain the following characters: '5' '\n'. The first scanf call consumes the '5' and leaves the '\n' in the input stream.

When you enter hello, the input stream contains '\n' 'h' 'e' 'l' 'l' 'o' '\n'. The next scanf call reads '\n' from the input stream and assigns it to myChar[0] because %c does not skip leading whitespace. So you wind up reading '\n' 'h' 'e' 'l' 'l' from the input stream and assigning them to your myChar array.

By putting the blank space before the %c conversion specifier, you tell scanf to skip any leading whitespace and consume the next non-whitespace character.

John Bode
  • 119,563
  • 19
  • 122
  • 198
0

The first scanf isn't eating the return key used to finish the length entry, so it becomes the first of your x characters read, so the last character isn't being read. @Gopi's fix will address this.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

You can also call

fflush (stdin); 

after the fifth line

David Haim
  • 25,446
  • 3
  • 44
  • 78