0
votes
#include <stdio.h>
#include <string.h>
int main(){
char a[7]= "car";
char b[7]="yyoug";
strcat(a,b[2]);
puts(a);
  return 0;
}

This won't compile. It says "passing argument 2 of 'strcat' makes pointer from integer without a cast." I haven't been taught the use of pointers.

3
b[2] gives the values of the 3rd element in the array. &b[2] gives the address.. That is expected from strcat()Gopi
What's the expected output you're looking for?jeremy
Thanks! but now it will add "oug" to the word "car." All I want is the letter 'o'J_C
Use strcat(a,&b[2]); or strcat(a,b+2);Tom Karzes
If you just want to append one character, you can use strncat(a,&b[2],1);Tom Karzes

3 Answers

3
votes

b[2] is of char type but strcat expects its both arguments are of char * type.
Use strncat instead. It will append only one byte, i.e. b[2] to the first string if the third argument passed is 1

strncat(a, &b[2], 1);
1
votes

If you just want to use strncat because you want to learn how it works, then @hacks example is completly perfect. But if you just want to concat on character to a you can also use

a[3] = b[2];

But please keep in mind, either solution only works, if the the destination array, in your case a is large enough.

0
votes

Without using malloc this might help explain what's going in

#include <assert.h>
#include <stdio.h>
#include <string.h>
int main(){
  //positions  0    1    2    3
  //"car" == ['c', 'a', 'r', '\0']
  char a[7] = "car";
  char b[7] = "yyoug";

  //strlen("car") == 3;
  //"car"[3]      == ['\0']; 

  a[strlen(a)]    = b[2]; 
  assert(a[3] == 'o');

  a[strlen(a) + 1] = '\0';
  assert(a[4] == '\0');
  puts(a); 
    return 0;
}