3

I want to know how to assign a struct containing an array of int to an array of structs. I keep getting the incorrect result no matter what new solution I think of.

I believe the problem lies in this piece of code:

struct Codes *create(int as) { struct Codes *c = malloc(sizeof (struct Codes)+as * sizeof (int)); c->as = as; for (int i = 0; i < as; i++) { c->a[i] = i; } return c; } 

The whole code:

#include <stdio.h> #include <stdlib.h> #include <ctype.h> struct Codes { int as; int a[]; }; struct Code { int as; struct Codes *ci[]; }; struct Codes *create(int as) { struct Codes *c = malloc(sizeof (struct Codes)+as * sizeof (int)); c->as = as; for (int i = 0; i < as; i++) { c->a[i] = i; } return c; } struct Code *and(int as, struct Codes *cd) { struct Code *c = malloc(sizeof (struct Code)+as * sizeof (struct Codes)); for (int i = 0; i < as; i++) { c->ci[i] = cd; } c->as = as; return c; } int main(int argc, char **argv) { struct Codes *cd; cd = create(4); struct Code *c; c = and(2, cd); for (int i = 0; i < c->as; i += 1) { for (int j=0; j < c->ci[i]->as; j++) { printf("%d \n", c->ci[i]->a[j]); } } free(cd); free(c); }//main 

Actual Result:

0 1 2 3 

Expected Result:

0 1 2 3 0 1 2 3 
2
  • 1
    It'd be good to learn how to use a debugger and be able to find these things yourself by inspecting the values of variables as your program runs Commented Oct 5, 2016 at 3:36
  • Sorry about that, I don't know how I messed that, and Thanks for the help. Commented Oct 5, 2016 at 3:39

1 Answer 1

1

struct Code *c = malloc(sizeof (struct Code)+as * sizeof (struct Codes)); is incorrect. The struct Code 's ci is an array of pointers , but you allocated space for an array of structs.

To fix this, either change to sizeof(struct Codes *), or preferably use the pattern of dereferencing the pointer to the type you're allocating space for:

struct Code *c = malloc( sizeof *c + as * sizeof c->ci[0] ); 

Also, for (int j; should be for (int j = 0; . Your code causes undefined behaviour by using uninitialized value of j, it's just chance that you happened to get the output you did. Using the gcc flag -Wextra would have diagnosed this error.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.