首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >strcat()不能连接

strcat()不能连接
EN

Stack Overflow用户
提问于 2015-05-14 04:51:02
回答 2查看 405关注 0票数 0

我有一个二维字符数组要连接到一个数组中。它有一个错误:

错误C2664:“strcat”:无法将参数1从“char*80”转换为“char*”

下面是代码:

代码语言:javascript
复制
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
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-05-14 05:02:37

这里有一些可以做你想做的事情的修正代码,但是很难确定你想要什么.

代码语言:javascript
复制
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);
票数 2
EN

Stack Overflow用户

发布于 2015-05-14 05:05:55

你对句子的定义有错误。您正在使用的代码char * that 80定义了一个指向80个字符串指针的数组。不要使用*限定符。下面是一些代码:

代码语言:javascript
复制
#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。虽然发布的代码不会使缓冲区溢出,但今天的代码重用程度很高,但是检查目标的大小是很好的做法,这样就不会引入安全漏洞。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30229460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档