strcat() 无法连接
strcat() could not concatenate
我有一个二维字符数组要连接成一个数组。它有一个错误:
error C2664: 'strcat' : cannot convert parameter 1 from 'char *[80]' to 'char *'
代码如下:
char *article[5] = {"the", "a", "one", "some", "any"};
char *sentence[80];
num = rand() % 5;
for(int x = 0; x < strlen(article[num]); x++){
strcat(sentence, article[num][x]); //a random element will be concatinated to the sentence array
}
这里有一些固定的代码,可以满足您的需求,但很难确定您想要什么...
srand(time_t(0)); // seed the random number generate once
// use const when handling pointers to string literals
const char* article[5] = {"the", "a", "one", "some", "any"};
char sentence[80]; // 80 character buffer in automatic storage - no pointers
sentence[0] = '[=10=]'; // empty ASCIIZ string to start
for (int x = 0; x < 5; ++x)
{
int num = rand() % 5;
strcat(sentence, article[num]);
}
printf("%s\n", sentence);
您对句子的定义有误。您正在使用的代码 char *sentence[80] 定义了一个指向 80 个字符串指针数组的指针。不要使用 * 限定符。这是一些代码:
#define MAX_ARRAY 5
#define MAX_SENTENCE 80
char *article[MAX_ARRAY] = {"the", "a", "one", "some", "any"};
char sentence[MAX_SENTENCE];
int num;
num = rand() % MAX_ARRAY
strncat(sentence, article[num], MAX_SENTENCE - 1);
sentence[MAX_SENTENCE - 1] = 0x00;
请注意,我使用 strncat 而不是 strcat。尽管您发布的代码不会溢出缓冲区,但鉴于当今代码重用的规模,检查目标大小始终是一个好习惯,这样您就不会引入安全漏洞。
我有一个二维字符数组要连接成一个数组。它有一个错误:
error C2664: 'strcat' : cannot convert parameter 1 from 'char *[80]' to 'char *'
代码如下:
char *article[5] = {"the", "a", "one", "some", "any"};
char *sentence[80];
num = rand() % 5;
for(int x = 0; x < strlen(article[num]); x++){
strcat(sentence, article[num][x]); //a random element will be concatinated to the sentence array
}
这里有一些固定的代码,可以满足您的需求,但很难确定您想要什么...
srand(time_t(0)); // seed the random number generate once
// use const when handling pointers to string literals
const char* article[5] = {"the", "a", "one", "some", "any"};
char sentence[80]; // 80 character buffer in automatic storage - no pointers
sentence[0] = '[=10=]'; // empty ASCIIZ string to start
for (int x = 0; x < 5; ++x)
{
int num = rand() % 5;
strcat(sentence, article[num]);
}
printf("%s\n", sentence);
您对句子的定义有误。您正在使用的代码 char *sentence[80] 定义了一个指向 80 个字符串指针数组的指针。不要使用 * 限定符。这是一些代码:
#define MAX_ARRAY 5
#define MAX_SENTENCE 80
char *article[MAX_ARRAY] = {"the", "a", "one", "some", "any"};
char sentence[MAX_SENTENCE];
int num;
num = rand() % MAX_ARRAY
strncat(sentence, article[num], MAX_SENTENCE - 1);
sentence[MAX_SENTENCE - 1] = 0x00;
请注意,我使用 strncat 而不是 strcat。尽管您发布的代码不会溢出缓冲区,但鉴于当今代码重用的规模,检查目标大小始终是一个好习惯,这样您就不会引入安全漏洞。