user2225940
user2225940

Reputation: 83

Copying from struct pointer to struct pointer for database in C

I have the following Structures created:

typedef struct {
  char name[15];
  int ID;
} Employee;

typedef Employee Item;

typedef struct {
  Item items[5];
  int size;
} List;

I am using this function call as a peek to see what is being stored in the list:

void Peek (int position, List *L, Item *X);

The function should take the item in the list [L] at [position] and copy its address to [X]. I have for the peek function this:

void Peek (int position, List *L, Item *X) {
  Item *B;
  B = malloc(sizeof(L->items[position]));
  X = B;
}

This assigns X to the same location as B however I think this would result in a memory leak and more importantly if I try to call the ID of item X back in my main, from this function:

int EmployeeID (Employee X) {
  return(X.ID);
}

I am returned with 32665 or something along those lines. What would be another way to get the data from L to X?

Upvotes: 1

Views: 130

Answers (2)

LihO
LihO

Reputation: 42083

"The function should ... copy its address to X" ~> The problem with this code:

void Peek (int position, List *L, Item *X) {
    Item *B = malloc(sizeof(L->items[position]));
    X = B;
}

is that it doesn't change the original pointer passed as a third argument. What you actually need to do is to modify the pointer itself, thus you need to either return this pointer from the function or pass it as Item**, i.e. pointer to pointer:

void Peek (int position, List *L, Item **X) {
    Item *B = malloc(sizeof(L->items[position]));
    *X = B;
}
...
// and somewhere:
Peek(position, L, &X);              // <-- you should pass an address of pointer

Upvotes: 1

DwB
DwB

Reputation: 38300

X and B are both pointers

X = B is pointer assignment, not structure assignment

X is a pass by value parameter, assigning a value to X inside a function has zero impact on the value of X outside the function.

Try this (not a solution, but a step in the right direction):

void Peek (int position, List *L, Item **X)
{
  Item *B;
  B = malloc(sizeof(L->items[position]));
  *X = B;
}

However, the value of L->items[position] is still not assigned to the X space.

Option 2:

void Peek(int position, List *L, Item *X)
{
  *X = L->items[position];
}

This assumes that X already points to a 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];
}

Upvotes: 1

Related Questions