1

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]); putchar('\n'); 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?

1
  • 1
    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) Commented Nov 6, 2018 at 2:54

1 Answer 1

4

It looks like you're not passing the low or high variables as arguments to the printf() call, on this line:

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

If you provide the low and high variables as arguments to printf() then the expected output should be printed to the console, like so:

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

The "print format" of "low:%d high:%d\n" being passed to the printf() function states that number values will be displayed for each occurrence of %d in the format string.

In order to specify the actual values that will be displayed for each occurrence of %d, additional arguments must be provided to the printf() function - one for each occurrence of %d:

printf("low:%d high:%d\n", low, /* <- the value of low will be printed after "low:" in output the string */ high /* <- the value of low will be printed after "low:" in output the string */ ); 

If these additional arguments are not provided, the program will still compile and run however, at run-time, the program will basically display what ever value is found at the memory locations where it expected to find values for each of the %d occurrences.

For more information on printf(), you might like to see this documentation - hope this helps!

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

1 Comment

@Yunnosch thanks for the feedback! - just updated the answer, what do you think? :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.