output unknown problem

This little function should show "3,5,2,7,4,2,7,0,0,0" but the element 8 is a 7-numbers random number. Please help me

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
int print_array (int *v, int dim) {
int i;
for (i=0; i<dim; i++)
printf ("Elemento [%d]: %d\n",i,v[i]);
}
int main() {
int v[] = { 3,5,2,7,4,2,7 };
print_array(v,10);
getchar();
}
You are passing its size as 10 but have initialized it with 7 items.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>

void print_array (int *v, int dim)
{
    int i;
    for (i=0; i<dim; i++)
        printf ("Elemento [%d]: %d\n",i,v[i]);
}
int main() {
    int v[] = { 3,5,2,7,4,2,7 };
    print_array(v,7);
    getchar();
}

Last edited on
ok but why the other two numbers are zero? shouldn't they be the same value?
shouldn't they be the same value?
No. You are trying to access 8th number in array containing 7 elements. It is undefined behavior. You can get any output. In fact, you program may crash or format your hard drive and that will be acceptable behavior.
By the way the routine should be void not int I have edited the example code above.
ok thank you both
Topic archived. No new replies allowed.