How to assign first element in array to a variable?

2579 views c

I'm new to c and I have trouble with arrays in c. I don't know how to assign first element from an array to an int variable. When I tried, I got a random large integer from nowhere even index was in range.

This is part of my code:

int solve(int *elev, int n)
    for (int i = 0; i < n; ++i)
        printf("%d ", elev[i]);

    printf("%d %d %d %d %d\n", elev[0], elev[1], elev[2], elev[3], elev[4]);

    int low = elev[0];
    int high = elev[4];

    printf("low:%d high:%d\n");

    // ...

Partial output:

1 4 20 21 24
1 4 20 21 24
low: 362452 high: 7897346

What was a cause of above output?

answered question

In addition to Dacre's answer, I'd rid the 2nd printf statement in favor of the dynamic for-loop---assuming you were just testing? And high is likely to be elev[n-1] (assuming n>0 and elev[] is sorted)

1 Answer


It looks like you're not passing the low or high variables to this printf("low:%d high:%d\n") call. If you add the low/high arguments, then the expected output should be printed to the console:

printf("low:%d high:%d\n", low, high);

posted this

Have an answer?


Please login first before posting an answer.