Debugging C Program for Outputting Array Elements

AI Thread Summary
The C program provided attempts to print array elements and their memory addresses but generates warnings due to incorrect format specifiers. Specifically, using '%d' for pointers leads to warnings, as it expects an 'int', while the arguments are of type 'int *'. The correct approach is to use '%p' for printing memory addresses. Additionally, while warnings are less severe than errors, they can indicate potential issues that may affect program execution. Understanding these nuances is crucial for effective debugging in C programming.
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 .
 


And keep in mind that the compiler issued warnings, which are not as serious as errors.
 


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.
 

Similar threads

Replies
4
Views
1K
Replies
3
Views
1K
Replies
12
Views
2K
Replies
3
Views
1K
Replies
17
Views
2K
Replies
5
Views
2K
Replies
1
Views
10K
Back
Top