Reputation: 75
I have a two-dimensional character array to be concatenated into an array. It has an error:
error C2664: 'strcat' : cannot convert parameter 1 from 'char *[80]' to 'char *'
Here's the code:
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
}
Upvotes: 0
Views: 430
Reputation: 1439
You have an error in your definition for sentence. The code that you are using, char *sentence[80] is defining a pointer to an array of 80 string pointers. Don't use the * qualifier. Here's some code:
#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;
Notice that I use strncat instead of strcat. Although your code as posted will not overflow the buffer, with today's magnitude of code reuse, it's always good practice to check the size of the destination so you don't introduce a security vulnerability.
Upvotes: 1
Reputation: 106196
Here's some fixed up code that might do what you want, but it's hard to tell what you want for sure...
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);
Upvotes: 2