string compare

J

James Antill

James said:
Mark Bluemel wrote:
...
I think Santosh was suggesting a structure approach like this :-

typedef struct {
short length;
char data[]; /* or "char data[1];" if c99 support isn't
available */
} my_string;

so if you had a string of 32 characters to work with, you'd do
something like:-

my_string *string_pointer = malloc(sizeof(short) + 32);

That assumes there are no padding bytes between length and data. The
right way to calculate the allocation is

#include <stddef.h>
...
mystring *string_pointer = malloc(offsetof(my_string, data) +
32);

This is required to be the same as sizeof(mystring),

Citation, please?

6.7.2.1

#16

As a special case, the last element of a structure with more than
one named member may have an incomplete array type; [...] the
size of the structure shall be equal to the offset of the last
element of an otherwise identical structure that replaces the
flexible array member with an array of unspecified length

#17 even gives an example basically identical to what I posted.
 
H

Harald van Dijk

James said:
typedef struct {
short length;
char data[]; /* or "char data[1];" if c99 support isn't
available */
} my_string;

#include <stddef.h>
...
mystring *string_pointer = malloc(offsetof(my_string, data) +
32);

This is required to be the same as sizeof(mystring),

Citation, please?

6.7.2.1

#16

As a special case, the last element of a structure with more than one
named member may have an incomplete array type; [...] the size of the
structure shall be equal to the offset of the last element of an
otherwise identical structure that replaces the flexible array member
with an array of unspecified length

This states that sizeof(my_string) must be equal to offsetof(struct {
short length;
char data[n];
}, data) for some fixed n, but that might be different from
offsetof(my_string, data).
#17 even gives an example basically identical to what I posted.

#17 even explicitly mentions that the offset of a flexible array member
might differ from the offset of a non-flexible array member.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,787
Messages
2,569,630
Members
45,338
Latest member
41Pearline46

Latest Threads

Top