1

I am trying to take input from user and store it as a char array. I have the following code in which the function array, returns the address to the character array. However, I am getting a core dump error, what is happening here?

//reading and storing input from user as char array
int * array(int * r){
        int ch;
        int i;
        r[10];
        printf("enter your name: ");
        for ( i = 0; i < 10; i++){
                r[i] = getc(stdin);
                printf("%c", r[i]);
        }
        return r;
}
//main
int main(void){
        int *p;
        p = array(p);
}
5
  • 2
    You never allocated any memory for p, so you're dereferencing an uninitialized pointer. Commented Dec 7, 2020 at 16:13
  • 1
    You should use a tutorial for learning how to read a string from standard input in C. You code does not follow the usual practices... Commented Dec 7, 2020 at 16:13
  • You say "char array" but you're using int. Commented Dec 7, 2020 at 16:14
  • The statement r[10]; doesn't do anything. You also declare a variable ch that you never use at all. Commented Dec 7, 2020 at 16:15
  • Your code will work if you change int *p; to int p[10]; Commented Dec 7, 2020 at 16:16

1 Answer 1

1

I'll try to be similar to your code.

The array could be char, instead of int and many other things (you may pass len instead of hard-coding length etc). Anyway the major error was passing a pointer without initializing it: statically as I've done, 11 places, one is for null character; or dynamically using malloc.

The if statement is just for exiting the loop if someone press enter or the stream ends, I think it's your desired behavior.

#include <string.h>
#include <stdio.h>
//reading and storing input from user as char array
void array(int * r){
        int ch;
        int i;
        //r[10];
        printf("enter your name: ");
        for ( i = 0; i < 10; i++){
                int ch = getc(stdin);
                if ( ch == EOF || ch == '\n' || ch == '\r')
                    break;
                r[i] = ch;
                printf("%c", r[i]);
        }
        r[i] = 0;
        
}
//main
int main(void){
        int p[11];
        array(p);
        printf("\nExit\n");
}
Sign up to request clarification or add additional context in comments.

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.