Issue
I am a Computer science student and I feel like I am missing something very simple. Could you please help me out ?
#include <stdio.h>
void do_stuff(int *c) {
static int a = 0;
int b = 0;
a+=3;
printf("%d %d\n", *(c+a), c[b]);
printf("%d %d\n", *(c+6), c[b]);
printf("%d %d\n", c[6], c[b]);
}
int main (void){
static int array[6] = {5,17,23,42,127,3};
do_stuff(array);
do_stuff(array);
do_stuff(array);
return 0;
}
This is the outcome of this code:
42 5
3 5
3 5
6 5
6 5
6 5
0 5
9 5
9 5
I don't get, why it is 6 5 for the second do_stuff(array). I thought it would be 0 5 for every print of second and third do_stuff(array). Then I thought maybe It was something to do with static a and I tried it without a variable, so just with the number 6. But the answer was the same. Could you please explain the reason for the outputs with the bold font? Thank you for your help.
Solution
In an array with 6 elements, using index 6
will read the first position after the array, which is not 0. The read value depends on the underlying architecture and compiler implementation; depending if such memory position is mapped to your process or not, the OS may kill your application.
In your case, it looks like in memory you have the value of variable a
stored just after the input array of do_stuff()
, that's why printing c[6]
basically prints the value of a
.
Of course this is best described as undefined behavior and the source code is basically incorrect.
Answered By - Jack Answer Checked By - Katrina (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.