-1

I have a problem understanding how this works out :

struct main_s {
   char test[1];
};

Is it a 2 dimensional array test[1][x] ? For example how to pass a string "Hello World" to the field of the structure ?

char array[1][11] = { {"H","e","l","l","o"," ","W","o","r","l","d"} };

and main_s->test = array doesn't work, compiler gives error about types, 1 is char [] and another char*.

  • You're not clear at all about what you're asking, but this looks like our old friend the _struct hack_ ( http://stackoverflow.com/questions/3711233/is-the-struct-hack-technically-undefined-behavior ). Does the reference answer your question? – This isn't my real name May 14 '13 at 06:01
  • "Is it a 2 dimensional array test[1][x]?" What?! Where do you see the two dimensions? – Daniel Daranas May 14 '13 at 08:15

3 Answers3

1

how to pass a string "Hello World" to the field of the structure ?

You have first to declare sufficient memory space for test array to contain your desired string. the "Hello World" contains 11 charachters. so your array should contains at least 12 elements

struct main_s {
   char test[12];
};

and then copy your string into the array with:

struct main_s m;
strcpy(m.test, "Hello World");
printf("%s\n", m.test) // this display the content of your char array as string

If you want to declare a 2D array:

struct main_s {
   char test[3][13];
}

struct main_s m;
strcpy(m.test[0], "Hello World0");
strcpy(m.test[1], "Hello World1");
strcpy(m.test[2], "Hello World2");
printf("%s\n%s\n%s\n", m.test[0], m.test[1], m.test[2]);

The

strcpy(m.test[1], "Hello World1");

is equivalent to:

m.test[1][0]='H';
m.test[1][1]='e';
m.test[1][2]='l';
.
.
m.test[1][10]='d';
m.test[1][11]='1';
m.test[1][12]='\0'; //add null charachter at the end. it's mandatory for strings

The above code are not allowed

m.test[1] = "Hello World1";
m.test[1] = {'H','e','l','l','o',' ','W','o','r','l','d','1'};
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
0

You can not pass the string "Hello world" to this array. It is a single char variable.

char test[1]; is similar to char test;.

Change the structure as follows to store the address,

struct main_s { char *test; };

Now the following code will work.

char array[1][11] = { {"H","e","l","l","o"," ","W","o","r","l","d"} };

struct main_s var;
var->test = array;
Deepu
  • 7,592
  • 4
  • 25
  • 47
0

Your char array is an array of size 1, so you can only fit one char in there. If you want to pass Hello World to this struct, it would be like this:

 struct main_s{
    char * test;

 };

 int main(){
    struct main_s a;
    a.test = malloc(sizeof(n)) //Where n is the size you want so how ever many chars hello world is followed by null
    memcpy(a, "Hello World\0")
  }

This is basically how it works. You need to copy Hello World\0 into the memory allocated to hte pointer.

KrisSodroski
  • 2,796
  • 3
  • 24
  • 39