0
char str1[20] = "Something";
char *str2 = "Random";
strcat(str1, str2[1]);

It gives the error pointer from integer without a cast why is str2[1] treated as an integer? so what should I do if I want to strcat individual elements in a string Thanks!

5 Answers 5

3

Because an element from a char array is a char, which is an integral type. If you want a pointer to the second element, try str2 + 1 or &str2[1].

Sign up to request clarification or add additional context in comments.

1 Comment

Brace yourself for another question when the OP's program croaks after attempting to write to unallocated space.
0

With str2[1] the 2nd character is meant (starting at index 0), which is the 'a' in 'Random'.

If you want the complete string you need to write str2 instead of str2[1].

Comments

0

strcat is expecting pointers to chars, but str2[1] is a char value, modify it to be &str2[1] to get back a pointer to the second char in str2.

Comments

0

str2[1] is of type char while in the strcat(), a char * is expected. Here you should have used str2 + 1.

Comments

0

str2[1] is a char which is promoted to an int according to C type promotion rules. If you want to append a single character to a string, try the following:

int len = strlen(str1);
str1[len] = str2[1];
str1[len + 1] = '\0';

In other words, strlen only concatenates two strings, not a string and a character.

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.