Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What values can I use in a C - string?

Tags:

c

I am facing the following code:

char buf[100];
char buf2[100];
strcpy( buf, "áéíóúç" );
sprintf(buf2, "%s", buf);

And I was wondering if it is correct or not. I've tested it in Windows and Linux and it did work, but will it work in all OS/platform of different languages?

Both strcpy and sprintf expects a C-string terminated by a null character, but can the content of the C-string be anything (excluding the null character)?

Is it ok to also do something like:

strcpy( buf, "\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00" );
sprintf(buf2, "%s", buf);

?

like image 986
Renan Greinert Avatar asked Jan 18 '23 11:01

Renan Greinert


2 Answers

A char array is just an array of bytes, and all the non-wide string functions operate on that assumption. The only byte in general that has a special meaning is the null byte.

The C standard, as far as I can remember, doesn't have much to say on the subject of character encodings (or text in general), so your program is bound to fail on a platform where the expected output character encoding doesn't match your code.

like image 200
Matti Virkkunen Avatar answered Jan 28 '23 20:01

Matti Virkkunen


This question is in place, but:

The string functions are stopping only at the NULL character, as the definition of c-string is null-terminated byte buffer. So your example is OK.

like image 43
MByD Avatar answered Jan 28 '23 20:01

MByD