memcpy and pointers
I am confuse on how to read the pointers copied in an array using memcpy. Following is what I have tried, but does not work.
Basically, I have allocated block of memory in which I am copying pointers similar to array fashion, but during retrial it is not working. While this works with basic data types properly
I want to store anything in the element
block, It can be either integers
or pointers
.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INDEX(x) ((char *)elements + (sizeof(int*) * (x)))
int size = 10;
void f2_int_ptr() {
int i = 0;
void *elements = (void*)malloc(size * sizeof(int*));
for ( i = 0; i < size; i++ ) {
int *v = ( int *) malloc ( sizeof(int));
memcpy ( v, &i, sizeof ( int ));
memcpy ( INDEX(i) , v, sizeof (int*));
}
for ( i = 0; i < size; i++ ) {
int *v = (int*)0;
memcpy ( v, INDEX(i), sizeof(int *));
printf ( "%d\n", *v );
}
}
void f1_int() {
int i = 0;
void *elements = (void*)malloc(size * sizeof(int));
for ( i = 0; i < size; i++ ) {
memcpy ( INDEX(i) , &i, sizeof (int));
}
for ( i = 0; i < size; i++ ) {
int v;
memcpy ( &v, INDEX(i), sizeof ( int ));
printf ( "%d\n", v );
}
}
int main(){
f1_int();
f2_int_ptr();
return 0;
}
In the above code f1_int
works fine but f2_int_ptr
does not work.开发者_开发知识库
f2_int_ptr()
needs to become this:
void f2_int_ptr() {
int i = 0;
void *elements = malloc(size * sizeof(int*));
for ( i = 0; i < size; i++ ) {
int *v = malloc ( sizeof(int));
memcpy ( v, &i, sizeof ( int ));
memcpy ( INDEX(i) , &v, sizeof (int*));
}
for ( i = 0; i < size; i++ ) {
int *v;
memcpy ( &v, INDEX(i), sizeof(int *));
printf ( "%d\n", *v );
}
}
Note the subtle changes to the memcpy()
arguments.
Note: I really, really, really, wouldn't write code like this! It's incredibly difficult to follow.
Code is very ugly, so I dont even know how it should works but: Why are u using &v here:
memcpy ( &v, INDEX(i), sizeof ( int ));
v is pointer itself:
int *v = (int*)0;
thanks Guys, it worked finally. i guess i have not allocated the space where to copy memcpy.
void f2_int_ptr() {
int i = 0;
void *elements = (void*)malloc(size * sizeof(int*));
for ( i = 0; i < size; i++ ) {
int *v = ( int *) malloc ( sizeof(int));
memcpy ( v, &i, sizeof ( int ));
memcpy ( INDEX(i) , v, sizeof (int*));
}
for ( i = 0; i < size; i++ ) {
int *v = ( int *) malloc (sizeof(int*));
memcpy ( v, INDEX(i), sizeof(int*));
printf ( "%d\n", *v );
}
}
If you are storing the pointers in the elemnts, I think the final memcpy needs to use &v to copy the element to the pointer v. Similar to v=elements[i].
void f2_int_ptr() {
int i = 0;
void *elements = (void*)malloc(size * sizeof(int*));
for ( i = 0; i < size; i++ ) {
int *v = ( int *) malloc ( sizeof(int));
memcpy ( v, &i, sizeof ( int *));
memcpy ( INDEX(i) , &v, sizeof (int*));
}
for ( i = 0; i < size; i++ ) {
int *v = (int *)0;
memcpy ( &v, INDEX(i), sizeof(int *));
printf ( "%d\n", *v );
}
}
精彩评论