Thursday, 19 September 2013

Copy C Struct with char pointer

Copy C Struct with char pointer

Firstly, I am really sorry if this has already been asked and resolved - I
have spent ages searching and trying to adapt code samples to give me what
I need... but sadly to no avail. Essentially I am just trying to copy the
contents of one struct to another (which is documented here elsewhere but
I cannot get it to work).
A scanner populates the following struct when it reads a barcode:
struct barcode
{
char *text;
int length;
int id;
int min;
int max;
};
This is instantiated as:
static struct barcode code = {0};
I instantiate another one of the same type:
struct barcode *barcodeHolder;
This is intended to store a copy of the scanned barcode. This is because
other codes will then be scanned that indicated other steps such as
barcodes to indicate numbers or stages (eg. end, start, etc). Once I want
to write the struct contents to disk I use the "copy" of the struct as
that is what I want.
However, the char *text property always equals 'c' and not the value of
the barcode.
I copy them as follows:
barcodeHolder = malloc(sizeof(code));
barcodeHolder->text = malloc(strlen(code->text) + 1);
strcpy(barcodeHolder->text, code->text);
barcodeHolder->id = code->id;
barcodeHolder->length = code->length;
barcodeHolder->max = code->max;
barcodeHolder->min = code->min;
This is what I have got from other posts on a similar topic.
However, I am clearly doing something stupidly wrong and would welcome any
help anyone might be able to offer so that my copy of the struct text
element does actually get the right value copied.
Thank you!

No comments:

Post a Comment