![](/img/trans.png)
[英]Why can´t we assign a new string to an char array, but to a pointer?
[英]Why use const char *prt1 when we can't change the containing of the pointer
如果我們使用例如:
char* strs[2];
strs[1] = "Hello";
strs[2] = "World!";
strcat(strs[1],strs[2]);
然后出現訪問沖突(訪問沖突寫入位置0x0028CC75)。
那么為什么要使用const char *strs[2];
由於strs1[1]
, strs1[2]
無法更改?
// string literals are non-writeable so const is appropriate here
const char* strs[2] = {"Hello", "World!"};
// let's create a target buffer with sufficient space
char buffer[20];
// copy the first string there
strcpy(buffer, strs[0]);
// add the second string there
strcat(buffer, strs[1]);
您遇到的兩種訪問沖突根源
字符串文字是只讀的,寫入字符串是未定義的行為
在c數組中基於0
索引,因此strs[2]
不存在,只有strs[0]
和strs[1]
。
使用const
可以防止您不小心修改它們,但是並不能禁止您。
數組是可修改的,
#include <stdio.h>
#include <string.h>
int
main(void)
{
char strs[2][11] = {"Hello", "World"};
strcat(strs[0], strs[1]);
return 0;
}
以上工作符合您的預期。
這是通過動態分配正確執行操作的方法
#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;
}
由於您使用strlen()
知道了字符串的長度,因此使用strcat()
會不必要地昂貴,因為它會像strlen()
一樣計算出第一個字符串的長度。
哇。 太錯了。
您應該創建一個緩沖區,然后填充它。
char* concat = (char *) _alloca(strlen(strs[0]) + strlen(strs[1])+1);
strcpy(concat, strs[0]);
strcat(concat, strs[1]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.