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.
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;
}
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 copiesn
characters from the object pointed to bys2
into the object pointed to bys1
. [...]
So, we can see, the objects themselves are not changed / replaced, it's only the contents that gets copied.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With