1

can you please explain how to use int array in typedef struct?

In my header i have code:

typedef struct {
    int arr[20];
    int id;
} Test;

In some function (where i include my header file) i use:

Test tmp = malloc(sizeof(Test));
tmp.id = 1;
//and how to use array arr?
//for example I want add to array -1

Thank you for your reply.

3
  • tmp.arr[0] = -1? You would have to keep track of the last index as you can't "add" stuff to arrays. Their size is fixed (unless you use realloc) Commented Nov 3, 2015 at 10:47
  • I get segmentation fault (core dumped) error after this command. Commented Nov 3, 2015 at 10:48
  • 2
    The code shown won't compile. Commented Nov 3, 2015 at 11:48

1 Answer 1

4

If you want to do it dynamically

Test* tmp = malloc(sizeof(Test));
tmp->id = 1;        //or (*tmp).id = 1;
tmp->arr[0] = 5;    // or (*tmp).arr[0] = 5
                    // any index from 0 to 19, any value instead of 5 (that int can hold)

If you do not want to use dynamic memory

Test tmp;
tmp.id = 1;      //any value instead of 1 (that int can hold)
tmp.arr[0] = 1;  //any value instead of 1 (that int can hold)

EDIT

As suggested by alk in the comments,

Test* tmp = malloc(sizeof *tmp);

is better then

Test* tmp = malloc(sizeof(Test));

Since, to quote alk "The former would survive a change in the type definition of tmp without any further code changes"

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

5 Comments

(*tmp). is quite uncommon, whereas doing tmp-> instead isn't.
Als doing Test * tmp = malloc(sizeof *tmp); instead of ... malloc(sizeof(Test)); would not only be nicer, but also saver.
@alk how are those different?
The former would survive a change in the type definition of tmp without any further code changes, that's why mentioned "saver".
@alk, thats ok, i edited the answer. But since both the things are on the same line, its quite easy to change both. And the former one looks a little less readable.

Your Answer

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