output unknown problem
Jun 29, 2015 at 10:25am UTC
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();
}
Jun 29, 2015 at 10:38am UTC
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 Jun 29, 2015 at 11:01am UTC
Jun 29, 2015 at 10:43am UTC
ok but why the other two numbers are zero? shouldn't they be the same value?
Jun 29, 2015 at 10:46am UTC
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.
Jun 29, 2015 at 11:00am UTC
By the way the routine should be void not int I have edited the example code above.
Jun 29, 2015 at 11:31am UTC
ok thank you both
Topic archived. No new replies allowed.