0

I am trying to allocate memory for an integer array

ptr=malloc(length*sizeof(int));

which will give me the pointer to the allocated memory. I understand that I can access the values with *(ptr+k), where k is the position in the integer array. However is there a way to define a new array

int allocarray[length];

and then assign allocarray the address ptr, so that I can access the stored values with

allocarray[k]

? I tried the following which does not work:

allocarray=ptr;

Thank you for the help.

Mark
  • 209
  • 3
  • 8

1 Answers1

1

If you declare an array like you do above, it will be automatically allocated. However, if you say:

int *allocarray = (int *)malloc(length*sizeof(int));

you can still access element k using the syntax allocarray[k].

Hellmar Becker
  • 2,824
  • 12
  • 18
  • 1
    Don't cast the result of `malloc`. – letmutx Mar 27 '17 at 12:38
  • Why is the (int*) part needed? – Mark Mar 27 '17 at 12:38
  • ... Specifically, here's the reasoning for not casting http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – StoryTeller - Unslander Monica Mar 27 '17 at 12:41
  • @StoryTeller, I think the casting of the result of malloc comes from the very old days when there was no void yet, int was default return type and malloc wasn't in the standard library (K&R72). There is nothing inherently wrong with that, though the link makes a strong case. And maybe for when you might want to use your code in C++, which requires casts if I remember correctly? – Paul Ogilvie Mar 27 '17 at 13:15
  • @PaulOgilvie - Any C code I want to use in C++ I'd still compile with a C compiler. No reason to gives up useful languages features to appease a cranky compiler for a completely different language. And by useful features I of course mean more than just implicit coercion from `void*`. – StoryTeller - Unslander Monica Mar 27 '17 at 13:18