I want to define a structure on the following way:
typedef struct Info_s
{
uint8 Size;
uint8 Address;
uint8 Pattern[Size];
}Info_t;
As you can notice the size of the array Pattern is "Size" which is declared first in the same structure.
Is that correct?
An array declared as a struct field must either have an integer constant expression as its size or be a flexible array member with no size (uint8 Pattern[];). Your variant is neither.
If the array size in your case is a run-time value, you have two choices
Flexible array member uint8 Pattern[];, which will result in a "flat" struct. The proper amount of memory to accommodate the entire struct with the array of desired length will have to be allocated with malloc manually.
Pointer member uint8 *Pattern;, in which case your struct will become two-leveled. Memory for the struct itself and memory for the array will generally become two separate memory blocks allocated independently.
A flexible array member is typically a better idea (and matches your apparent original intent), unless you have some other requirements that would preclude that aproach.
You can't do that. That is violating the rule. Compile the code and you will know it clearly.
Rather keep a uint8* and then allocate to it memory (using malloc,realloc etc) based on the value of Size.
And now if you increase or decraese the value Size as per that reallocate your memory.
Yes with this, you have to free the dynamically allocated memory when you are done working with it.
Just remove the array size Size in the declaration of Pattern and you will get a valid declaration of a structure with a flexible array member.:)
typedef struct Info_s
{
uint8 Size;
uint8 Address;
uint8 Pattern[];
}Info_t;
Go with
uint8* Pattern;
and use malloc to allocate its size once Size is known.
If you want to dynamically allocate memory to the structure, you can do it in following way :
struct Info_s
{
uint8 Address;
uint8 Pattern[Size];
};
int main()
{
struct Info_s *no;
int i, noOfRecords;
printf("Enter no: ");
scanf("%d", &noOfRecords);
no=(struct Info_s*) malloc (noOfRecords * sizeof(struct course));
for(i=0;i<noOfRecords;++i)
{
scanf(...);
}
.
.
.
return 0;
}
You can also refer https://www.programiz.com/c-programming/examples/structure-dynamic-memory-allocation for more information.
Related
I have looked around but have been unable to find a solution to what must be a well asked question.
Here is the code I have:
#include <stdlib.h>
struct my_struct {
int n;
char s[]
};
int main()
{
struct my_struct ms;
ms.s = malloc(sizeof(char*)*50);
}
and here is the error gcc gives me:
error: invalid use of flexible array member
I can get it to compile if i declare the declaration of s inside the struct to be
char* s
and this is probably a superior implementation (pointer arithmetic is faster than arrays, yes?)
but I thought in c a declaration of
char s[]
is the same as
char* s
The way you have it written now , used to be called the "struct hack", until C99 blessed it as a "flexible array member". The reason you're getting an error (probably anyway) is that it needs to be followed by a semicolon:
#include <stdlib.h>
struct my_struct {
int n;
char s[];
};
When you allocate space for this, you want to allocate the size of the struct plus the amount of space you want for the array:
struct my_struct *s = malloc(sizeof(struct my_struct) + 50);
In this case, the flexible array member is an array of char, and sizeof(char)==1, so you don't need to multiply by its size, but just like any other malloc you'd need to if it was an array of some other type:
struct dyn_array {
int size;
int data[];
};
struct dyn_array* my_array = malloc(sizeof(struct dyn_array) + 100 * sizeof(int));
Edit: This gives a different result from changing the member to a pointer. In that case, you (normally) need two separate allocations, one for the struct itself, and one for the "extra" data to be pointed to by the pointer. Using a flexible array member you can allocate all the data in a single block.
You need to decide what it is you are trying to do first.
If you want to have a struct with a pointer to an [independent] array inside, you have to declare it as
struct my_struct {
int n;
char *s;
};
In this case you can create the actual struct object in any way you please (like an automatic variable, for example)
struct my_struct ms;
and then allocate the memory for the array independently
ms.s = malloc(50 * sizeof *ms.s);
In fact, there's no general need to allocate the array memory dynamically
struct my_struct ms;
char s[50];
ms.s = s;
It all depends on what kind of lifetime you need from these objects. If your struct is automatic, then in most cases the array would also be automatic. If the struct object owns the array memory, there's simply no point in doing otherwise. If the struct itself is dynamic, then the array should also normally be dynamic.
Note that in this case you have two independent memory blocks: the struct and the array.
A completely different approach would be to use the "struct hack" idiom. In this case the array becomes an integral part of the struct. Both reside in a single block of memory. In C99 the struct would be declared as
struct my_struct {
int n;
char s[];
};
and to create an object you'd have to allocate the whole thing dynamically
struct my_struct *ms = malloc(sizeof *ms + 50 * sizeof *ms->s);
The size of memory block in this case is calculated to accommodate the struct members and the trailing array of run-time size.
Note that in this case you have no option to create such struct objects as static or automatic objects. Structs with flexible array members at the end can only be allocated dynamically in C.
Your assumption about pointer aritmetics being faster then arrays is absolutely incorrect. Arrays work through pointer arithmetics by definition, so they are basically the same. Moreover, a genuine array (not decayed to a pointer) is generally a bit faster than a pointer object. Pointer value has to be read from memory, while the array's location in memory is "known" (or "calculated") from the array object itself.
The use of an array of unspecified size is only allowed at the end of a structure, and only works in some compilers. It is a non-standard compiler extension. (Although I think I remember C++0x will be allowing this.)
The array will not be a separate allocation for from the structure though. So you need to allocate all of my_struct, not just the array part.
What I do is simply give the array a small but non-zero size. Usually 4 for character arrays and 2 for wchar_t arrays to preserve 32 bit alignment.
Then you can take the declared size of the array into account, when you do the allocating. I often don't on the theory that the slop is smaller than the granularity that the heap manager works in in any case.
Also, I think you should not be using sizeof(char*) in your allocation.
This is what I would do.
struct my_struct {
int nAllocated;
char s[4]; // waste 32 bits to guarantee alignment and room for a null-terminator
};
int main()
{
struct my_struct * pms;
int cb = sizeof(*pms) + sizeof(pms->s[0])*50;
pms = (struct my_struct*) malloc(cb);
pms->nAllocated = (cb - sizoef(*pms) + sizeof(pms->s)) / sizeof(pms->s[0]);
}
I suspect the compiler doesn't know how much space it will need to allocate for s[], should you choose to declare an automatic variable with it.
I concur with what Ben said, declare your struct
struct my_struct {
int n;
char s[1];
};
Also, to clarify his comment about storage, declaring char *s won't put the struct on the stack (since it is dynamically allocated) and allocate s in the heap, what it will do is interpret the first sizeof(char *) bytes of your array as a pointer, so you won't be operating on the data you think you are, and probably will be fatal.
It is vital to remember that although the operations on pointers and arrays may be implemented the same way, they are not the same thing.
Arrays will resolve to pointers, and here you must define s as char *s. The struct basically is a container, and must (IIRC) be fixed size, so having a dynamically sized array inside of it simply isn't possible. Since you're mallocing the memory anyway, this shouldn't make any difference in what you're after.
Basically you're saying, s will indicate a memory location. Note that you can still access this later using notation like s[0].
pointer arithmetic is faster than arrays, yes?
Not at all - they're actually the same. arrays translate to pointer arithmetics at compile-time.
char test[100];
test[40] = 12;
// translates to: (test now indicates the starting address of the array)
*(test+40) = 12;
Working code of storing array inside a structure in a c, and how to store value in the array elements Please leave comment if you have any doubts, i will clarify at my best
Structure Define:
struct process{
int process_id;
int tau;
double alpha;
int* process_time;
};
Memory Allocation for process structure:
struct process* process_mem_aloc = (struct process*) malloc(temp_number_of_process * sizeof(struct process));
Looping through multiple process and for each process updating process_time dyanamic array
int process_count = 0;
int tick_count = 0;
while(process_count < number_of_process){
//Memory allocation for each array of the process, will be containting size equal to number_of_ticks: can hold any value
(process_mem_aloc + process_count)->process_time = (int*) malloc(number_of_ticks* sizeof(int));
reading data from line by line from a file, storing into process_time array and then printing it from the stored value, next while loop is inside the process while loop
while(tick_count < number_of_ticks){
fgets(line, LINE_LENGTH, file);
*((process_mem_aloc + process_count)->process_time + tick_count) = convertToInteger(line);;
printf("tick_count : %d , number_of_ticks %d\n",tick_count,*((process_mem_aloc + process_count)->process_time + tick_count));
tick_count++;
}
tick_count = 0;
the code generated will be identical (array and ptr). Apart from the fact that the array one wont compile that is
and BTW - do it c++ and use vector
I have this struct:
typedef struct SomeStruct {
char someString[];
} SomeStruct;
This produces an error since someString's size is not defined when initialized.
I want to make someString an array of strings, but I will not know the size of the array at the time of initialization. (The elements that will be in the array will depend on user input later in the program).
Is it possible to initialize this as an array of strings without knowing the size of the array?
Yes, the C standard talks about this in 7.2.18-26. What you are describing is known as a flexible array member of a struct. From the standard:
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.
Essentially what it is saying is, if the last member of the struct is an array of undefined size (as might be the case for runtime sizes), then when using the struct, you would allocate the appropriate size of your struct including how large you want the string to be. For example:
typedef struct SomeStruct {
char someString[];
} SomeStruct;
has the flexible array member someString. A common way to use this is:
SomeStruct *p = malloc(sizeof (SomeStruct) + str_size);
Assuming that the call to malloc succeeds, the object pointed to by p behaves, for most purposes, as if p had been declared as:
struct {char someString[str_size]; } *p;
Read the standard for more detail. The buzzword flexible array member will show up a lot of information too. The wikipedia is a good place to start.
You can use a structure with flexible array. For example
typedef struct SomeStruct
{
size_t n;
char someString[];
} SomeStruct;
where n is used to store the number of elements in the array.
Then you can create objects of the structure the following way
SomeStruct *s = malloc( sizeof( SomeStruct ) + 10 * sizeof( char[100] ) );
s->n = 10;
If you can't use a dynamic array (it sounds like this, if you get a compile error for it), you can actually overrun the array, as long as it's at the end of the struct, and as long as you can actually access that memory. Example:
#include <stdio.h>
#include <stdlib.h>
typedef struct SomeStruct {
char someString[10];
} SomeStruct;
int main (void)
{
// Allocate 4x space, so we have room to overrun
SomeStruct *p = malloc(sizeof(SomeStruct) * 4);
p->someString[38] = 'a';
printf("%c\n", p->someString[38]);
}
Of course, you still have to actually allocate the space, so it may not be so useful to you depending on your case.
I'm programming for embedded, resource constrained devices in C.
I have a structure, like this:
typedef struct UjThread{
struct{
UInt32 runInstr;
UInt8* mailbox;
}appBucket;
struct{
UInt32 appId;
UInt32 numInstr;
UInt32 allocMem;
UInt32 eepromStartAddr;
}appContract;
UInt16 spBase; //we use an empty ascending stack
UInt16 spLimit; //also used for "isPtr"
UInt16 localsBase;
UInt32 stack[];
}UjThread;
I start a thread per object and allocate the needed memory (92 bytes for this structure, but I haven't shown all fields).
However, some objects won't use the internal appContract and appBucket structures but memory for those structures will still be allocated.
Is there a way to avoid this? To designate internal structures as optional or perhaps extract the size of those internal structures and subtract it from the memory allocation?
I could make two separate structures, one per type of object, but I'd prefer not to since I'd have to adjust my code everywhere to work with the two types of threads.
Besides the obvious - using two structs, I see only two other possibilities.
Either use a pointer to a separately allocated appContract, or if some of the data you need is mutually exclusive, use a union.
Consider this implementation of single inheritance that works in C.
Define a base struct that contains all the elements common to both objects. Notice that I've changed the type of the stack member to a pointer because that's going to have to be a separate allocation in this design.
typedef struct ThreadBase{
UInt16 spBase; //we use an empty ascending stack
UInt16 spLimit; //also used for "isPtr"
UInt16 localsBase;
UInt32 *stack;
}ThreadBase;
Then declare another struct that contains the base object as the first member and appends the extra stuff.
typedef struct ThreadExtra{
ThreadBase base;
struct{
UInt32 runInstr;
UInt8* mailbox;
}appBucket;
struct{
UInt32 appId;
UInt32 numInstr;
UInt32 allocMem;
UInt32 eepromStartAddr;
}appContract;
}ThreadExtra;
Now you can define a ThreadBase object for threads that only need the base stuff. And you can define a ThreadExtra object for the threads that need more. But you can cast the ThreadExtra object to ThreadBase because ThreadBase is the first member of ThreadExtra. So in general purpose code that doesn't deal with the ThreadExtra elements you can treat all the Thread objects as if they are ThreadBase objects.
If your optional fields are at the beginning of your struct, you can adjust the address of an allocated object, so the optional fields reside in unallocated memory. Use the offsetof macro to determine where the mandatory data starts:
offsetof(UjThread, spBase) // in bytes
Adjust the allocation size by this amount:
UjThread *newThread;
if (NoOptionalFields())
{
size_t sizeReduce = offsetof(UjThread, spBase);
size_t size = sizeof(UjThread) - sizeReduce;
newThread = (void*)((char*)malloc(size) - sizeReduce);
}
else
{
newThread = malloc(sizeof(UjThread));
}
To free the memory, don't forget to adjust the pointer back:
if (NoOptionalFields())
{
size_t sizeReduce = offsetof(UjThread, spBase);
free((char*)newThread + sizeReduce);
}
else
{
free(newThread);
}
BTW since you have a "flexible array member" in your struct, the actual size calculation is more complicated than in my example. But you get the idea - just subtract the size of the optional fields from both the allocation size and the resulting pointer.
If the stack had a fixed size, you could use the idiomatic C-style single inheritance:
typedef struct {
int a;
} Base;
typedef struct {
Base base;
int b;
} Derived;
void useBase(Base *);
void test(void) {
Base b;
Derived d;
useBase(&b);
useBase(&d.base); // variant 1
useBase((Base*)&d); // variant 2
}
Alas, the stack doesn't have a fixed size, so the somewhat idiomatic if unnecessarily shaky variant 2 won't work, but variant 1 will:
typedef struct {
int a[];
} Small;
typedef struct {
int b;
Small small;
} Large;
void useBase(Base *);
void test(void) {
Small s;
Large l;
useBase(&s);
useBase(&l.small);
}
I have the following code:
typedef struct
{
int name;
int info[1];
} Data;
then I have five variables:
int a, b, c, d, e;
how can I use this as a flexible array to keep all the values of the five variables?
To do this properly, you should declare the flexible array member as an incomplete type:
typedef struct
{
int name;
int info[];
} Data;
Then allocate memory for it dynamically with
Data* data = malloc(sizeof(Data) + sizeof(int[N]));
for(int i=0; i<N; i++)
{
data->info[i] = something; // now use it just as any other array
}
EDIT
Ensure that you are using a C99 compiler for this to work, otherwise you will encounter various problems:
If you allocate an array of length 1, then you will malloc 1 item for the first element of the array together with the struct, and then append N bytes after that. Meaning you are actually allocating N+1 bytes. This is perhaps not what one intended to do, and it makes things needlessly complicated.
(To solve the above problem, GCC had a pre-C99 extension that allowed zero-length arrays, which isn't allowed in standard C.)
Pre-C99, or in any other context than as a flexible array member, C doesn't allow incomplete array types as the one shown in my code.
C99 guarantees that your program is well-defined when using a flexible array member. If you don't use C99, then the compiler might append "struct padding" bytes between the other struct members and the array at the end. Meaning that data->info[0] could point at a struct padding byte and not at the first item in your allocated array. This can cause all kinds of weird, unexpected behavior.
This is why flexible array members were called "struct hack" before C99. They weren't reliable, just a dirty hack which may or may not work.
That kind of structure is a somewhat common idiom in C; the idea is that you allocate extra space at the end of the struct, where the elements of info after the first are actually stored. The size-1 array member at the end of the struct then allows you to use array syntax to access this data.
If you want to store 5 elements you'll have to do:
Data * data=malloc(sizeof(Data)+sizeof(int)*4); /* 4 because the first element is
already included in the size of
the struct */
/* error checking omitted ... */
data->info[0]=a;
data->info[1]=b;
data->info[2]=c;
data->info[3]=d;
data->info[4]=e;
/* ... */
/* when you don't need d anymore remember to deallocate */
free(data);
You may also write a helper function to ease the allocation:
Data * AllocateData(size_t elements)
{
if(elements==0)
return NULL;
return malloc(sizeof(Data)+sizeof(int)*(elements-1));
}
and the example above would be
Data * data=AllocateData(5);
/* then as above */
This is called flexible arrays and was introduced in C99. Often called a struct hack too.
In C99, the flexible array member should be declared without a size.
You need to dynamically allocate memory that can hold more memory than the size of the struct.
As the array is the last member in the struct, you can index it past its size, provided you allocated enough memory for it.
typedef struct
{
int name;
int info[1];
} Data;
Data *d = malloc(sizeof(*d) + (5 * sizeof(int)); //enough for the struct and 5 more ints.
//we have enough room for 6 elements in the info array now
//since the struct has room for 1 element, and we allocated room for another 5 ints
d->info[0] = 1;
d->info[1] = 2;
d->info[2] = 3;
d->info[3] = 4;
d->info[4] = 5;
d->info[5] = 6;
Using an array member with 1 size int info[1]; in this manner is technically undefined behavior - but will work fine on many popular compilers. With a C99 compiler this is supported by a flexible array member declared as int info[];. Read more here
If I create a struct in one class as so
typedef struct
{
int numberOfTiles;
// an array of ints here
int *tileArray;
} CollisionLayer;
is it possible to create an array of ints with an empty [] and set the size on creation? Or how would this array be created? dynamically with a pointer? I will know the size of the array when creating one of these struct "objects", if it is possible to fill in the size of the array on creation, how is the array declared in the struct above?
You will need to initialize the array yourself:
CollisionLayer layer;
layer.numberOfTiles = numberOfTiles;
layer.tileArray = (int*)malloc(sizeof(int) * numberOfTiles);
Or, if you want to create the struct on the heap:
CollisionLayer* pl = (CollisionLayer*)malloc(sizeof(CollisionLayer));
pl->numberOfTiles = numberOfTiles;
pl->tileArray = (int*)malloc(sizeof(int) * numberOfTiles);
// When you are done:
free(pl->tileArray);
free(pl);
The other option would be to hardcode a fixed size limit into CollisionLayer, e.g.:
typedef struct
{
int numberOfTiles;
// an array of ints here
int tileArray[100];
} CollisionLayer;
Of course this will be less desirable in all respects, but it's your only option if you don't want to manage memory manually.
If you don't know the size at compile time, then you must allocate the memory using malloc() at runtime. To use an actual array in C, you must know the size when the code is compiled.
tileArray is a pointer to int. malloc/calloc should be used to create the object to which it will point to. This should happen when creating an object of CollisionLayer.
Defining a struct in which the array [] is empty is not a good idea, refer this. It speaks of C++, bit it should apply for C as well.
VLAs cannot be members of structs so you will need to allocate the memory with malloc when you create the struct object.