我有一个二维字符数组要连接到一个数组中。它有一个错误:
错误C2664:“strcat”:无法将参数1从“char*80”转换为“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
}发布于 2015-05-14 05:02:37
这里有一些可以做你想做的事情的修正代码,但是很难确定你想要什么.
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] = '\0'; // empty ASCIIZ string to start
for (int x = 0; x < 5; ++x)
{
int num = rand() % 5;
strcat(sentence, article[num]);
}
printf("%s\n", sentence);发布于 2015-05-14 05:05:55
你对句子的定义有错误。您正在使用的代码char * that 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。虽然发布的代码不会使缓冲区溢出,但今天的代码重用程度很高,但是检查目标的大小是很好的做法,这样就不会引入安全漏洞。
https://stackoverflow.com/questions/30229460
复制相似问题