0

I have a problem, they gave me a task. They told us that we must use a pointer to put the value from the keyboard to array and then print that array.

I try to create that, but I don't know why this is wrong. I define my array then I get value and put that value into an array.

#include <stdio.h>
#include <stdlib.h>
#define N 10000 // Maximum array size


int main ()
{
    char keyboardArray[N];    
    char *r;            
    r = keyboardArray;
    while( (*r++ = getchar()) != EOF );
    printf("You write %s", r);

    return 0;
}
0

2 Answers 2

2

You have several problems:

  1. At the end of the loop, r points to the end of the string, not the beginning. So printing r won't print the string that was entered. You should print the keyboardArray rather than r.
  2. You're never adding a null terminator to the string, so you can't use the %s format operator.
  3. getchar() returns int, not char -- this is needed to be able to distinguish EOF from ordinary characters. So you need to read into a different variable before storing into the array.
int main ()
{
    char keyboardArray[N];    
    char *r;    
    int c;        
    r = keyboardArray;
    while( (c = getchar()) != EOF ) {
        *r++ = c;
    }
    *r = '\0'; // Add null terminator
    printf("You write %s\n", keyboardArray);
}

Note that this will read until EOF, so the user will have to type a special character like Control-d (on Unix) or Control-z (on Windows) to end the input. You might want to check for newline as well, so they can enter a single line:

while ((c = getchar()) != EOF && c != '\n') {
Sign up to request clarification or add additional context in comments.

2 Comments

Make that while (r < keyboardArray + N - 1 && (c = getchar()) != EOF && c != '\n'). Always, always, always check for buffer overflow in C!
I know this is a beginner question, but it is a good habit to get into.
1

I think that in any case you need an intermediate variable that will accept a read character.

Also you need to append the entered sequence of characters with the terminating zero.

For example

#include <stdio.h>

#define N 10000 // Maximum array size

int main( void )
{
    char keyboardArray[N];    
    char *r = keyboardArray;

    for ( int c; 
          r + 1 < keyboardArray + N && ( c = getchar() ) != EOF && c != '\n';
          ++r )
    {
        *r = c;
    }

    *r = '\0';

    printf( "You write %s\n", keyboardArray );
}

Comments

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.