0

I was about to initialize a char array inside a class as

class a{ char a[25]; }; a::a(){ a[] = {'a','b','c'}; } 

but gives compile time error.

6
  • 1
    You can initialize it in class constructor. Commented Jul 25, 2012 at 6:27
  • My answer on this other question might help you. Commented Jul 25, 2012 at 6:27
  • @ArunJain thats what im doing..isnt it..second part a(){}?? Commented Jul 25, 2012 at 6:29
  • Does it have to be char array? Can't you use std::string? Commented Jul 25, 2012 at 6:29
  • char array it has to be. Commented Jul 25, 2012 at 6:30

2 Answers 2

5

If your compiler supports the C++11 feature, you can do it like this:

a::a() :arr({'a','b','c'}) {} 

Otherwise, you'll have to do it manually, or you can use a function like memcpy:

a::a() { memcpy(arr,"abc",3); // The other initialization method will fill the rest in with 0, // I don't know if that's important, but: std::fill(arr + 3, arr + 25, '\0'); } 

Or, as suggested by ephemient:

a::a() { strncpy(arr, "abc", 25); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Another possibility: when strncpy is available, it always pads with \0 to fill -- strncpy(a, "abc", 25) will write 25 bytes, the last 22 of which are NUL.
1
class LexerP { public: char header[5]; void h(); void echo(){printf(" salut les gars ...\n \n");}; }; void LexerP::h() { int i=0; int j=0; char headM[5] ={0x07,0x0A,0x05,0x00,0x05}; /* for (i=0;i<strlen(this->header);i++) header[i]=headM[i];*/ strcpy(this->header,headM) }; main() { LexerP *M=new (LexerP); M->echo(); M->h(); return 0; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.