-2
#include <stdio.h>
#include <string.h>

int main(void) {

    char rez[100] = "\0";
    char t = 97;
    char temp;
    strcpy(temp, t);
    strcat(rez, temp);

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

I want to join the character 'a' to the result but strcpy and strcat command do not work. How could I do that if the char t should be an ASCII code?

warning: passing argument 1 of 'strcpy' makes pointer from integer without a cast [-Wint-conversion] strcpy(temp,t); note: expected 'char * restrict' but argument is of type 'char' char * __cdecl strcpy(char * restrict _Dest,const char * restrict _Source);

enter image description here

anastaciu
  • 23,467
  • 7
  • 28
  • 53
Fei Xu
  • 1
  • 1

2 Answers2

0

Both functions work with strings, not with individual characters. It’s often convenient to create a new string of length 1 from the char, and work with that:

char str[] = { t, '\0' };

Now you can concatenate that.

Alternatively, you can implement the concatenation manually by just writing the character into the right location of the resulting array:

const len = strlen(rez);
rez[len] = t;
rez[len + 1] = '\0';

… or you could use the sprintf function:

sprintf(rez, "%s%c", rez, t);

In all cases you need to take care to not accidentally write outside of the bounds of the string.

In your specific case, none of these make sense, since rez is empty to start with; you’re not concatenating anything, you’re just writing a single character into a buffer.

rez[0] = t;
rez[1] = '\0'; // for good measure
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
0

strcpy and strcat expect both of their arguments to have type char * and that both arguments point to the first character of a zero-terminated string.

The problem is that neither t nor temp are pointers, and neither are the first characters of a string so passing &t or &temp will work.

If you want to append a single character to rez, you can do something like

/**
 * Use character literals instead of raw ASCII codes - 
 * it’s easier to understand, it will work as expected
 * on non-ASCII systems, and you’re less likely to make
 * a mistake.
 */
t = 'a'; 
size_t len = strlen(rez);
/**
 * Overwrite the terminator with the value in t, 
 * then write the terminator to the following element
 * (strictly not necessary in this case, but it never
 * hurts to make sure)
 */
rez[len++] = t;
rez[len] = 0;

You could also use the sprintf library function:

sprintf( rez, "%s%c", rez, t );
John Bode
  • 119,563
  • 19
  • 122
  • 198