Reputation: 153
i have a trouble with my code in C:
#include<stdlib.h>
#include<stdio.h>
int main()
{
int i1,j1,k1;
int n_block;
struct block
{
int i,j,k;
} *blocks;
n_block=3;
i1=4;
k1=3;
j1=2;
blocks=malloc(n_block*sizeof(blocks));
for(int count=0;count<=n_block-1;count++){
printf("count %d\n",count);
blocks[count].i=i1;
blocks[count].j=j1;
blocks[count].k=k1;
printf("results:%d\n",blocks[count].i);
printf("results:%d\n",blocks[count].j);
printf("results:%d\n",blocks[count].k);
}
}
the expected output is:
count 0
results:4
results:2
results:3
count 1
results:4
results:2
results:3
count 2
results:4
results:2
results:3
but I obtain:
count 0
results:4
results:2
results:3
count 1
results:4
results:2
results:3
count 2
results:4
results:2
results:1970496882
I suppose that the last result is the value of the pointer, but why do it happen?
I tried to modify the for loop (without modify the n_block):
for(int count=0;count<=n_block+1;count++)
and I obtain:
count 0
results:4
results:2
results:3
count 1
results:4
results:2
results:3
count 2
results:4
results:2
results:1970496882
count 3
results:4
results:2612
results:10
count 4
results:4
results:2
results:3
so, the question is, why does it happen?
Thanks
Upvotes: 0
Views: 59
Reputation: 3767
In case of malloc
the statement sizeof(blocks)
will evaluates to size of a pointer and in your case sizeof(blocks) != sizeof(struct block)
change the malloc
to
blocks = malloc(n_block * (sizeof( struct block) ) ); // more readable
for loop
is over complicated one here, stick to basics
for(int count=0; count < n_block; count++ )
Upvotes: 1