-5

I have problem to compile the following lines:

/*This code compiles with error*/
char HeLev1[6];
HeLev1[]="45.0";
/*but this is OK:*/
char HeLev1[6]="45.0";
Jani
  • 1

2 Answers2

5

You cannot assign values to an array. You need to assign values to array elements one-by-one (or, when dealing with strings, using strcpy())

char HeLev1[6];
strcpy(HeLev1, "45.0");

char HeLev2[6];
HeLev2[0] = '4';
HeLev2[1] = '5';
HeLev2[2] = '.';
HeLev2[3] = '0';
HeLev2[4] = '\0'; /* properly "terminate" the string */

Note that in your code, the OK part, you have an array initialization, not assignment.

Also note that, in both cases above, the 6th element (HeLev1[5] or HeLev2[5]) has an undefined value (garbage).

pmg
  • 106,608
  • 13
  • 126
  • 198
  • Doesn't your first example miss the nul char too? OR is it implicit? I can't remember –  Apr 25 '13 at 20:39
  • You can always `memcpy()` arrays, no? – millimoose Apr 25 '13 at 20:40
  • 1
    @0A0D: The nul char is implicit. You just need to make sure there is enough space in the array for all the characters **and** the nul char. – pmg Apr 25 '13 at 20:40
  • @millimoose: Yes, but don't do that: http://stackoverflow.com/a/1454018/195488 –  Apr 25 '13 at 20:40
  • @0A0D: I meant in the general case, for not-strings, as a contradiction to the "you need to assign values to array elements one-by-one" part. Assuming that you have an array with a known length etc. – millimoose Apr 25 '13 at 20:43
  • @millimoose: yes, you can use `memcpy()` or `memmove()` which, just like `strcpy()`, are nothing but element-by-element copies in a loop :) – pmg Apr 25 '13 at 20:45
  • @pmg This doesn't seem to hold true for `glibc`. There's a whole bunch of architecture specific assembly in the source providing optimised implementations. – millimoose Apr 26 '13 at 01:57
  • 1
    @millimoose: well sure, but how was I supposed to know? We are talking about char arrays here :) –  Apr 26 '13 at 12:25
-1

you can assign whole values to an array only while initialization. like these are correct forms,

char HeLev1[6]="45.0";
int array[3]={1,2,3};
char HeLev1[]="45.0";
int array[]={1,2,3};

but once you have skipped this part. you have to assign element by element. like,

    char HeLev2[6];
    HeLev2[0] = '4';
    HeLev2[1] = '5';
    HeLev2[2] = '.';
    HeLev2[3] = '0';
    HeLev2[4] = '\0'; /* properly "terminate" the string */

or you can use memcpy or strcpy.

Nasif Imtiaz Ohi
  • 1,563
  • 5
  • 24
  • 45