It prints nothing.I think the problem is at the type char * but i dont know if and why.
int main() {
char *a = "0123456789" ;
char *b = "abcdefghij" ;
strcat (a,b) ;
printf( "%s", a ) ;
}
It prints nothing.I think the problem is at the type char * but i dont know if and why.
int main() {
char *a = "0123456789" ;
char *b = "abcdefghij" ;
strcat (a,b) ;
printf( "%s", a ) ;
}
strcat
modifies the destination
parameter buffer, but a
's buffer is in read-only memory as it's a string literal.
The solution is to create a buffer at runtime and use that as the buffer. You'll need to copy a
into it first, of course.
char* a = "1234567890";
char* b = "abcdefghij";
size_t aLen = strlen( a );
char* combined = malloc( sizeof(char) * ( strlen(a) + strlen(b) + 1 ) );
strcpy_s( combined, aLen, a ); // always use _s versions of string/buffer functions!
strcat( combined, b );
puts( combined );
free( combined );
Alternatively in C99 we could just use a stack-allocated array that's preinitialized (and preallocated to be large enough). Stack arrays, including pre-initialized ones, can have their buffer written to:
char a[100] = "1234567890";
strcat( a, "abcdefghij" );
puts( a );
You cant cat to string literal as dest. Use an array as dest buffer
char str[30] = "Ala ";
const char *strFrom = "ma kota";
strcat (str, strFrom);
edit: extending the answer
Take a look how string literals get compiled: https://godbolt.org/g/hZuR1o
Array buffer is defined inline and it's value is constructed during execution and is located on the stack. Thus the buffer itself can be freely modified.
If you allocated it dynamically (with malloc or calloc), you'd get a pointer to the buffer on the heap which could be modified as well.
String literals on the other hand land in read-only memory regions and are shared across various instances since they're read-only anyway. That's how it's designed, man:)