Search code examples
carraysstringext2

C, Storing a string with length <=60 in the space for an array of unsigned ints of size 15


This question has totally confused me-

I have an array(fixed size):

unsigned int i_block[15];

I have a string(length <= 60):

"path/to/bla/is/bla"

How would I go about storing the characters of the string in the space for the array? I was thinking about perhaps using memset, but I have no idea if that would even work?

For Reference: "If the data of a file fits in the space allocated for pointers to the data, this space can conveniently be used. E.g. ext2 stores the data of symlinks (typically file names) in this way, if the data is no more than 60 bytes ("fast symbolic links")."

from

Source


Solution

  • This code assumes that the int type uses 4 bytes, hence 15 int use 60 bytes.

    You can store the string this way:

    size_t len = strlen(str);
    if (len <= sizeof i_block) {
        memset(i_block, 0, sizeof i_block);
        memcpy(i_block, str, len);
    }
    

    The array should be filled with '\0' for cleanliness and to provide a way to tell the length of the string. The above code is simple and readable. You could copy the string and just set the remainder of the buffer to 0 with a slightly less readable call to memset.

    Note that if the string length is 60, there will be no trailing '\0' at the end of the array. The string should be retrieved carefully to account for this limitation.