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 array(fixed size):

unsigned int i_block[15]; 

i have string(length <= 60):

"path/to/bla/is/bla" 

how go storing characters of string in space array? thinking perhaps using memset, have no idea if work?

for reference: "if data of file fits in space allocated pointers data, space can conveniently used. e.g. ext2 stores data of symlinks (typically file names) in way, if data no more 60 bytes ("fast symbolic links")."

from

source

this code assumes int type uses 4 bytes, hence 15 int use 60 bytes.

you can store string 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 filled '\0' cleanliness , provide way tell length of string. above code simple , readable. copy string , set remainder of buffer 0 less readable call memset.

note if string length 60, there no trailing '\0' @ end of array. string should retrieved account limitation.


Comments