is it possible to initialise a char array separately from where it is declared without using either a for loop or initialising the array character by character?
is it possible to initialise a char array separately from where it is declared without using either a for loop or initialising the array character by character?
Yes.
I don't care if someone doesn't like me, i was not put on earth to entertain everyone.
No King, no Queen, I am the ACE of battle.
You can use string functions. but you cannot assign since array is not first-class in C.
Eg.
Code:char str[100]; strcpy(str,"hello");
If you can use c99, I believe using compound literals is the closest to what your asking.
Code:char *arr; arr = ((char []){"Hello"});
Well, you are assigning pointer. not array.
Just like you I provided an alternative solution, I don't see the problem? I was clear that it's the closest thing (I know of) to an assignment. After the assignment arr, behaves and functions just like a normal array in terms of indexing and so on.
Last edited by Subsonics; 03-21-2011 at 07:02 AM.
Because OP is asking 'is it possible to initialise a char array separately from where it is declared'.
You canNOT assign to an array. C (including C99) only allows to initialize array.
Yes, so the correct answer to the question is, NO. What both you and me are doing here is to offer an alternative solution.
You can cheat.Technically it's not assigning arrays, so no, you can't actually assign an array. But you can cheat your way around it.Code:#include<stdio.h> struct foo { char bar[10]; }; #define CHEAT(x,y) *((struct foo *)(x)) = (y) #define CHEATA(x,y) *((struct foo *)(x)) = *((struct foo *)(y)) int main( void ) { char bar[10] = {0}; char foo[10] = { "world" }; struct foo baz = { "hello" }; CHEAT(bar, baz) ; printf( "I cheated: %s\n", bar ); CHEATA( bar, foo ) ; printf( "I cheated: %s\n", bar ); return 0; }
Quzah.
Last edited by quzah; 03-21-2011 at 03:11 PM. Reason: added CHEATA
Hope is the first step on the road to disappointment.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"