3

I am trying to learn arrays and pointers in C. I'm trying to write a program that in a function: gets 2 numbers from the user, puts them in an array, and returns them to the main function. I am getting an error and I don't understand what the problem is. Here is my code:

#include<stdio.h>

void get_nums(float *x)
{
    float num1, num2;

    printf("enter two numbers: ");
    scanf("%f %f", &num1, &num2);

    *x[0] = num1;
    *x[1] = num2;

}

main(){

    float x[2];
    float (*p_x)[2] = &x;

    get_nums(p_x[2]);

    printf("Number 1: %f\nNumber 2: %f", x[0], x[1]);

    return 0;
}

I am getting an error on these 2 lines

    *x[0] = num1;
    *x[1] = num2;

The error message is

Error: operand of '*' must be a pointer

I don't see what it is that is wrong. Does anyone see the problem?

EDIT: I changed the 2 lines to

    x[0] = num1;
    x[1] = num2;

and now I can run the program. However I get a new error after I enter the two numbers. The error message is:

  Unhandled exception at 0x40e00000 in arraysandpointers.exe: 0xC0000005: Access violation.

2 Answers 2

3

You don't need the *. Just this is fine:

x[0] = num1;
x[1] = num2;

In your original code x[0] already is of type float. *x[0] will try to deference it - which is not possible since x[0] isn't a pointer. Therefore it doesn't compile.

EDIT : Also change your main to this:

int main(){

    float x[2];
    get_nums(x);

    printf("Number 1: %f\nNumber 2: %f", x[0], x[1]);

    return 0;
}

It is not necessary to have the p_x. And it is what's causing the crash.

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

1 Comment

That worked, however I am now getting a new error. After I enter the two numbers I get the error: "Unhandled exception at 0x40e00000 in arrayandpointers.exe: 0xC0000005: Access violation."
2

*X can be considered as an array of X like X[]. So when you are writing as *X[0] it considers as a 2D array. So remove the pointers in X[0] and X[1].

Remove these two lines:

float (*p_x)[2] = &x;
get_nums(p_x[2]);

You can directly do get_nums(x).

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.