1

I am trying to use pointers to save characters to an array but when I run the program, it saves all but the last character and instead replaces it with something random.

Here is the code:

#include <stdio.h>

void inputCharArray(char *beg, char *end){
    char *current = beg;

    while (current != end) {
        scanf("%c ", current);
        current++;
    }
}

int main(void) {
    int size, position;
    position = 0;

    printf("Size of array: ");
    scanf("%d", &size);

    char letters[size];

    printf("Array: ");

    inputCharArray(&letters[0], &letters[size]);

    printf("%s", letters);

    return 0;
}

And here is what I get when I run the program:

Size of array: 3
Array: a s d

as▒

Any help or direction would be appreciated.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Espi
  • 13
  • 2
  • So I added end = '\0'; after the while loop and it didn't change the outcome. Thanks for the suggestions though – Espi Mar 28 '19 at 19:50

1 Answers1

2

There is no '\0' string terminator written to letters[]

In main you need

char letters[size + 1];          // allow for terminator

and the function should be

void inputCharArray (char *beg, char *end){
    char *current = beg;

    while (current != end){
        scanf(" %c", current);   // moved the space to other side of %c
        current++;
    }
    *current = '\0';             // added string terminator
}

I also changed scanf("%c ", current); to scanf(" %c", current); because it was reading the newline left in the buffer after %d format specifier.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • Thanks for your help. I made those changes and it got rid of the random character at the end, but it didn't save the last character. So if I entered "a s d " it just saved "as" – Espi Mar 28 '19 at 19:57
  • The change to scanf(" %c", current); got it. Thanks a lot! – Espi Mar 28 '19 at 20:01
  • 1
    Most `scanf` format specifiers automatically filter out leading whitespace, but `%c` and `%[]` do not. A space before `%c` and `%[]` tells `scanf` to do that. – Weather Vane Mar 28 '19 at 20:01