0

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

5
  • 3
    sizeof(blocks) is the size of a pointer. You sure that's what you wanted? Doesn't look like it. Try blocks=malloc(n_block * sizeof *blocks); ? Commented Oct 10, 2018 at 10:09
  • sizeof(struct block) and count < n_block Commented Oct 10, 2018 at 10:11
  • not a problem, but for(int count=0;count<=n_block-1;count++) is usually written as for (int count = 0; count < n_block; count++) Commented Oct 10, 2018 at 10:13
  • Your code as is gives some strange output. A version with the correct sizeof gives the expected output. Commented Oct 10, 2018 at 10:19
  • @pmg yes, i think that the problem was on the sizeof(block) as suggested in the answer by u_ Commented Oct 10, 2018 at 10:30

1 Answer 1

1

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++ )
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, now it works. Why sizeof(blocks) != sizeof(struct block) ?
sizeof *blocks would maybe be better, in case the type of blocks changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.