is there anyway to do what I do in Lines 2 and 3, with smth similar to Line 1?
If I just put Line 1, then both “a” and “one.index1” will be pointing to similar location, which I do not want. What I really want is done by Lines 2 and 3. So, is it the only way, or can anyone give better way?
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int *index1;
} data;
void doo(int *);
int main(int argc, char *argv[])
{
int *a = (int *) malloc(10*sizeof(int));
int i;
for(i=0; i<10; i++)
{
a[i] = 2*i;
}
doo(a);
data one;
//one.index1 = a; // Line 1
/*******************/
one.index1 = (int *) malloc(5*sizeof(int)); // Line 2
for(i=0; i<5; i++) one.index1[i] = a[i]; // Line 3
/*******************/
printf("%d\n", one.index1[4]);
free(a);
printf("%d\n", one.index1[4]);
free(one.index1);
return 0;
}
void doo(int *b)
{
b = (int *) realloc(b, 5*sizeof(int));
return;
}
Thanks in advance!
doo will not work as it is. It would need to be:
and called by
Your original version may occasionally accidently work, if the realloc occurs immedaitely after the malloc, so there is space to expand the memory block in place. But that should not be counted on.
Now, to answer your actual question, Since we are dealing with simple data items (i.e., ints), you can use
memmove()ormemcpy()to copy them: (memmove is safe if the memory blocks overlap; memcpy isn’t, but that’s not a problem here)As for the efficency of memmove/memcpy, that’s pretty much an unknown area. memmove does a bit more range checking then memcpy, so it’ll be a hair slower the memcpy. As far memcpy vs a loop, hard to say. memcpy has a bit more overhead, but it’s called a lot, so compiler vendors have a guy who spends a lot of time making sure it’s a fast as possible.
Note however, given a small, fixed number of elements to copy, the fastest way to going to be to just copy them directly: