C - Concatenate char (Not STRCAT)

Asked

Viewed 3,252 times

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.

1 answer

2

Your problem is here strlen(x +1), the correct would be strlen(x) + 1.

Staying

x[strlen(x)+1] = c; 

Depending on your code you don’t even need add up 1, example:

#include <stdio.h>
#include <string.h>
#define TAMANHO 100

int main()
{
    char x[TAMANHO];
    memset(&x, '\0', sizeof(char)*TAMANHO);
    char c = 'a';
    x[strlen(x)] = c; // strlen(x) retorna 0 porque está vazio
    c = 'b';
    x[strlen(x)] = c; // strlen(x) retorna 1 porque já possui 1 elemento

    printf("%s", x);
    return 0;
}

Exit

ab

Ideone Exemplo

Changes suggested by ctgPi and jsbueno.

  • 2

    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.

  • Rodei yes @jsbueno and in the compiler that use (online) worked exactly as shown if you do char x[100] = "" already initializes everything with 0 also, no?

  • I’m no expert on C, I just know what I saw in college and playing.

  • 1

    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

  • 1

    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 do memset(&x, 0, sizeof(x)) or move x for global scope (there is 100% guaranteed that the vector comes zeroed).

  • @ctgPi I changed the code, a check :)

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.