Ad

How To Assign A String To A Fixed Sized Char Array

- 1 answer

I am reading a string from a json object. The string can be compressed or uncompressed. If it's compressed, I have to decompress it. So depending on the compressed condition I want to assign a value to with json_string_value. I know the size of the string, hence I want the string to have a static size.

I have the following:

char my_string[MY_SIZE];

if( [some condition]){ 
    //how to assign a value to my_string in this case?
} else {
    ...
    int ret = decompress(compressed_str, compressed_str_len, my_string, MY_SIZE);
    ...
} 

json_string_value() returns a string with a null terminator.

I managed to get it to work by using a different string literal and copying the value over

const char *tmp = json_string_value(image);
strcpy(my_string, tmp); 

but I was wondering if there is an easier (better) way to do this?

Ad

Answer

You don't need all the extra variables, you can just call the function in strcpy() arguments.

strcpy(my_string, json_string_value(image));
Ad
source: stackoverflow.com
Ad