Copying from struct pointer to struct pointer for database in C -


i have following structures created:

typedef struct {   char name[15];   int id; } employee;  typedef employee item;  typedef struct {   item items[5];   int size; } list; 

i using function call peek see being stored in list:

void peek (int position, list *l, item *x); 

the function should take item in list [l] @ [position] , copy address [x]. have peek function this:

void peek (int position, list *l, item *x) {   item *b;   b = malloc(sizeof(l->items[position]));   x = b; } 

this assigns x same location b think result in memory leak , more importantly if try call id of item x in main, function:

int employeeid (employee x) {   return(x.id); } 

i returned 32665 or along lines. way data l x?

x , b both pointers

x = b pointer assignment, not structure assignment

x pass value parameter, assigning value x inside function has 0 impact on value of x outside function.

try (not solution, step in right direction):

void peek (int position, list *l, item **x) {   item *b;   b = malloc(sizeof(l->items[position]));   *x = b; } 

however, value of l->items[position] still not assigned x space.

option 2:

void peek(int position, list *l, item *x) {   *x = l->items[position]; } 

this assumes x points malloc'd block of memory. if not, option 3

option 3:

void peek (int position, list *l, item **x) {   item *b;   b = malloc(sizeof(l->items[position]));   *x = b;   *b = l->items[position]; } 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -