size of each element of a struct array in c - c

First, I have a struct here:
//Space to store the results for analysis map
struct Analysis analysis_space[32];
Each element of analysis_space array is for one file to store the results by some calculations;
So, my question is
If I want to get the size of each one of analysis_space,
It should be sizeof(analysis_space[0]) which returns the size of each element.
And sizeof(analysis_space) returns the whole array size?
Additional question:
Since analysis_space is an array, I suppose to initialize it before I store results into it?
Something like: analysis_space[0] = '\0' ?

... to get the size of each one of analysis_space, It should be sizeof(analysis_space[0]) which returns the size of each element.
sizeof(analysis_space[0]) returns the value of the char size of analysis_space[0]. The type returned is size_t and the matching printf() specifier is "%zu", "%zX" and others. When using the sizeof operator, code needs to use () with types. () are optional with objects.
printf("One element size %zu\n", sizeof analysis_space[0]);
And sizeof(analysis_space) returns the whole array size?
Yes,
printf("Array size %zu\n", sizeof analysis_space);
I suppose to initialize it before I store results into it? Something like: analysis_space[0] = '\0' ?
analysis_space[0] = '\0' is an assignment, not initialization. Further, struct Analysis expects a structure assignment/initialization, not scalar. Initialization is not required before writing
to it. #pm100
struct Analysis {
int a;
double b;
};
// Sample initialization
struct Analysis analysis_space[32] = {
{0, 0.0}, {1, 1.0} , {2, 2.0} }; // remainder zero initialized.
To compute the array element count:
// the type of the quotient is size_t
#define analysis_space_N (sizeof analysis_space / sizeof analysis_space[0])

Related

Is there a way to find array length in a function without passing an argument? [duplicate]

This question already has answers here:
C sizeof a passed array [duplicate]
(7 answers)
Closed 2 years ago.
Is there a way I could get the length of an array inside a function? I need to find the size of an array, however it is defined in the main function and I cannot pass the array size as an argument as I cannot change the main function. So is there any way to find it through the function?
The array's max size is set to be roughly 100, however the actual input will be anywhere between size 1 - 20. So I can't really take the max size approach either.
No, arrays always decay to pointers when passing into functions so you must pass the length in if you want the function to know the size. With some preconditions you have multiple ways to do that without an additional parameter:
Add a null/zero/whatever special parameter at the last, similar to a null-terminated char array. This is only possible if you really know there's a unique value that never appears in the value list to put at the final position. This method is actually very common in Linux system calls, for example the exec family
char *args[] = { "Hello", "C", "Programming", NULL /* ends the array */ };
execv("./hello", args);
Add a length prefix at the beginning
void my_function(int array[])
{
int length = array[0];
int* data = &array[1];
// operate on data[];
}
int my_data[LENGTH + 1] = { LENGTH, /* values */ };
my_function(my_data);
Pascal also uses length-prefixed string, so its string is limited to only 255 characters with a 1-byte length. But this can be fixed by using a bigger length
A variation of this is BSTR in Windows where the pointer points to the actual data instead of start of the struct
typedef struct MY_ARRAY
{
int32_t length;
my_type* data; // array of the desired type
} my_array;
void my_function(my_type array[])
{
int length;
memcpy(&length, (char*)array - sizeof(int32_t), sizeof(int32_t));
// operate on array[];
}
my_type data_list[] = { /* some data */ };
my_array my_data = { LENGTH, data_list };
my_function(my_data.data);
if the function is declared for example like
void f( T a[] );
where T is some type specifier then the function deals with a pointer to the type T. That is the above declaration is equivalent to the following declaration
void f( T *a );
and the both declare the same one function.
So the only way to calculate the number of actual elements in the array pointed to by the pointer is to introduce a sentinel value that will differ from values of actual elements of the array.
For example a character array can have such a sentinel value like '\0' that is when a character array contains a string.
An array of strings can have as a sentinel value either an empty string "" or depending on how it is declared (for example as an array of element type char *) the sentinel value can be NULL.
For integer arrays you have yourself to select an appropriate value as a sentinel value. For example if actual elements are non-negative then the sentinel value can be set to -1.
You could include a for loop with a counter to see how many variables there are before the the next line.
int counter(int array[100]) {
int counter = -1;
for (i = 0; array != '\0'; i++) {
counter = counter + 1;
}
return counter;
}
and then in the main section
int arraysize = counter();

Dynamically expanding array of structs C [duplicate]

This question already has answers here:
Dynamic array in C — Is my understanding of malloc and realloc correct?
(3 answers)
Closed 5 years ago.
So for my school project, a large CSV file will be entered through stdin and we will have to sort it based on column and print it out as a sorted csv file.
The step I am on right now is figuring out how to keep reallocing a struct of arrays so that it will grow if there is not big enough to hold the data coming in from stdin. We don't know the exact amount of rows that will be inputted in the CSV file. Right now we just used a static amount to test and see if the values are assigned to the structs.
I am still a beginner at C so I do not clearly know how I would iterate through a pointer like I would iterate through an array. Since we are using a static amount of structs in the array, we can just iterate using array[i] like in Java but how would you iterate through something like *array?
I do not know where to start for creating this dynamic array. I tried
struct array* testArray = (array*)malloc(sizeof(testArray));
but I have no idea how to iterate through it like I did with the static array by using array[i].
Any help would be greatly appreciated, sorry for the wall of text...
You can navigate through a malloced space the same way as with an array (using indicies), but it seems that your main issue lies in your use of malloc. Malloc's argument is the size in number of bytes that you want to allocate. So if you want to have an array of structs, you would first need to find out how many bytes one struct contains using sizeof(struct array), and then determine how large of an array you want, let's say N. So that line of code should look more like struct array* testArray = malloc(N * sizeof(struct array));. The return value of malloc will be a void pointer containing the memory address of the first byte of allocated space. Upon assigning this value to testArray, it will be type-casted to the assigned variable type (struct array *). Now you can use pointer arithmetic to access a specific index i with *(testArray + i), or simply testArray[i]. If you find that N was not a sufficient size, you can use realloc to increase the array size to 2N, or whatever size deemed necessary.
struct array* testArray = (array*)malloc(sizeof(testArray));
is a little wrong as you only allocate 1 element of testArray.
It is more like:
struct A
{
int a;
int b;
....
};
struct A* arr = malloc( N * sizeof(struct A) );
^^^
N element of struct A
int j;
for (j=0; j<N; ++j) // Iterate it like any other array
{
arr[j].a = 5;
arr[j].b = 42;
....
}
Use realloc when you need the array to grow.
When reading from a file/stdin it could look like (based on comment from David C. Rankin):
int n=0; // Count of the number of structs read from the file
struct A* arr = malloc( N * sizeof(struct A) );
while (read line from file)
{
arr[n].a = val1;
arr[n].b = val2;
++n; // Increment count
if (n == N) // Check if current array is full, i.e. realloc needed
{
// realloc array to 2 * N; N = N * 2
}
}

sizeof of string literal inside a struct - C

I have the following code:
struct stest
{
int x;
unsigned char data[];
} x =
{
1, {"\x10\x20\x30\x00\x10"}
};
int main()
{
printf( "x.data: %d\n", (int)x.data[0] );
return 0;
}
Which works fine. However, I need to use the size of the "data".
If I do:
printf( "sizeof x.data: %d\n", (int)sizeof(x.data) );
I get the error:
invalid application of ‘sizeof’ to incomplete type ‘char[]’
Is there a way to get the size of "data" in this situation, or maybe a suggestion of an alternative method I could use?
The compiler I am using is gcc 4.6.3.
Since x.data is a null terminated char array you could just use strlen function.
printf( "sizeof x.data: %u\n", strlen(x.data)+1 );
This code will not work correctly if the array contains null. In this case you need to store length of the array in separate member of struct.
As others have said, strlen will get you what you want.
The reason you're running into trouble isn't due to the string literal aspect, but rather the lack of a definite size of the array in your struct. It's an incomplete type. The compiler doesn't know how big the array is, and so sizeof can't figure it out.
Specifically, this is a "flexible array member". C99 added these. Structs with array's with an incomplete array as the last element (so it has room to grow).
Sizeof gets the size of the datatype.
Sizeof when applied to arrays, gets the size of the whole array.
Sizeof when applied to structs with a flexible array member, ignores the array.
Sizeof when applied to incomplete types simply fails. It gives up trying to figure out how big the array is.
So long story short, slap a number in your array. (Or pass along that information)
struct
{
int x;
int thesizeofmyarrayisfive = 5;
unsigned char data[5];
}
Add a size field to the structure.
#define DATA ("\x10\x20\x30\x00\x10")
struct stest
{
int x;
size_t size;
unsigned char data[];
} x =
{
1, sizeof DATA, { DATA }
};
There's only two options:
Store a terminating byte. Often people use the null character for this. Of course, you must make sure that the terminating byte is not found in the valid data part of the array.
Add a length member to your struct.

Bug on calling a dynamic array function

I have bug when calling to a function dynamic_arr - somehow I loose all my array and only
the first element being returned.
In my code my main calls a function that dynamically needs to create an array
and after the user will insert the elements of the array all the array needs to be passed to
function funcdosomthing.
But at the moment function funcdosomthing gets only the first element and not all the array.
Just to make clear that everything else works - when I don't use function dynamic_arr and
set the array manualy int a[] = {1, 0, 2}; everything works fine and function funcdosomthing gets all the array with 3 elements.
Here's my code:
int *dynamic_arr(int n)
{
int i, *a;
a = (int*)calloc(n, sizeof(int));
for(i=0;i<n;i++) scanf("%d",a+i);
return a;
}
int mainprograma()
{
int n,*a,i;
scanf("%d",&n);
a=dynamic_arr(n);
funcdosomthing(a, sizeof a / sizeof a[0]);
...
You are trying to calculate the size of an array from a pointer to a dynamic array.
sizeof a / sizeof a[0]
In C you simply cannot find out the length of an array if you only have a pointer to the array. The code you are using is appropriate if you have an array, but you don't have an array, you have a pointer.
So, if you had declared a like this
int a[3];
or this
int a[] = {0, 1, 2};
then a would be an array rather than a pointer and the sizeof code above would be applicable.
Fortunately you know how big the dynamic array is because you just created it. It has n elements. So you must write your call to funcdosomthing like this:
funcdosomthing(a, n);
Why do you try to find the size when you already know the size?!
You should use n instead of calculating the size like sizeof a / sizeof a[0]. And more over, sizeof(a) will give your expected result iff a is an array. In this case, it is a pointer-to-memory-which-can-store-n-integers.

Result of 'sizeof' on array of structs in C?

In C, I have an array of structs defined like:
struct D
{
char *a;
char *b;
char *c;
};
static struct D a[] = {
{
"1a",
"1b",
"1c"
},
{
"2a",
"2b",
"2c"
}
};
I would like to determine the number of elements in the array, but sizeof(a) returns an incorrect result: 48, not 2. Am I doing something wrong, or is sizeof simply unreliable here? If it matters I'm compiling with GCC 4.4.
sizeof gives you the size in bytes, not the number of elements. As Alok says, to get the number of elements, divide the size in bytes of the array by the size in bytes of one element. The correct C idiom is:
sizeof a / sizeof a[0]
sizeof a / sizeof a[0];
This is a compile-time constant, so you can use it to, for example, create another array:
#define N sizeof a / sizeof a[0]
int n_a[N];
sizeof returns the size in memory of the passed element. By dividing the size of an array by a single element size, you get the elements count.
Note that the element size may include some padding bytes as well. For this reason, a padded struct (e.g. when a char member is followed by a pointer) will have a sizeof value greater than it members size sum.
On the other hand, don't let it bother you when counting elements in an array: sizeof(a) / sizeof(a[0]) will still work as smooth as expected.
ssize_t portfoySayisi = sizeof(*portfoyler);
THIS ONE WORKS

Resources