0

Basically I will only know the size of the array once the user enters it in the command line.

I'm not sure how to tell the global array to be that size. Should I just do that with malloc()? This array should be global because it will be shared by threads.

alk
  • 69,737
  • 10
  • 105
  • 255
user3217278
  • 320
  • 3
  • 9

2 Answers2

2

Yes, just use malloc(). And of course be very careful when sharing memory among threads.

There's no need for an actual global variable holding the allocated memory, just pass it to the threads on creation.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

Yes, malloc() is exactly right. Just have a global pointer to the correct array type to start like:

int* myGlobalArray;

Then after you capture the user's input as an int:

myGlobalArray = malloc(sizeof(*myGlobalArray)*userSize);
fivetentaylor
  • 1,277
  • 7
  • 11
  • No, [please don't cast the return value of `malloc()` in C](http://stackoverflow.com/a/605858/28169). – unwind Feb 19 '14 at 17:25
  • Is that a recent thing? What compiler? My C is a little rusty – fivetentaylor Feb 19 '14 at 17:27
  • `myGlobalArray = malloc(userSize * sizeof *myGlobalArray);` is more robust. – Keith Thompson Feb 19 '14 at 17:28
  • @fivetentaylor: Casting the result of `malloc()` is legal, but a bad idea. No, it's not a recent thing; it's true for any C compiler conforming to the 1989 ANSI standard or later. Follow the link in unwind's comment. – Keith Thompson Feb 19 '14 at 17:29
  • @Keith Thompson: Should `sizeof *myGlobalArray` be `sizeof(*myGlobalArray)`? – fivetentaylor Feb 19 '14 at 17:31
  • 1
    It can be if you prefer, but the parentheses aren't necessary. The argument to `sizeof` is either a parenthesized type name or an expression. Syntactically, `sizeof` is a unary operator like `!` or `~`, not a function. – Keith Thompson Feb 19 '14 at 17:32
  • Very cool! I think the parens make it less ambiguous though. Thanks for the explanation, I hate when people just say no without explanation. – fivetentaylor Feb 19 '14 at 17:34