0
#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.

7
  • b[2] gives the values of the 3rd element in the array. &b[2] gives the address.. That is expected from strcat() Commented Mar 22, 2016 at 5:44
  • What's the expected output you're looking for? Commented Mar 22, 2016 at 5:46
  • Thanks! but now it will add "oug" to the word "car." All I want is the letter 'o' Commented Mar 22, 2016 at 5:47
  • 1
    Use strcat(a,&b[2]); or strcat(a,b+2); Commented Mar 22, 2016 at 5:47
  • 1
    If you just want to append one character, you can use strncat(a,&b[2],1); Commented Mar 22, 2016 at 5:49

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.