mariner
mariner

Reputation: 930

What is the most reasonable declaration of an array for a string of fixed length in C?

I am new to C, so this question might sound dumb. I have a const char* variable with length 2 always. Now I need to pass it on to a struct variable. Should the struct variable be a char array[2] (since it needs only two bytes always) or be a char*. The reason why I am asking is, using a char* will create space for a pointer (4bytes or 8 bytes) but I really need only 2 bytes. Which is the best way to do it? If using a char array[] is the better approach, should I use strcpy to copy the char* variable to char array[]??

Upvotes: 1

Views: 105

Answers (2)

LihO
LihO

Reputation: 42083

"I have a const char* variable with length 2 always. Now I need to pass it on to a struct variable"

If you know that the string will always have a length 2, it is perfectly reasonable to use an array of fixed size 3 (including a null-terminating character):

struct myStruct {
    char code[3];
};

and somewhere:

struct myStruct m;
const char* src = "ab"; 
strncpy(&myStruct.code[0], src, 3);

but in case you can not ensure that the length of src will be no more than 2, you better do:

strncpy(&myStruct.code[0], src, 2);
myStruct.code[2] = '\0';

Upvotes: 0

Joe
Joe

Reputation: 47609

If you are confident that it is always 2 bytes, there's no problem using an array. Just always use strncpy and friends to make sure you don't overrun. Remember to make it 3 bytes long to accommodate the null char. You can get a pointer to your array for reading purposes and that behave identical to a char* to malloced memory.

Upvotes: 5

Related Questions