Re: Casting a generic or void pointer to point to a struct...
- From: Flash Gordon <spam@xxxxxxxxxxxxxxxxxx>
- Date: 2 Aug 2006 02:00:42 +0200
MQ wrote:
MQ wrote:redefined.horizons@xxxxxxxxx wrote:First, I would thank all of those that took the time to answer mystruct new_data_type * ptr = calloc(number_of_elements,
question about creating an array based on a numeric value stored in a
variable.
I realize after reading the responses and doing some more research,
that what I really need is known in C as a "dynamic array". Basically,
you surpass the array notation and use pointers with memory obtained
with malloc() or calloc(). I think this will do just what I needed.
That has brought up another question though. I'm not sure what syntax I
would use to cast a gneeric or void pointer to a struct that I have
defined. For example, if I have defined the "new_data_type" struct
previously in the source code file, would the following code be valid?
/* Create a generic pointer to the first element in the block of
memory obtained with the calloc() function. */
void generic_pointer = calloc(number_of_elements, size_of_element);
/* If the memory has been sucessfully allocated, cast the generic
pointer to the correct data type. */
if(generic_pointer != NULL)
(struct new_data_type *)generic_pointer
else
/* We've got problems. */
Thanks again for the help everyone.
Scott Huey
size_of_element);
if(ptr == NULL)
{
/*error */
}
else
{
/*do something */
}
correction: size_of_element should be replaced by sizeof(struct
new_data_type)
In all probability neither is optimal. Firstly, the OP did not say that it needed clearing to all bits 0 (remember that floating point 0 and null pointers might not be all bits 0) so why pay the cost of zeroing the memory? Secondly, there are better ways to use sizeof.
If you really do want calloc:
T *ptr = calloc(number_of_elements, sizeof *ptr);
Then you only have to specify the type in one place, so maintenance is easier.
Or, for malloc
T *ptr = malloc(number_of_elements * sizeof *ptr);
Or, if mallocing some time after declaration:
ptr = malloc(number_of_elements * sizeof *ptr);
Although the OP should also look up the references to the struct hack others have posted and, if using a C99 compiler, the C99 sanctioned alternative.
--
Flash Gordon
Still sigless on this computer.
.
- Follow-Ups:
- References:
- Casting a generic or void pointer to point to a struct...
- From: redefined . horizons
- Re: Casting a generic or void pointer to point to a struct...
- From: MQ
- Re: Casting a generic or void pointer to point to a struct...
- From: MQ
- Casting a generic or void pointer to point to a struct...
- Prev by Date: Re: Writing to an existing file.
- Next by Date: Re: Checking return values for errors, a matter of style?
- Previous by thread: Re: Casting a generic or void pointer to point to a struct...
- Next by thread: Re: Casting a generic or void pointer to point to a struct...
- Index(es):
Relevant Pages
|