user437777
user437777

Reputation: 1519

Memcpy and Memset on structures of Short Type in C

I have a query about using memset and memcopy on structures and their reliablity. For eg:

I have a code looks like this

typedef struct
    {
    short a[10];
    short b[10];
}tDataStruct;

 tDataStruct m,n;

memset(&m, 2, sizeof(m));
memcpy(&n,&m,sizeof(m));

My question is,

1): in memset if i set to 0 it is fine. But when setting 2 i get m.a and m.b as 514 instead of 2. When I make them as char instead of short it is fine. Does it mean we cannot use memset for any initialization other than 0? Is it a limitation on short for eg

2): Is it reliable to do memcopy between two structures above of type short. I have a huge strings of a,b,c,d,e... I need to make sure copy is perfect one to one.

3): Am I better off using memset and memcopy on individual arrays rather than collecting in a structure as above?

One more query,

In the structue above i have array of variables. But if I am passed pointer to these arrays and I want to collect these pointers in a structure

typedef struct
    {
    short *pa[10];
    short *pb[10];
}tDataStruct;

 tDataStruct m,n;

memset(&m, 2, sizeof(m));
memcpy(&n,&m,sizeof(m));

In this case if i or memset of memcopy it only changes the address rather than value. How do i change the values instead? Is the prototype wrong?

Please suggest. Your inputs are very imp

Thanks dsp guy

Upvotes: 1

Views: 2399

Answers (1)

Richard Sitze
Richard Sitze

Reputation: 8463

  1. memset set's bytes, not shorts. always. 514 = (256*2) + (1*2)... 2s appearing on byte boundaries. 1.a. This does, admittedly, lessen it's usefulness for purposes such as you're trying to do (array fill).
  2. reliable as long as both structs are of the same type. Just to be clear, these structures are NOT of "type short" as you suggest.
  3. if I understand your question, I don't believe it matters as long as they are of the same type.

Just remember, these are byte level operations, nothing more, nothing less. See also this.

For the second part of your question, try

memset(m.pa, 0, sizeof(*(m.pa));
memset(m.pb, 0, sizeof(*(m.pb));

Note two operations to copy from two different addresses (m.pa, m.pb are effectively addresses as you recognized). Note also the sizeof: not sizeof the references, but sizeof what's being referenced. Similarly for memcopy.

Upvotes: 1

Related Questions