Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using arrays and pointers

Tags:

arrays

c

pointers

I have few questions with how to use the pointers. I have the following code.

float* arr;
arr = (float*) malloc(4*sizeof(float));
float temp[4] = {1,2,3,4};

I want to point the arr to the temp array. How do I do it? Is arr=&temp correct?

The output I want is arr pointing to the 1D array {1,2,3,4}.

like image 832
Minions Avatar asked Nov 19 '25 13:11

Minions


1 Answers

I want to point the arr to the temp array.

Then, no need to allocate memory to arr. Just use arr = temp; and you're good to go.

Otherwise, first if you allocate memory and then you assign another pointer, you'll be losing the allocated memory, facing a memory leak.


As per the suggestion in the comment by Mr. barak manos, it's worthy to mention that in the way described above, arr actually points to temp. Now, if this assignment is done inside a function and temp is local to the function, returning arr will be UB.

If the case arises, then, you have to use malloc() and memcpy() to allocate memory to arr and copy the contents of temp to that memory which has a lifetime until deallocated, so can be returned from a function.

like image 198
Sourav Ghosh Avatar answered Nov 22 '25 04:11

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!