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.

1
  • So I added end = '\0'; after the while loop and it didn't change the outcome. Thanks for the suggestions though Commented Mar 28, 2019 at 19:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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"
The change to scanf(" %c", current); got it. Thanks a lot!
Most scanf format specifiers automatically filter out leading whitespace, but %c and %[] do not. A space before %c and %[] tells scanf to do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.