Consider the code:
#include <stdio.h>
int a[] = { 1, 2, 3 };
int b[];
int main() {
b = { 4, 5, 6 };
return 0;
}
This of course is illegal.
main.c:7:9: error: expected expression before '{' token
7 | b = { 4, 5, 6 };
| ^
I need to initialize array b
in a function. How to do that?
I know one way, but it's... IDK, really?
#include <stdio.h>
int a[] = { 1, 2, 3 };
int b[3];
int main() {
b[0] = 4;
b[1] = 5;
b[2] = 6;
return 0;
}
Is it the only way of doing that?
CodePudding user response:
The proper term is variable length array. This is an array whose size is determined by a non-constant expression. Its size is set at execution time when program execution reaches the definition of the array. (“Flexible” is used in the term flexible array member, which is an array that is the last member of a structure and that adapts to the memory allocated for the structure.)
The size of a variable length array must be given where the array is defined, as with int b[n];
. You cannot leave the size incomplete, as with int b[];
, and specify it later.
C has no grammar for assigning directly to an array. You can assign values to individual elements, and a method for specifying values in aggregate is to use memcpy
to copy them from another array, which can be a compound literal:
#include <stdio.h>
#include <string.h>
int main(void)
{
int n = 3;
int b[n];
memcpy(b, (int []) { 4, 5, 6 }, sizeof b);
for (int i = 0; i < 3; i)
printf("b[%d] = %d.\n", i, b[i]);
}
CodePudding user response:
The first thing that's wrong is
int b[];
This makes no sense. gcc treats this as the following
int b[1];
This is most definitely wrong. You want
int *b;
Cloning a
would be done as follows:
#include <stdlib.h>
#include <string.h>
size_t size = sizeof( a );
b = malloc( size );
if ( !b ) {
perror( "malloc" );
exit( 1 );
}
memcpy( b, a, size );
Don't forget to free( b );
.