Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic allocation of array issue C

To be clear, my code works perfectly. The issue that concerns me is that i am unsure of my array allocation type.

My task is rather simple: i am required to do some operations within a dynamically allocated array.

Yet, the values are already given in the array. So therefore i am required to add these values in it.

To keep my vector dynamically allocated and to avoid the following situation:

float *p;
 p = malloc(9 * sizeof(float));
* p=2;
* (p+1)=60;
* (p+2)=-23;
.
.
.
* (p+8)=9;

I tried doing this :

float *p;
p = malloc(9 * sizeof(float));
memcpy (p, (float[]) {2 ,60 ,-23, 55, 7, 9, -2.55, -66.9, 9}, 9 * sizeof(float));

Now I am unsure because memcpy copies a static allocated array into my p. My question is then: my array still remains dynamically allocated?

EDIT: My question refers to 2nd code.

like image 765
Catalin Ghita Avatar asked Dec 21 '16 15:12

Catalin Ghita


2 Answers

my array still remains dynamically allocated?

float *p;
p = malloc(9 * sizeof(float));
memcpy ( p, (float[]){2,60,-23,55,7,9,-2.55,-66.9,9}, 9 * sizeof(float));

Yes. The value of pointer p remains unchanged. It still points to the memory dynamically allocated.
p[0], the first element now has the value of 2.0f,
p[1], the next element now has the value of 60.0f, etc.


Some coding suggestions:

int main(void) {
#define COUNT 9
  float *p = malloc(sizeof *p * COUNT);
  if (p) {
    memcpy(p, (float[COUNT] ) { 2, 60, -23, 55, 7, 9, -2.55f, -66.9f, 9 },
        sizeof *p * COUNT);
    //...
  }
  free(p);
  return 0;
}
like image 187
chux - Reinstate Monica Avatar answered Sep 28 '22 04:09

chux - Reinstate Monica


First of all, you don't have an(y) array, all you have a pointer to a memory of particular size.

Secondly, as you mentioned, (emphasis mine)

memcpy copies a static allocated array into my p

so, yes, the pointer still has (or points to) the dynamically allocated memory.

As we see from C11, chapter §7.24.2.1

The memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1. [...]

So, we can see, the objects themselves are not changed / replaced, it's only the contents that gets copied.

like image 29
Sourav Ghosh Avatar answered Sep 28 '22 04:09

Sourav Ghosh