I have two pointers, each pointing to a different array. One of the pointers is inside of a struct, as follows:
typedef struct
{
int N; /* Number of Elements in array */
double *c; /* Pointer to an array */
/* Other members.... */
} CS;
The struct was initialized by:
CS->N = n; /* n is an integer of an initially unknown size */
CS->c = (double *)malloc(n * sizeof(double));
The pointer in the struct, CS->C
, contains data that I no longer care about.
My other pointer was defined as follows:
double *alpha;
alpha = (double *)malloc(CS->N * sizeof(double));
I need to replace the contents of CS->C
with alpha
. I know I can do something naive like:
for (i=0;i<CS->N;i++) /* i is an integer */
CS->c[i] = alpha[i];
I could also use memcpy, like this:
memcpy(CS->c,alpha,CS->N * sizeof(double));
My understanding is that both of these methods will copy the contents from memory located at alpha
to the memory occupied by CS->C
. That being a very expensive operation, it would make more sense to simply change the assignment of CS->C
to alpha
.
How can I do this?
I've tried to reassign the pointer by doing like CS->C = &alpha
, but this gives me the following warning "assignment from incompatible pointer type".
Note: This is using ANSI C89 under full compliance, ie the compiler options are: -Wall -pedantic -ansi
Edit 1
Freeing CS->c
and assigning it to alpha
by doing:
free(CS->c);
CS->c = alpha;
does not work. It causes every entry in CS->c
to become equal to 0.0
and it results in my program seg faulting.
Edit 2
I think I realized why the method suggested in my first edit did not work. alpha
is a temporary pointer, created and initialized inside of a function, so once that function is exited, the memory occupied by alpha
is "freed". Since CS->c
points to that memory, it is also freed. Upon this discovery, I think I will rework my code, such that alpha
and CS-c
are initially swapped, such that when they are switched again, the end order will be correct. Thank you all for you valuable input.
Just copy the pointer
CS->C = alpha;
Alpha is a pointer to double, CS->C too, types matches, you simply change the pointer.
/!\\ Don't forgot to free the old CS->C ...
Free the old pointer and assing the new directly. (Not the adress of the new pointer)
The pointer in the struct,
CS->c
, contains data that I no longer care about.My other pointer was defined as follows:
double *alpha;
alpha = malloc(CS->N * sizeof(double));
...
free (CS->c);
CS->c = alpha ; alpha=NULL;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.