C - Concatenate char (Not STRCAT)

0

I have 2 variables: char x[100] and char c;

At first, I needed to store c within x . I did this:

x[0] = c;

Within my program, after the one previously executed, the c variable changes value. So I need to concatenate the value of c next to x that has already been filled. I tried to do this:

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

But it did not work.

Using StrCat does not solve.

    
asked by anonymous 11.06.2015 / 17:45

1 answer

2

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

Getting

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

Depending on your code you do not even need to add 1, eg

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

int main()
{
    char x[TAMANHO];
    memset(&x, '
x[strlen(x)+1] = c; 
', 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; }

Output

  

ab

Ideone Example

Changes suggested by ctgPi and jsbueno .

    
11.06.2015 / 18:05