Two sources of access violation in your case
String literals are read only and writing to them is undefined behavior
In c arrays are 0
index based, so strs[2]
does not exist, only strs[0]
and strs[1]
.
Using const
prevents you from accidentally modifying them, but it does not forbid you.
Arrays are modifiable though,
#include <stdio.h>
#include <string.h>
int
main(void)
{
char strs[2][11] = {"Hello", "World"};
strcat(strs[0], strs[1]);
return 0;
}
the above works as you expected it.
Here it is how you would do it correctly with dynamic allocation
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *
autostrcat(const char *const head, const char *const tail)
{
char *result;
size_t headlen;
size_t taillen;
if ((head == NULL) || (tail == NULL))
return NULL;
headlen = strlen(head);
taillen = strlen(tail);
result = malloc(1 + headlen + taillen);
if (result == NULL)
return NULL;
memcpy(result, head, headlen);
memcpy(&result[headlen], tail, taillen);
result[headlen + taillen] = '\0';
return result;
}
int
main(void)
{
const char *strs[2] = {"Hello", "World"};
char *result = autostrcat(strs[0], strs[1]);
if (result != NULL)
printf("%s\n", result);
free(result);
return 0;
}
Since you used strlen()
you know what the lengths of the strings are, so using strcat()
would be unecessarily expensive because it would again figure out the length of the first string as strlen()
does.