Reputation: 3
#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.
Upvotes: 0
Views: 99
Reputation: 11678
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;
}
Upvotes: 0
Reputation: 2410
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.
Upvotes: 1
Reputation: 106102
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);
Upvotes: 3