I have the following code parts:
typedef struct Board* BoardP;
typedef struct Board {
int _rows;
int _cols;
char *_board;
} Board;
char* static allocateBoard(BoardP boardP, int row, int col) {
boardP->_rows = row;
boardP->_cols = col;
boardP->_board = malloc(row * col * sizeof(char));
return boardP->_board;
}
i can't seem to figure out why it gives the error
expected identifier or ‘(’ before ‘static’
it gives the error after i changed return type to be char*. when it was void no error was given.
and one more question: i was taught that cast is needed when using malloc, however, this seems to be working ok without a cast. is it needed in this case?
thanks
Change your function to
static char* allocateBoard(BoardP boardP, int row, int col):
The return value of malloc is a void*, and in C (unlike C++), a void* is implicittly convertible to any
other pointer type - except function pointers. so you don't need a cast.
Your function prototype needs to be:
static char* allocateBoard(BoardP boardP, int row, int col)
No cast is needed on malloc() in C; however, it is in C++.
In C, Casting for malloc is needed before ANSI C, as there was no void* type (perhaps as extension on some C compilers), but after ANSI C there is no need for casting at all, if you do that then you are suppressing some useful diagnostics by the compiler which is more harmful to your program. Never do casting on malloc() in C.
Although the casting here in this case works for you. It is suggested that you make it a habit to cast things, before you try to assign them to a different type. It saves a lot of pain later. Also when incorporating this code into C++ it saves a lot of time.
Related
I compile some code with visual studio 9.0 (2008).
The behave as expected, but when I allocate some 2D array with some hand made
functions, Visual-Studio generates some C4133 warning:
void ** alloc_2d(int w, int h, size_t type_size);
void free_d2(void ** mem);
int main (void)
{
float ** data;
/* Here is generated a C4133 warning:
"incompatible type from void ** to float **" */
data = alloc_2d(100, 100, sizeof **data);
/* do things with data */
/* free data */
free_2d(data);
return 0;
}
I understand why this warning is generated, but I wonder what I should do to make it quiet.
What should I do?
Live with the warning?
Disable the warning (dangerous I think)?
Disable the warning around the alloc_2d calls (with some macros specific to
visual studio)?
cast the function return (But [Do I cast the result of malloc?)
Second question:
Are newer/other compilers aware of this kind of cast?
Behind the void** are hidden two arrays: one big to store all data I need to be contiguous, and one other to browse through differents lines.
The implementation looks like (I removed the error checking)
void **alloc_2D_array(int w, int h, size_t size)
{
void ** mem = malloc(w * sizeof *mem);
*mem = malloc(w*h*size);
for (i = 1; i < w; ++i)
{
mem[i] = (void*)((char*)mem[0] + i*w*size);
}
return mem;
}
From the signature, I assume your function is implemented roughly like this (plus error checking I'm leaving out here for brevity):
void **alloc_2d(int w, int h, size_t type_size)
{
void **pointers = malloc(h * sizeof *pointers);
for (size_t i = 0; i < h; ++i)
{
pointers[i] = malloc(w * type_size);
}
return pointers;
}
Some remarks on this:
The result of this function is not a 2d array, but an array of pointers to arrays. It can be used somewhat similar to a real 2d array, but comes with some overhead. A real 2d array would be one contiguous block of size w * h * type_size.
This code is in fact unsafe and could invoke undefined behavior when you cast the void ** returned from it to float **. This is because there's no guarantee that pointers to different types have the same representation -- they could even have different sizes. See also Are there any platforms where pointers to different types have different sizes?. By casting void ** to float **, you're treating an array of void * as if it was and array of float *. Although probably fine on your typical modern PC platform, this can go completely wrong.
That said, you could avoid the cast by simply having your function return void * instead of void **, but this would only hide the problem: void * is the generic pointer type and the compiler will allow implicit conversion to any other pointer type, but you'd still access your void * array using the wrong pointer type that way.
I suggest allocating a flat array instead and calculate the offsets manually, like this:
size_t rows = 100;
size_t cols = 100;
float *data = malloc(cols * rows * sizeof *data);
data[cols*5 + 3] = 1.41;
// ...
free(data);
As an alternative, you can use variable-length arrays (obligatory in C99, optional but almost always supported in C11 -- maybe not supported by Microsoft ....) to dynamically allocate a real 2d array:
size_t rows = 100;
size_t cols = 100;
float (*data)[cols] = malloc(rows * sizeof *data);
data[5][3] = 1.41;
// ...
free(data);
The generic pointer type in C is void*. That does not mean that void** is also a generic pointer type, the rule does not apply recursively.
Rather, a conversion from void** to float** or the other way around is an invalid pointer conversion. They are not compatible types - the compiler must issue a diagnostic message. Ignoring the warning might result in misaligned data or strict aliasing issues - in either case bugs.
What should I do?
Fix the code so that it doesn't contain forbidden pointer conversions.
Are newer/other compilers aware of this kind of cast?
This particular rule has not changed since the first standardization of C.
As for how you should fix your code... you shouldn't. You should rewrite it from scratch so that it allocates arrays and not "pointer-based look-up tables". There is no obvious reason why you would benefit from such a look-up-table here, but many reasons why you should avoid it.
In addition, your code would be much more readable if you use pointers to VLA.
See Correctly allocating multi-dimensional arrays for examples of how to do this proper (code example at the very bottom of the answer).
I observed that in line int *x = malloc(sizeof(int)); this code is trying to convert a void* into a int* without using proper typecasting. So according to me answer should be option A. But in official GATE-2017 exam answer key, answer is given D. So am i wrong ? how ?
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int *assignval(int *x, int val){
*x = val;
return x;
}
void main(){
clrscr();
int *x = malloc(sizeof(int));
if(NULL==x) return;
x = assignval(x,0);
if(x){
x = (int *)malloc(sizeof(int));
if(NULL==x) return;
x = assignval(x,10);
}
printf("%d\n",*x);
free(x);
getch();
}
(A) compiler error as the return of malloc is not typecast
appropriately.
(B) compiler error because the comparison should be made as x==NULL
and not as shown.
(C) compiles successfully but execution may result in dangling
pointer.
(D) compiles successfully but execution may result in memory leak.
In my opinion option D is only correct when int *x = (int *)malloc(sizeof(int)); is used.
There's no right answer among the choices offered.
The immediately obvious problems with the code, under assumption that the code is supposed to be written in standard C:
Standard library does not have <conio.h> header or <iostream.h> header.
void main() is illegal. Should be int main(). Even better int main(void)
clrscr(), getch() - standard library knows no such functions.
The second malloc leaks memory allocated by the first one (assuming the first one succeeds).
Result of second malloc is explicitly cast - bad and unnecessary practice.
The statement :
int *x = malloc(sizeof(int));
will not lead to compile error, as it declares x as a pointer to int and initializes it right afterwards. It did not have type void beforehand.
The statement :
x = (int *)malloc(sizeof(int));
causes a possible memory leak, as it reallocates the memory which is already allocated for x.
NOTE : However none of this answers is completely correct. This code will not compile for various reasons.
If this is your code, change :
void main()
to :
int main(void)
and also see why you should not cast the result of malloc.
Apart from that, clrscr(), getch(), <conio.h> and <iostream.h> are not recognized by standard library.
I observed that in line int *x = malloc(sizeof(int)); this code is trying to convert a void* into a int* without using proper typecasting.
There's more than a little debate about whether or not to cast malloc, but it's a stylistic thing. void * is safely promoted to any other pointer.
ISO C 6.3.2.3 says...
A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
Whatever you choose, pick one and stick with it.
The memory leak is here:
int *x = malloc(sizeof(int));
if(NULL==x) return;
x = assignval(x,0);
if(x){
// Memory leak
x = (int *)malloc(sizeof(int));
The first malloc points x at allocated memory. The second malloc can only happen if the first succeeded (if x is true). The pointer to the memory allocated by the first malloc is lost.
Using a new variable would fix the leak, keeping in mind that the code is nonsense.
int *x = malloc(sizeof(int));
if(NULL==x) return;
x = assignval(x,0);
if(x){
int *y = malloc(sizeof(int));
if(NULL==y) return;
y = assignval(y,10);
free(y);
}
As a side note, void main() is technically not a violation of the ISO C standard, it is "some other implementation-defined manner".
5.1.2.2.1 says:
The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):
int main(int argc, char argv[]) { / ... */ }
or equivalent;) or in some other implementation-defined manner.
I'm guessing you're using a Windows compiler, that would be the "some other implementation". clang considers it an error.
test.c:8:1: error: 'main' must return 'int'
void main(){
^~~~
int
1 error generated.
you should never forget that a void * pointer can be assigned to all type of pointers. in IDEs like visual studio, you get a compile error if you do not perform casting while assigning a void * to <>. for example:
float *ptr = malloc(sizeof(float));//compile error in visual studio.
but if you compile it with GCC without typecasting, you won't get a compile error.
I have two structures:
typedef struct abc {
unsigned int pref;
unsigned int port;
char *aRecordIp;
int index;
int count;
}abc_t;
typedef struct xyz {
abc_t *ab;
int index;
int count;
}xyz_t;
and I would like to achieve the following
int Lookup (char *lookup,void *handle) {
*handle = (xyz_t *)malloc(sizeof(xyz_t *));
handle->ab = (abc_t *) malloc(sizeof(abc_t *));
//
}
I am trying to typecast void pointer to xyz_t basically.
Is this correct?
You are doing it wrong on multiple counts:
You're trying to set a variable handle->ab, but handle is a void *, not a structure type pointer.
You need to show your call, but there's likely to be problems — why do you think a void * argument is a good idea?
You want to allocate structures, so the sizeof() operands should be xyz_t and not xyz_t *; repeat for abc_t.
You should probably use:
int Lookup(const char *lookup, xyz_t **handle)
{
...
*handle = (xyz_t *)malloc(sizeof(xyz_t));
(*handle)->ab = (abc_t *)malloc(sizeof(abc_t));
...
}
Don't forget to check the result of malloc().
There are those who will castigate you for using casts on malloc(). I won't. When I learned C (a long time ago, years before there was a C standard), on a machine where the int * value for an address was not the same bit pattern as the char * address for the same memory location, where malloc() had to be declared char *malloc() or all hell broke loose, the casts were necessary. But — and this is the major issue that people are concerned about — it is crucial that you compile with compiler options such that if you invoke a function without a prototype in scope, you will get a compilation error, or a warning that you will pay attention to. The concern is that if you do not have a declaration for malloc() in scope, you will get incorrect results from using the cast which the compiler would diagnose if you don't.
On the whole, though, I think you should separate your lookup code from your 'create xyz_t' code — your function is doing two jobs and it complicates the interface to your function.
xyz_t *Create_xyz(void);
int Lookup(const char *lookup, const xyz_t *handle);
While casting of a void* to any pointer type is correct, it is not necessary in C, and it is not recommended for malloc (e.g. see Do I cast the result of malloc? ).
Also, you should specify sizeof(xyz_t), not sieof(xyz_t*), otherwise you allocate memory enough only for pointer, not for the whole structure.
And of course you should assign a pointer to handle, not to *handle. And handle should be of proper pointer type (xyz_t*).
Oh, and if the question is about casting handle to xyz_t*, then you can do it like ((xyz_t*)handle)->ab.
I'd recommend reading a book before playing with pointers like that.
I believe you want handle to hold a valid address of a xyz_t struct after the function call. Then you need to change the function signature and contents like so:
int Lookup (char *lookup, xyz_t **handle) { // double indirection here
*handle = (xyz_t *)malloc(sizeof(xyz_t));
(*handle)->ab = (abc_t *) malloc(sizeof(abc_t));
}
And call it like this:
xyz_t *myhandle;
char lookup;
Lookup(&lookup, &mynandle);
// now you can use it
myhandle->index ...
You will need to free the memory as well...
free(myhandle->ab);
free(myhandle);
If you want to pass void *, here is the solution
int Lookup (char *lookup, void *handle) {
handle = malloc(sizeof(xyz_t));
((xyz_t *)handle)->ab = (abc_t *) malloc(sizeof(abc_t));
//
}
Even though it is possible to write generic code in C using void pointer(generic pointer), I find that it is quite difficult to debug the code since void pointer can take any pointer type without warning from compiler.
(e.g function foo() take void pointer which is supposed to be pointer to struct, but compiler won't complain if char array is passed.)
What kind of approach/strategy do you all use when using void pointer in C?
The solution is not to use void* unless you really, really have to. The places where a void pointer is actually required are very small: parameters to thread functions, and a handful of others places where you need to pass implementation-specific data through a generic function. In every case, the code that accepts the void* parameter should only accept one data type passed via the void pointer, and the type should be documented in comments and slavishly obeyed by all callers.
This might help:
comp.lang.c FAQ list · Question 4.9
Q: Suppose I want to write a function that takes a generic pointer as an argument and I want to simulate passing it by reference. Can I give the formal parameter type void **, and do something like this?
void f(void **);
double *dp;
f((void **)&dp);
A: Not portably. Code like this may work and is sometimes recommended, but it relies on all pointer types having the same internal representation (which is common, but not universal; see question 5.17).
There is no generic pointer-to-pointer type in C. void * acts as a generic pointer only because conversions (if necessary) are applied automatically when other pointer types are assigned to and from void * 's; these conversions cannot be performed if an attempt is made to indirect upon a void ** value which points at a pointer type other than void *. When you make use of a void ** pointer value (for instance, when you use the * operator to access the void * value to which the void ** points), the compiler has no way of knowing whether that void * value was once converted from some other pointer type. It must assume that it is nothing more than a void *; it cannot perform any implicit conversions.
In other words, any void ** value you play with must be the address of an actual void * value somewhere; casts like (void **)&dp, though they may shut the compiler up, are nonportable (and may not even do what you want; see also question 13.9). If the pointer that the void ** points to is not a void *, and if it has a different size or representation than a void *, then the compiler isn't going to be able to access it correctly.
To make the code fragment above work, you'd have to use an intermediate void * variable:
double *dp;
void *vp = dp;
f(&vp);
dp = vp;
The assignments to and from vp give the compiler the opportunity to perform any conversions, if necessary.
Again, the discussion so far assumes that different pointer types might have different sizes or representations, which is rare today, but not unheard of. To appreciate the problem with void ** more clearly, compare the situation to an analogous one involving, say, types int and double, which probably have different sizes and certainly have different representations. If we have a function
void incme(double *p)
{
*p += 1;
}
then we can do something like
int i = 1;
double d = i;
incme(&d);
i = d;
and i will be incremented by 1. (This is analogous to the correct void ** code involving the auxiliary vp.) If, on the other hand, we were to attempt something like
int i = 1;
incme((double *)&i); /* WRONG */
(this code is analogous to the fragment in the question), it would be highly unlikely to work.
Arya's solution can be changed a little to support a variable size:
#include <stdio.h>
#include <string.h>
void swap(void *vp1,void *vp2,int size)
{
char buf[size];
memcpy(buf,vp1,size);
memcpy(vp1,vp2,size);
memcpy(vp2,buf,size); //memcpy ->inbuilt function in std-c
}
int main()
{
int array1[] = {1, 2, 3};
int array2[] = {10, 20, 30};
swap(array1, array2, 3 * sizeof(int));
int i;
printf("array1: ");
for (i = 0; i < 3; i++)
printf(" %d", array1[i]);
printf("\n");
printf("array2: ");
for (i = 0; i < 3; i++)
printf(" %d", array2[i]);
printf("\n");
return 0;
}
The approach/strategy is to minimize use of void* pointers. They are needed in specific cases. If you really need to pass void* you should pass size of pointer's target also.
This generic swap function will help you a lot in understanding generic void *
#include<stdio.h>
void swap(void *vp1,void *vp2,int size)
{
char buf[100];
memcpy(buf,vp1,size);
memcpy(vp1,vp2,size);
memcpy(vp2,buf,size); //memcpy ->inbuilt function in std-c
}
int main()
{
int a=2,b=3;
float d=5,e=7;
swap(&a,&b,sizeof(int));
swap(&d,&e,sizeof(float));
printf("%d %d %.0f %.0f\n",a,b,d,e);
return 0;
}
We all know that the C typesystem is basically crap, but try to not do that... You still have some options to deal with generic types: unions and opaque pointers.
Anyway, if a generic function is taking a void pointer as a parameter, it shouldn't try to dereference it!.
I was trying to create a pseudo super struct to print array of structs. My basic
structures are as follows.
/* Type 10 Count */
typedef struct _T10CNT
{
int _cnt[20];
} T10CNT;
...
/* Type 20 Count */
typedef struct _T20CNT
{
long _cnt[20];
} T20CNT;
...
I created the below struct to print the array of above mentioned structures. I got dereferencing void pointer error while compiling the below code snippet.
typedef struct _CMNCNT
{
long _cnt[3];
} CMNCNT;
static int printCommonStatistics(void *cmncntin, int cmncnt_nelem, int cmncnt_elmsize)
{
int ii;
for(ii=0; ii<cmncnt_nelem; ii++)
{
CMNCNT *cmncnt = (CMNCNT *)&cmncntin[ii*cmncnt_elmsize];
fprintf(stout,"STATISTICS_INP: %d\n",cmncnt->_cnt[0]);
fprintf(stout,"STATISTICS_OUT: %d\n",cmncnt->_cnt[1]);
fprintf(stout,"STATISTICS_ERR: %d\n",cmncnt->_cnt[2]);
}
return SUCCESS;
}
T10CNT struct_array[10];
...
printCommonStatistics(struct_array, NELEM(struct_array), sizeof(struct_array[0]);
...
My intention is to have a common function to print all the arrays. Please let me know the correct way of using it.
Appreciate the help in advance.
Edit: The parameter name is changed to cmncntin from cmncnt. Sorry it was typo error.
Thanks,
Mathew Liju
I think your design is going to fail, but I am also unconvinced that the other answers I see fully deal with the deeper reasons why.
It appears that you are trying to use C to deal with generic types, something that always gets to be hairy. You can do it, if you are careful, but it isn't easy, and in this case, I doubt if it would be worthwhile.
Deeper Reason: Let's assume we get past the mere syntactic (or barely more than syntactic) issues. Your code shows that T10CNT contains 20 int and T20CNT contains 20 long. On modern 64-bit machines - other than under Win64 - sizeof(long) != sizeof(int). Therefore, the code inside your printing function should be distinguishing between dereferencing int arrays and long arrays. In C++, there's a rule that you should not try to treat arrays polymorphically, and this sort of thing is why. The CMNCNT type contains 3 long values; different from both the T10CNT and T20CNT structures in number, though the base type of the array matches T20CNT.
Style Recommendation: I strongly recommend avoiding leading underscores on names. In general, names beginning with underscore are reserved for the implementation to use, and to use as macros. Macros have no respect for scope; if the implementation defines a macro _cnt it would wreck your code. There are nuances to what names are reserved; I'm not about to go into those nuances. It is much simpler to think 'names starting with underscore are reserved', and it will steer you clear of trouble.
Style Suggestion: Your print function returns success unconditionally. That is not sensible; your function should return nothing, so that the caller does not have to test for success or failure (since it can never fail). A careful coder who observes that the function returns a status will always test the return status, and have error handling code. That code will never be executed, so it is dead, but it is hard for anyone (or the compiler) to determine that.
Surface Fix: Temporarily, we can assume that you can treat int and long as synonyms; but you must get out of the habit of thinking that they are synonyms, though. The void * argument is the correct way to say "this function takes a pointer of indeterminate type". However, inside the function, you need to convert from a void * to a specific type before you do indexing.
typedef struct _CMNCNT
{
long count[3];
} CMNCNT;
static void printCommonStatistics(const void *data, size_t nelem, size_t elemsize)
{
int i;
for (i = 0; i < nelem; i++)
{
const CMNCNT *cmncnt = (const CMNCNT *)((const char *)data + (i * elemsize));
fprintf(stdout,"STATISTICS_INP: %ld\n", cmncnt->count[0]);
fprintf(stdout,"STATISTICS_OUT: %ld\n", cmncnt->count[1]);
fprintf(stdout,"STATISTICS_ERR: %ld\n", cmncnt->count[2]);
}
}
(I like the idea of a file stream called stout too. Suggestion: use cut'n'paste on real source code--it is safer! I'm generally use "sed 's/^/ /' file.c" to prepare code for cut'n'paste into an SO answer.)
What does that cast line do? I'm glad you asked...
The first operation is to convert the const void * into a const char *; this allows you to do byte-size operations on the address. In the days before Standard C, char * was used in place of void * as the universal addressing mechanism.
The next operation adds the correct number of bytes to get to the start of the ith element of the array of objects of size elemsize.
The second cast then tells the compiler "trust me - I know what I'm doing" and "treat this address as the address of a CMNCNT structure".
From there, the code is easy enough. Note that since the CMNCNT structure contains long value, I used %ld to tell the truth to fprintf().
Since you aren't about to modify the data in this function, it is not a bad idea to use the const qualifier as I did.
Note that if you are going to be faithful to sizeof(long) != sizeof(int), then you need two separate blocks of code (I'd suggest separate functions) to deal with the 'array of int' and 'array of long' structure types.
The type of void is deliberately left incomplete. From this, it follows you cannot dereference void pointers, and neither you can take the sizeof of it. This means you cannot use the subscript operator using it like an array.
The moment you assign something to a void pointer, any type information of the original pointed to type is lost, so you can only dereference if you first cast it back to the original pointer type.
First and the most important, you pass T10CNT* to the function, but you try to typecast (and dereference) that to CMNCNT* in your function. This is not valid and undefined behavior.
You need a function printCommonStatistics for each type of array elements. So, have a
printCommonStatisticsInt, printCommonStatisticsLong, printCommonStatisticsChar which all differ by their first argument (one taking int*, the other taking long*, and so on). You might create them using macros, to avoid redundant code.
Passing the struct itself is not a good idea, since then you have to define a new function for each different size of the contained array within the struct (since they are all different types). So better pass the contained array directly (struct_array[0]._cnt, call the function for each index)
Change the function declaration to char * like so:
static int printCommonStatistics(char *cmncnt, int cmncnt_nelem, int cmncnt_elmsize)
the void type does not assume any particular size whereas a char will assume a byte size.
You can't do this:
cmncnt->_cnt[0]
if cmnct is a void pointer.
You have to specify the type. You may need to re-think your implementation.
The function
static int printCommonStatistics(void *cmncntin, int cmncnt_nelem, int cmncnt_elmsize)
{
char *cmncntinBytes;
int ii;
cmncntinBytes = (char *) cmncntin;
for(ii=0; ii<cmncnt_nelem; ii++)
{
CMNCNT *cmncnt = (CMNCNT *)(cmncntinBytes + ii*cmncnt_elmsize); /* Ptr Line */
fprintf(stdout,"STATISTICS_INP: %d\n",cmncnt->_cnt[0]);
fprintf(stdout,"STATISTICS_OUT: %d\n",cmncnt->_cnt[1]);
fprintf(stdout,"STATISTICS_ERR: %d\n",cmncnt->_cnt[2]);
}
return SUCCESS;
}
Works for me.
The issue is that on the line commented "Ptr Line" the code adds a pointer to an integer. Since our pointer is a char * we move forward in memory sizeof(char) * ii * cmncnt_elemsize, which is what we want since a char is one byte. Your code tried to do an equivalent thing moving forward sizeof(void) * ii * cmncnt_elemsize, but void doesn't have a size, so the compiler gave you the error.
I'd change T10CNT and T20CNT to both use int or long instead of one with each. You're depending on sizeof(int) == sizeof(long)
On this line:
CMNCNT *cmncnt = (CMNCNT *)&cmncnt[ii*cmncnt_elmsize];
You are trying to declare a new variable called cmncnt, but a variable with this name already exists as a parameter to the function. You might want to use a different variable name to solve this.
Also you may want to pass a pointer to a CMNCNT to the function instead of a void pointer, because then the compiler will do the pointer arithmetic for you and you don't have to cast it. I don't see the point of passing a void pointer when all you do with it is cast it to a CMNCNT. (Which is not a very descriptive name for a data type, by the way.)
Your expression
(CMNCNT *)&cmncntin[ii*cmncnt_elmsize]
tries to take the address of cmncntin[ii*cmncnt_elmsize] and then cast that pointer to type (CMNCNT *). It can't get the address of cmncntin[ii*cmncnt_elmsize] because cmncntin has type void*.
Study C's operator precedences and insert parentheses where necessary.
Point of Information: Internal Padding can really screw this up.
Consider struct { char c[6]; }; -- It has sizeof()=6. But if you had an array of these, each element might be padded out to an 8 byte alignment!
Certain assembly operations don't handle mis-aligned data gracefully. (For example, if an int spans two memory words.) (YES, I have been bitten by this before.)
.
Second: In the past, I've used variably sized arrays. (I was dumb back then...) It works if you are not changing type. (Or if you have a union of the types.)
E.g.:
struct T { int sizeOfArray; int data[1]; };
Allocated as
T * t = (T *) malloc( sizeof(T) + sizeof(int)*(NUMBER-1) );
t->sizeOfArray = NUMBER;
(Though padding/alignment can still screw you up.)
.
Third: Consider:
struct T {
int sizeOfArray;
enum FOO arrayType;
union U { short s; int i; long l; float f; double d; } data [1];
};
It solves problems with knowing how to print out the data.
.
Fourth: You could just pass in the int/long array to your function rather than the structure. E.g:
void printCommonStatistics( int * data, int count )
{
for( int i=0; i<count; i++ )
cout << "FOO: " << data[i] << endl;
}
Invoked via:
_T10CNT foo;
printCommonStatistics( foo._cnt, 20 );
Or:
int a[10], b[20], c[30];
printCommonStatistics( a, 10 );
printCommonStatistics( b, 20 );
printCommonStatistics( c, 30 );
This works much better than hiding data in structs. As you add members to one of your struct's, the layout may change between your struct's and no longer be consistent. (Meaning the address of _cnt relative to the start of the struct may change for _T10CNT and not for _T20CNT. Fun debugging times there. A single struct with a union'ed _cnt payload would avoid this.)
E.g.:
struct FOO {
union {
int bar [10];
long biff [20];
} u;
}
.
Fifth:
If you must use structs... C++, iostreams, and templating would be a lot cleaner to implement.
E.g.:
template<class TYPE> void printCommonStatistics( TYPE & mystruct, int count )
{
for( int i=0; i<count; i++ )
cout << "FOO: " << mystruct._cnt[i] << endl;
} /* Assumes all mystruct's have a "_cnt" member. */
But that's probably not what you are looking for...
C isn't my cup o'java, but I think your problem is that "void *cmncnt" should be CMNCNT *cmncnt.
Feel free to correct me now, C programmers, and tell me this is why java programmers can't have nice things.
This line is kind of tortured, don'tcha think?
CMNCNT *cmncnt = (CMNCNT *)&cmncntin[ii*cmncnt_elmsize];
How about something more like
CMNCNT *cmncnt = ((CMNCNT *)(cmncntin + (ii * cmncnt_elmsize));
Or better yet, if cmncnt_elmsize = sizeof(CMNCNT)
CMNCNT *cmncnt = ((CMNCNT *)cmncntin) + ii;
That should also get rid of the warning, since you are no longer dereferencing a void *.
BTW: I'm not real sure why you are doing it this way, but if cmncnt_elmsize is sometimes not sizeof(CMNCNT), and can in fact vary from call to call, I'd suggest rethinking this design. I suppose there could be a good reason for it, but it looks really shaky to me. I can almost guarantee there is a better way to design things.