0

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?

3
  • 1
    Where do you have a string literal? String literals are in double quotes, e.g. "foo" Commented Feb 16, 2022 at 23:32
  • @Barmar: right, sorry, mixed up names. And sorry again, used the wrong variable names, edited my answer Commented Feb 17, 2022 at 0:29
  • Slightly off-topic: beware buffer overrun when you use strcpy. Consider strncpy instead. Commented Feb 17, 2022 at 0:33

1 Answer 1

2

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

strcpy(my_string, json_string_value(image));
Sign up to request clarification or add additional context in comments.

3 Comments

" I know the size of the string" I would still strncpy just in case, cant be too careful in C
If you use strncpy() and the length is too short you end up with an unterminated string. It prevents buffer overflow, but causes other problems. It's not a magic bullet.
TIL that strncpy_s is part of C11. So thats what should be used

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.