View previous topic :: View next topic |
Author |
Message |
derverstand Guru


Joined: 15 Dec 2005 Posts: 511 Location: /dev/null
|
Posted: Wed Aug 09, 2006 11:29 am Post subject: C: typedef struct ?? |
|
|
Hi,
I want to setup a simple linked list in C. So I have to do something like this:
Code: |
struct s_entry{
int value;
struct s_entry *next;
};
typedef struct entry t_entry;
... // Some Code
t_entry entry;
... // Allocation etc
|
And now the big ?
Why can't I access a value like this?
It only works with
Whats the difference exaclty? And is it possible to write the "->" expression with "." ?
Best regards. |
|
Back to top |
|
 |
tboloo Guru


Joined: 20 Jan 2006 Posts: 403 Location: Grodzisq, Poland
|
Posted: Wed Aug 09, 2006 11:50 am Post subject: |
|
|
Hi.
Looks like you've made some mistakes - maybe you dynamically allocated memory for your struct ?If so, you'll need to dereference pointer in order to use . instead of ->, like
Code: | *(entry.value) = 1; |
Anyway this code below works fine
Code: |
#include <stdio.h>
struct s_entry{
int value;
struct s_entry* next;
};
typedef struct s_entry t_entry;
int main()
{
t_entry entry;
entry.value = 1;
entry.next = NULL;
printf(" %d, %p", entry.value, entry.next );
printf("\n");
return 0;
}
|
_________________ The clock is ticking, brothers and sisters, counting down to Armageddon. |
|
Back to top |
|
 |
Archangel1 Veteran


Joined: 21 Apr 2004 Posts: 1212 Location: Work
|
Posted: Wed Aug 09, 2006 10:47 pm Post subject: Re: C: typedef struct ?? |
|
|
derverstand wrote: | Whats the difference exaclty? And is it possible to write the "->" expression with "." ? |
Basically -> is for a pointer, . is when the variable actually is a struct. So:
Code: |
t_entry spam;
t_entry* eggs = malloc(sizeof(t_entry));
spam.value = 5;
eggs->value = 5;
|
_________________ What are you, stupid? |
|
Back to top |
|
 |
Voltago Advocate


Joined: 02 Sep 2003 Posts: 2593 Location: userland
|
Posted: Wed Aug 09, 2006 10:54 pm Post subject: |
|
|
You can even do this:
Code: | typedef struct s_entry t_entry;
struct s_entry{
int value;
t_entry* next;
}; |
|
|
Back to top |
|
 |
voytas Apprentice


Joined: 31 Mar 2004 Posts: 203 Location: Poland, Lodz
|
Posted: Thu Aug 10, 2006 9:00 am Post subject: |
|
|
if A is a pointer to a struct these are equivalents: Code: | (*A).val = 10;
A->val = 10; |
_________________ LAPTOP: ThinkPad T530 |
|
Back to top |
|
 |
tboloo Guru


Joined: 20 Jan 2006 Posts: 403 Location: Grodzisq, Poland
|
Posted: Thu Aug 17, 2006 10:34 am Post subject: |
|
|
voytas wrote: | if A is a pointer to a struct these are equivalents: Code: | (*A).val = 10;
A->val = 10; |
|
You're right. I've put right comma in a wrong place  _________________ The clock is ticking, brothers and sisters, counting down to Armageddon. |
|
Back to top |
|
 |
|