Re: Pointer to array of structs?
- From: Barry Schwarz <schwarzb@xxxxxxxxx>
- Date: Thu, 09 Feb 2006 22:29:24 -0800
On Wed, 08 Feb 2006 09:34:30 +0100, Paminu <sdef@xxxxxxx> wrote:
Robert Gamble wrote:
Paminu wrote:
Still having a few problems with malloc and pointers.
I have made a struct. Now I would like to make a pointer an array with 4
pointers to this struct.
#include <stdlib.h>
#include <stdio.h>
typedef struct _tnode_t {
void *content;
struct _tnode_t *kids;
} tnode_t;
int main(void)
{
tnode_t *array;
array = malloc(sizeof(tnode_t)*4);
array[3] = NULL;
return 0;
}
As I understand "array" point to the first element of an array consisting
of space for 4 tnode_t structs. But why can't I initialize element at
index 3 to NULL?
tnode_t *array; creates a pointer to a tnode_t structure.
Ok so it will only work if I set array[3] equal to a struct instead of a
pointer to a struct or NULL:
1)
tnode_t tt;
tt.content = "test";
tt.kids = NULL;
tnode_t *array;
array[0] = tt;
tt is a tnode_t. array is a pointer to a tnode_t. array is not
initialized to point anywhere. array[0] would be the first tnode_t it
pointed if it did point anywhere. That is why your program is
syntactically correct. Some compilers warn you if you attempt to use
an uninitialized variable but even without the warning it is still
undefined behavior. If you added a call to malloc before using
array[0], array would then point to one or more structures and the
assignment would be fine.
this seems to work and make sense. But if I make:
Seeming to work is just leading down the path of murphy's law.
2)
int *p;
p = malloc(sizeof(int)*4);
p[0] = NULL;
this only give the warning: "warning: assignment makes integer from pointer
without a cast".
p is a pointer to int. p[0] is the first uninitialized int it points
to. NULL is not a suitable value for int. Hence the warning. Do not
think of it as "only". Your program is doing something much different
than you expect.
In 1) if I did: array[0] = NULL; I would get the error:
"error: incompatible types in assignment".
There is an implementation defined conversion from void* (the type of
NULL) to int. There is no such conversion from int* to struct.
Why the different rules?
Different types.
Remove del for email
.
- Follow-Ups:
- Re: Pointer to array of structs?
- From: Roka100@xxxxxxxxx
- Re: Pointer to array of structs?
- References:
- Pointer to array of structs?
- From: Paminu
- Re: Pointer to array of structs?
- From: Robert Gamble
- Re: Pointer to array of structs?
- From: Paminu
- Pointer to array of structs?
- Prev by Date: Re: pointer concepts
- Next by Date: Re: pointer concepts
- Previous by thread: Re: Pointer to array of structs?
- Next by thread: Re: Pointer to array of structs?
- Index(es):
Relevant Pages
|
Loading