I have my struct like below , there can be n number of vendor which can contain n number of test struct.
I am trying to initialize this structure . This is a sample code I am trying , later I want to make it using macros and load the structure like X-macros.
I am also using flexible structure concept as I do not know how many test structs for a vendor are going to be. The data would be in a file , the struct needs to load all that is there. I have created a minimal sample code for SO.
Below is my code.
#include <stdio.h>
typedef struct test{
int a;
int b;
int c;
}test;
typedef struct vendor{
int size;
test t[0];
}vendor;
vendor v[]={
{.size = 1, .t[] = {{1,2,3},}}
};
int main()
{
return 0;
}
I get this error -
a.c:16: error: expected expression before ‘]’ token
a.c:16: error: array index in initializer not of integer type
a.c:16: error: (near initialization for ‘v[0].t’)
a.c:16: error: extra brace group at end of initializer
a.c:16: error: (near initialization for ‘v[0]’)
a.c:16: error: extra brace group at end of initializer
a.c:16: error: (near initialization for ‘v[0]’)
a.c:16: warning: excess elements in struct initializer
a.c:16: warning: (near initialization for ‘v[0]’)
I have tried without flexible struct , no luck so far.
any suggestions on how to init this struct ?
The .t[]= syntax in the initializer is invalid. When using a designated initializer, you only need to specify the name of the member:
.t={1, 2, 3}
However, this still won't work with a flexible array member.
The size of a struct with a flexible array member doesn't include space for the flexible array member, so you can't created a static or automatic instance of it. You need to allocate memory for the struct dynamically:
vendor *v;
void init()
{
v = malloc(sizeof(vendor) + 1 * sizeof(test));
v.size = 1;
v.t = (test){1, 2, 3};
}
int main()
{
init();
return 0;
}
Also, because of the variable size, a struct with a flexible array member cannon be a member of an array.
Related
Here I'm a bit confused about this code:
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
struct test_struct {
uint8_t f;
uint8_t weird[];
};
int main(void) {
struct {
struct test_struct tst;
uint8_t weird[256];
} test_in = {};
printf("%u\n", test_in.weird[0]); // 0
test_in.tst.weird[0] = 1;
printf("%u\n", test_in.weird[0]); // 1
return 0;
}
I didn't know that it is possible to use struct's fields this way, so I have two questions:
How is it called in C?
And, of course, how does it work? (Why weird field was changed when I don't change it directly, I thought these are two different fields?)
Here I'm a bit confused about this code:
The short answer is: the code has undefined behavior.
How is it called in C? How does it work?
struct test_struct is defined with its last member as an array of unspecified length: uint8_t weird[]; This member is called a flexible array member, not to be confused with a variable length array.
6.7.2 Type specifiers
[...]
20 As a special case, the last member of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply. However, when a . (or ->) operator has a left operand that is (a pointer to) a structure with a flexible array member and the right operand names that member, it behaves as if that member were replaced with the longest array (with the same element type) that would not make the structure larger than the object being accessed; the offset of the array shall remain that of the flexible array member, even if this would differ from that of the replacement array. If this array would have no elements, it behaves as if it had one element but the behavior is undefined if any attempt is made to access that element or to generate a pointer one past it.
if you allocate such a structure from the heap with extra space for array elements, these elements can be accessed via the weird member up to the number of elements thus allocated.
The C Standard mandates that such a structure can only be defined as a member of another structure or union if it appears as the last member of said aggregate. In the posted code, the programmer violates this constraint, so accessing elements of test_in.tst.weird has undefined behavior, and so does accessing elements of test_in.weird.
The programmer also assumes that the test_in.tst.weird array and the test_in.weird array overlap exactly, which may be the case but is not guaranteed, nor supported: code relying on this type of aliasing has undefined behavior as well.
In your example, assuming the compiler accepts the empty initializer {} (part of the next C Standard and borrowed from C++), it seems to work as expected, but this is not guaranteed and alignment issues may cause it to fail as shown in the modified version below:
#include <stdint.h>
#include <stdio.h>
struct test_struct {
uint8_t f;
uint8_t weird[];
};
struct test_struct1 {
int x;
uint8_t f;
uint8_t weird[];
};
int main(void) {
struct {
struct test_struct tst;
uint8_t weird[256];
} test_in = {};
struct {
struct test_struct1 tst;
uint8_t weird[256];
} test_in1 = {};
printf("modifying test_in.weird[0]:\n");
printf("%u\n", test_in.weird[0]); // 0
test_in.tst.weird[0] = 1;
printf("%u\n", test_in.weird[0]); // 1
printf("modifying test_in1.weird[0]:\n");
printf("%u\n", test_in1.weird[0]); // 0
test_in1.tst.weird[0] = 1;
printf("%u\n", test_in1.weird[0]); // 0?
return 0;
}
Output:
chqrlie$ make 220930-flexible.run
clang -O3 -std=c11 -Weverything -o 220930-flexible 220930-flexible.c
220930-flexible.c:17:28: warning: field 'tst' with variable sized type 'struct test_struct' not at
the end of a struct or class is a GNU extension [-Wgnu-variable-sized-type-not-at-end]
struct test_struct tst;
^
220930-flexible.c:19:17: warning: use of GNU empty initializer extension [-Wgnu-empty-initializer]
} test_in = {};
^
220930-flexible.c:22:29: warning: field 'tst' with variable sized type 'struct test_struct1' not
at the end of a struct or class is a GNU extension [-Wgnu-variable-sized-type-not-at-end]
struct test_struct1 tst;
^
220930-flexible.c:24:18: warning: use of GNU empty initializer extension [-Wgnu-empty-initializer]
} test_in1 = {};
^
4 warnings generated.
modifying test_in.weird[0]:
0
1
modifying test_in1.weird[0]:
0
0
struct test_struct {
uint8_t f;
uint8_t weird[];
};
int main(void) {
struct {
struct test_struct tst;
uint8_t weird[256];
} test_in = {};
Effectively, before there were FAM's in the language, what you've declared is:
int main(void) {
struct {
struct { uint8_t f; } tst;
union {
uint8_t weird0[1]; // any non-zero size up to 256
uint8_t weird1[256];
} overlay;
} test_in = {};
On the contrary as described in the comments section above, a declaration like
int array[];
is not a Variable Length Array, it's either called Arrays of unknown size (cppreference) or Arrays of Length Zero (gcc).
An example of a VLA would be:
void foo(size_t n)
{
int array[n]; //n is not available at compile time
}
Based on the comment below (from the cppreference - see provided link):
Within a struct definition, an array of unknown size may appear as the last member (as long as there is at least one other named member), in which case it is a special case known as flexible array member. See struct (section Explanation) for details:
struct s { int n; double d[]; }; // s.d is a flexible array member
struct s *s1 = malloc(sizeof (struct s) + (sizeof (double) * 8)); // as if d was double d[8]
The provided code is just invalid.
You declared a structure with a flexible array member
struct test_struct {
uint8_t f;
uint8_t weird[];
};
From the C Standard (6.7.2.1 Structure and union specifiers)
18 As a special case, the last element of a structure with more than
one named member may have an incomplete array type; this is called a
flexible array member.
As it is seen from the quote such a member must be the last element of a structure. So the above structure declaration is correct.
However then in main you declared another unnamed structure
int main(void) {
struct {
struct test_struct tst;
uint8_t weird[256];
} test_in = {};
//...
that contains as member an element of the structure with the flexible array element that now is not the last element of the unnamed structure. So such a declaration is invalid.
Secondly, you are using empty braces to initialize an object of the unnamed structure. Opposite to C++ in C you may not use empty braces to initialize objects.
It's an extremely simple and useless piece of practice code I'm working with in what is starting to seem like and extremely useless book. I was doing a struct exercise, and upon code compilation I received a handful of errors.
Here's the offending code:
struct fish = {
const char *name;
const char *species;
int teeth;
int age;
};
void catalog(struct fish f)
{
printf("%s is a %s with %i teeth. He is %i.\n", f.name, f.species, f.teeth, f.age);
}
int main()
{
struct fish snappy = {"Snappy", "piranha", 69, 4};
catalog(snappy);
return 0;
}
This is the exact code from the book, minus the struct definition above catalog. I ended up just copy pasting because I started to suspect this book was just dead wrong. The book claimed that the above code should compile and run without the struct even being defined. I've tried putting the struct definition into a header file, and I've tried removing it or adding it to different parts of the code. I get the same exact errors:
snappy.c:8:13: error: expected identifier or ‘(’ before ‘=’ token
struct fish = {
^
snappy.c:16:26: error: parameter 1 (‘f’) has incomplete type
void catalog(struct fish f)
^
snappy.c: In function ‘main’:
snappy.c:24:12: error: variable ‘snappy’ has initializer but incomplete type
struct fish snappy = {"Snappy", "piranha", 69, 4};
^
snappy.c:24:12: warning: excess elements in struct initializer
snappy.c:24:12: warning: (near initialization for ‘snappy’)
snappy.c:24:12: warning: excess elements in struct initializer
snappy.c:24:12: warning: (near initialization for ‘snappy’)
snappy.c:24:12: warning: excess elements in struct initializer
snappy.c:24:12: warning: (near initialization for ‘snappy’)
snappy.c:24:12: warning: excess elements in struct initializer
snappy.c:24:12: warning: (near initialization for ‘snappy’)
snappy.c:24:17: error: storage size of ‘snappy’ isn’t known
struct fish snappy = {"Snappy", "piranha", 69, 4};
struct fish = { is wrong in struct declaration. It should be struct fish {. Remove = sign.
I've been quite aways away from C and as I am diving back into it I have found myself hitting a roadblock. I have the following structure:
typedef struct{
char id;
struct S *children[SIZE];
}S;
In my code I initially declare an array of structs...
struct S arr[SIZE];
But when I get to this point of trying to allocate my first child for my first member of arr...
arr[0].children[0] = (S*)malloc(sizeof(S));
I get this warning: warning: incompatible implicit declaration of built-in function ‘malloc’ warning: assignment from incompatible pointer type [enabled by default]
On top of this I'm getting an error that doesn't sound very logical to me. I have the following function:
int foo(S *children[SIZE]);
but when I call this line....
foo(arr[0].children);
I get this note: note: expected ‘struct S **’ but argument is of type ‘struct S **’
which to me just sounds silly, it is expecting the argument it is getting and is upset about it.
Any help in explaining what I should be doing to properly allocate this memory and achieve the same idea would be very much appreciated.
There is no struct S, only S which is a typedef of anonymous structure.
Define struct S too:
typedef struct S {
char id;
struct S *children[SIZE];
}S;
Or:
typedef struct S S;
struct S {
char id;
S *children[SIZE];
};
And do avoid casting return of malloc in C:
arr[0].children[0] = malloc(sizeof(S));
For your first problem, you need to do:
#include <stdlib.h>
at the top of your program, in order to call malloc successfully.
The second problem (as also pointed out by others) is that struct S in your class definition refers to a different struct than S. In C, struct tags are in a different "namespace" than type names.
I'm currently learning C. I've been playing around with typedef and structs, and ran into a strange error (at least to my inexperienced eyes).
I am using a typedef to create a dimensions type (int array of two values), and I have a struct that uses that type def.
Upon trying to specify values for the field in my main, I run into an error:
error: expected expression before ‘{’ token
The code:
typedef int dimensions[2];
struct television
{
dimensions resolution;
};
int main()
{
struct television theTV;
theTV.resolution = {1024, 768};
return 0;
}
It's a very contrived example -- is it possible to initialise the .resolution variable in this way?
Use instead:
struct television theTV = {{1024, 768}};
{} initializer list can only be use in a declaration and cannot be used in a statement.
You are not allowed to use assignment to an array, since it is a non-modifiable l-value. However, you can use memcpy() with a compound literal:
memcpy(theTV.resolution, (dimensions){1024, 768}, sizeof(dimensions));
When I initialize this array inside my struct. I get the error message -
syntax error : '{'.
Unexpected token(s) preceding '{'; skipping apparent function body.
int array[8][2] = {{3,6},{3,10},{3,14},{8,4}, {8,8},{8,12},{8,16},{12,2}};
I'm not sure what is wrong as I copied the syntax from my textbook.
Declaration is typedef struct _array *Array;
You cannot initialize a variable inside a struct declaration, doesn't matter if an array or int. Yet, you can initialize the array in the struct initialization.
struct foo {
int x;
int array[8][2];
};
struct foo foovar = {1, {{3,6},{3,10},{3,14},{8,4}, {8,8},{8,12},{8,16},{12,2}}};