0
I have 2 variables: char x[100]
and char c;
At first, I had to store c
inside x
. I did it this way:
x[0] = c;
Inside my program, after the previous run, the variable c
value changes. Then I need to concatenate the value of c
next to the x
that has already been filled. I tried to do so:
x[strlen(x +1)] = c;
but did not resolve.
Using Strcat does not resolve.
You ran this example? You are aware that if it worked it was by chance, isn’t it? The lignuaem C does not specify that after a statement
char x[100];
the content of the 100 positions reserved for x is zero - (your compiler can ae do this "please" - but the content is undefined. Meaning star character at position [0] does not limit string to [1] character length - only if character at position [1] is 0.– jsbueno
Rodei yes @jsbueno and in the compiler that use (online) worked exactly as shown if you do
char x[100] = ""
already initializes everything with0
also, no?– Maicon Carraro
I’m no expert on
C
, I just know what I saw in college and playing.– Maicon Carraro
So I suggest you arrange the answer - at least remove the wrong example, if you will not try to run it - your answer to the question is right (take out the "+1" from within the strlen argument) - but the example has to be either tidied up, or removed - no code is only code that does not compile, is code with concept errors, that runs, and if it is used by others an open port for security failures
– jsbueno
It’s not exactly true that it’s an "accident" that the code works - the memory you receive from the operating system is always zero (to avoid leaking information between processes), so this first allocation in the
main()
always will, yes, be zeroed. But I agree that this is a very heavy edge case - better to domemset(&x, 0, sizeof(x))
or movex
for global scope (there is 100% guaranteed that the vector comes zeroed).– user25930
@ctgPi I changed the code, a check :)
– Maicon Carraro