How to concatenate a char into a string?

Asked

Viewed 2,210 times

4

I’m trying to copy the char E for the component char of my struct No:

void push(Pilha* p, char E)
{
    No* novo = (No*)malloc(sizeof(No));

    strcpy(novo->simbolo, E);
    novo->prox = p->topo;
    p->topo = novo;

    p->tam += 1;
}

typedef struct No
{
  char simbolo;
  struct No* prox;
} No;

However, the compiler gives me the Warning:

Passing argument 1 of 'strcpy' makes Pointer from integer without a cast.

I wanted to know how to leave the value of E in novo->simbolo.

2 answers

5

You are confusing letter with text (character with string).

In C a letter or a character is defined by type char.
A string or text is defined as an array of characters and will normally be written as char[] or char*.

To modify a character just change directly as if it were an integer or other basic type:

char letra = 'a';
letra = 'z';

Now if you have a text you cannot modify directly because the text is actually a set of letters (array) and you must make the change based on the function strcpy:

char texto[30] = "ola";
strcpy(texto, "mundo");

In your code you have only one letter but are trying to change with strcpy which is for texts, so it’s not correct. Also concatenating means adding a letter to a text that also doesn’t represent what you’re doing.

The solution is to remove the strcpy that is not correct and put a normal assignment of a char, just as p->simbolo = E;.


Responding now to the question you have in the title and that is not what you want to do:

How to concatenate a char into a string?

To this end can:

  • Check where the last character ends by strlen
  • Place the new character in the position given by strlen
  • Put the terminator back after the new letter

Implementation:

void concatenar_letra(char texto[], char letra){
    size_t tamanho = strlen(texto);
    texto[tamanho] = letra;
    texto[tamanho + 1] = '\0'; //recolocar terminador
}

See an example of this function working on Ideone

Keep in mind that this function assumes that there is space allocated in the string for the new character, otherwise you incur undefined behavior, or you have to add more things to validate.

To concatenate two texts already has a function of C libraries for this, the strcat.

-2

Instead of

strcpy(novo->simbolo, E);

do:

*novo->simbolo = E;
*(novo->simbolo + 1) = 0;
  • Replacing another error appears in the compiler: invalid type argument of unary '*' (have 'int')

  • The field simbolo is a pointer of char?

  • symbol is a char that is inside a no of a struct pointed by new. Being struct No {char simbolo, struct No* Prox};

  • So just do it novo->simbolo = E;.

Browser other questions tagged

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