c - Why use const char *prt1 when we can't change the containing of the pointer -
if use example:
char* strs[2]; strs[1] = "hello"; strs[2] = "world!"; strcat(strs[1],strs[2]);
then access violation comes (access violation writing location 0x0028cc75).
so why use const char *strs[2];
since strs1[1]
, strs1[2]
cannot changed?
two sources of access violation in case
string literals read , writing them undefined behavior
in c arrays
0
index based,strs[2]
not exist,strs[0]
,strs[1]
.
using const
prevents accidentally modifying them, not forbid you.
arrays 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 expected it.
here how correctly 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 used strlen()
know lengths of strings are, using strcat()
unecessarily expensive because again figure out length of first string strlen()
does.
Comments
Post a Comment