-2

Im learning how to combine two arrays and made this simple code to understand it. I keep getting the error "array must be initialized with a brace-enclosed initializer" what does this mean and how can I fix it? thx

char a[20] ="hello";

char b[20] = "there";

char c[40] = strcat(a, b);



int main()

{

     printf("%s", c);

}
pat101
  • 1

2 Answers2

3

char c[40] = strcat(a, b);

is invalid because you try to assign an array with a pointer

If you really want to use arrays :

#include <stdio.h>
#include <string.h>

char a[20] ="hello";

char b[20] = "there";

int main()

{
     char c[40];

     strcpy(c, a);
     strcat(c, b);

     puts(c);
}

or just

#include <stdio.h>
#include <string.h>

char a[20] ="hello";

char b[20] = "there";

int main()

{
     strcat(a, b);

     puts(a);
}

Compilation and execution :

pi@raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall c.cc
pi@raspberrypi:/tmp $ ./a.out
hellothere
pi@raspberrypi:/tmp $ 

but this is C code and you used C++ tag, strcpy and strcat suppose the receiver have enough space, and if this is false the behavior is undefined. Use the std::string to avoid these problems and more

bruno
  • 32,421
  • 7
  • 25
  • 37
2

In C++ you might as well use string to do it.

#include <string>
#include <iostream>

// ...

std::string a = "hello";
std::string b = "world";
std::string c = a + b;
std::cout << c << std::endl;
Swordfish
  • 12,971
  • 3
  • 21
  • 43
chamip
  • 31
  • 5