Debugging C Program for Outputting Array Elements

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 6K views
rclakmal
Messages
76
Reaction score
0
C programme ?

Homework Statement


/* Program-8.4 */
#include <stdio.h>
int main()
{
int marks[5]= {89, 45, 73, 98, 39};
printf("%d\n", marks); //memory addres pointed by pointer
printf("%d\n", &marks[0]); //memory address of 1st element
printf("%d\n", *marks); //value pointed by pointer
printf("%d\n", marks[0]); //value of 1st array element
return 0;


i can't run these source code >it give an error saying
laka.c:6: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘int *’
laka.c:7: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘int *’
line 6 and 7 refers to the lines where marks and & marks[0] are present .
please point out the error >great help !



Homework Equations





The Attempt at a Solution

 
Physics news on Phys.org


The compiler is correct, format ‘%d’ DOES expects type ‘int’, but argument 2 has type ‘int *’
You can either use '%p' or cast the address to an int, some older compilers did allow you to treat an address as an int but it causes problems with 64bit and isn't really allowed.
 


thanks u so much mgb_phys .It was a great help .this programme is in my textbook .So i was amazed as it didn't compile .But now i understand as it was written sometime ago ,those days compilers had allowed to do that .
 


rclakmal said:
printf("%d\n", marks); //memory addres pointed by pointer
printf("%d\n", &marks[0]); //memory address of 1st element
I believe the correct format string for this is %p.

Mark44 said:
And keep in mind that the compiler issued warnings, which are not as serious as errors.
That's arguable. Warnings are quite often more serious than errors: if you made a mistake and get an error, you can't compile your program; however if you made a mistake and ignore the warning, your buggy code actually gets executed.
 


I agree in general about the warnings vs. errors, but there are different categories of warnings, some of which can be safely ignored and some of which can't. At least with a warning, you get compiled code that can produce output for further analysis and debugging.