PHWinfo banniere

Titres
PORTAIL ANNUAIRE ARTICLES COMPARATEUR HÉBERGEURS DEVIS FORUMS RÉDUCTEUR D'URL
Précédent   PHWinfo > Autres forums > Forum Programmation & Conception > comp.lang.c > A Stupid Question about Structure
S'inscrire FAQ Membres Recherche Messages du jour Marquer les forums comme lus
A Stupid Question about Structure

Réponse
 
LinkBack Outils de la discussion
Vieux 01/02/2008, 09h23   #1
ot_007_2001@hotmail.com
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut A Stupid Question about Structure

Hi, all,

For pricticing defination of structure in C, I wrote a small code as
follow:

#include<stdio.h>

struct datastruct
{
int data;
struct datastruct *next;
};
typedef struct datastruct dataType;
typedef struct datastruct *dataTypePt;

int main()
{
dataType y;
dataTypePt p;
dataTypePt *Pt;


y.data=1;
p->data=2;

/*Here, compiler says "Segmentation falt" */
(*pt)->data=3;
printf("\n%d\n%d\n%d\n",y.data,p->data,(*pt)->data);

return 0;


}

I'm confusing about the use of structure. Anyone can me?
  Réponse avec citation
Vieux 01/02/2008, 09h31   #2
James Dow Allen
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: A Stupid Question about Structure

On Feb 1, 4:23pm, ot_007_2...@hotmail.com wrote:
> typedef struct datastruct dataType;
> typedef struct datastruct *dataTypePt;


typedefs like these are usually purposeless obfuscations.

> dataTypePt p;


OK, you've allocated memory for a pointer.
It's automatic, so uninitialized (i.e., garbage).
(If static it would be initialized to NULL.)

> p->data=2;


"Dereferencing" an uninitialized pointer?
Wrong.

> /*Here, compiler says "Segmentation falt" */


Whew, you lucked out!
(Some wise-acre will point out, the compiler
"would have been within its rights" to format
your hard disk!)

> I'm confusing about the use of structure. Anyone can me?


Not structures. You're confused about pointers,
or rather the need to give them values.

James

  Réponse avec citation
Vieux 01/02/2008, 09h34   #3
Mark Bluemel
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: A Stupid Question about Structure

ot_007_2001@hotmail.com wrote:
> Hi, all,
>
> For pricticing defination of structure in C, I wrote a small code as
> follow:
>
> #include<stdio.h>
>
> struct datastruct
> {
> int data;
> struct datastruct *next;
> };
> typedef struct datastruct dataType;
> typedef struct datastruct *dataTypePt;


You'll probably find many people suggesting that you don't use
typedef for pointers, but you may chose to ignore them...

You've chosen poor names for your structures and types, in my
opinion, by the way.

> int main()
> {
> dataType y;


so y is a structure. OK

> dataTypePt p;


So p is a pointer to structure, but hasn't been initialised to point to
a structure...

> dataTypePt *Pt;


Pt is a pointer to a pointer to structure and again hasn't been
initialised.

> y.data=1;


That's fine.

> p->data=2;


So you are trying to follow an unitialised pointer... Not a good idea.

> /*Here, compiler says "Segmentation falt" */


I doubt it. I'd worry about a compiler that had a segmentation fault.

It's more likely that your program builds and then fails when you run
it.

> (*pt)->data=3;


Similar problems - following an unitialized pointer, trying to use
whatever you find as a pointer to structure.

> printf("\n%d\n%d\n%d\n",y.data,p->data,(*pt)->data);
>
> return 0;
>
>
> }
>
> I'm confusing about the use of structure. Anyone can me?


Try reading a good textbook (I like Kernighan and Ritchie) and the C FAQ
at www.c-faq.com
  Réponse avec citation
Vieux 01/02/2008, 09h40   #4
Nick Keighley
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: A Stupid Question about Structure

On 1 Feb, 09:23, ot_007_2...@hotmail.com wrote:

> For pricticing defination of structure in C, I wrote a small code as
> follow:
>
> #include<stdio.h>


#include <stdio.h>

>
> struct datastruct
> {
> int data;
> struct datastruct *next;};


struct datastruct *next;
};


> typedef struct datastruct dataType;


I think this is a good idea because it saves the oddity of "struct"
being part of the type name. Other people disagree.


> typedef struct datastruct *dataTypePt;


I think this is a bad idea as it hides the pointerness.
Most people (?) agree though some disagree.



> int main()


int main(void)

> {
> dataType y;


this is a struct

> dataTypePt p;


this is a pointer to struct. It isn't pointing at anything

> dataTypePt *Pt;


this is a ptr-to-ptr-struct. Did you mean to do that?

> y.data=1;


ok, you've written to the data field of y

> p->data=2;
> /*Here, compiler says "Segmentation falt" */


which is compiler speak for "oops! deep shit"
p doesn't point at anything.
maybe

p = &y; /* point p at y */
p->data = 2;

> (*pt)->data=3;


pt doesn't point at anything.
pt = &p; /* assume p points at something */
(*pt)->data = 3;

> printf("\n%d\n%d\n%d\n",y.data,p->data,(*pt)->data);


I prefer more whitespace and find your version unreadable.

printf ("\n%d\n%d\n%d\n", y.data, p->data, (*pt)->data);

you accessed two uninitialised pointers.

> return 0;
> }
>
> I'm confusing about the use of structure. Anyone can me?


I think you are confused about the use of pointers.
But without a specific question I can't .
Get a good book, eg. K&R


--
Nick Keighley

Unicode is an international standard character set that can be used
to write documents in almost any language you're likely to speak,
learn or encounter in your lifetime, barring alien abduction.
(XML in a Nutshell)


  Réponse avec citation
Vieux 01/02/2008, 09h53   #5
ot_007_2001@hotmail.com
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: A Stupid Question about Structure

Thank you all

Now, the biggest problem seems to be the pointer pointing to nothing.

To initialise a struct pointer, should I use the malloc(), or I have
to get it point to a struct variable?

  Réponse avec citation
Vieux 01/02/2008, 10h11   #6
Mark Bluemel
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: A Stupid Question about Structure

ot_007_2001@hotmail.com wrote:
> Thank you all
>
> Now, the biggest problem seems to be the pointer pointing to nothing.
>
> To initialise a struct pointer, should I use the malloc(), or I have
> to get it point to a struct variable?
>

It entirely depends on what you are trying to achieve...

I think most of us feel that you need to spend more time with a good
textbook or tutorial (or both) rather than trying to learn by tinkering.
  Réponse avec citation
Vieux 01/02/2008, 17h19   #7
Kenneth Brody
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: A Stupid Question about Structure

James Dow Allen wrote:
>
> On Feb 1, 4:23 pm, ot_007_2...@hotmail.com wrote:

[...]
> > p->data=2;

>
> "Dereferencing" an uninitialized pointer?
> Wrong.
>
> > /*Here, compiler says "Segmentation falt" */

>
> Whew, you lucked out!
> (Some wise-acre will point out, the compiler
> "would have been within its rights" to format
> your hard disk!)

[...]

Consider a system without memory protection (real-mode MS-DOS comes
to mind). Consider the possible ramifications of storing a "2" in
some random memory location. Reformatting your hard drive, possibly
two days later, while very unlikely, is not impossible. (And, as
far as the C standard is concerned, it's a perfectly legal outcome.)

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:ThisIsASpamTrap@gmail.com>


  Réponse avec citation
Vieux 01/02/2008, 17h22   #8
Keith Thompson
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: A Stupid Question about Structure

ot_007_2001@hotmail.com writes:
> For pricticing defination of structure in C, I wrote a small code as
> follow:
>
> #include<stdio.h>
>
> struct datastruct
> {
> int data;
> struct datastruct *next;
> };
> typedef struct datastruct dataType;


As you've seen in this thread, typedefs for structs are controversial.
Personally, I prefer not to use them; it's simpler to refer to the
type as "struct datastruct" than to invent a new name for it.
Remember that a typedef merely creates an alias for an existing type;
your type "struct datastruct" already has a perfectly good name.

On the other hand, plenty of intelligent people do like typedefs for
structs, so that the type has a simple one-word name and you don't
have to repeat the "struct" keyword every time you refer to it.

But in either case, there's no good reason to use a substantially
different name for the struct tag than for the typedef. You're using
two different names, "datastruct" and "dataType", for the same thing;
you *could* use exactly the same name for both:

struct dataType
{
int data;
struct dataType *next;
};
typedef struct dataType dataType;

or even:

typedef struct dataType
{
int data;
struct dataType *next;
} dataType;

The latter is a very common idiom. There's no ambiguity; the name
"datastruct" is interpreted as a struct tag if and only if it
immediately follows the "struct" keyword.

> typedef struct datastruct *dataTypePt;


Typedefs for pointer types are less controversial; they're widely
considered to be a bad idea. For any use of the name dataTypePt, it's
important to know that it's a pointer type, so don't hide that
information behind a typedef (even if it ends in "Pt"). Just refer to
the type as "struct datastruct*" or "dataType*".

> int main()


Better: "int main(void)".

> {
> dataType y;
> dataTypePt p;
> dataTypePt *Pt;
>
>
> y.data=1;
> p->data=2;


A bit of whitespace around the "=" operator would make this easier to
read:

y.data = 1;
p->data = 2;

> /*Here, compiler says "Segmentation falt" */


No, the compiler doesn't say that. (At least I *hope* it doesn't.)
The compiler is the component that translates your C program into
executable code; once you have an executable file, the compiler's job
is done. You got that message when you ran your program. The message
came from your program, or from the runtime environment, or from the
operating system.

And as you know by now, it happened because "p" had not been
initialized. In this particular case, that means the value of "p" is
arbitrary garbage. You're lucky that the error was detected; if "p"
had happened, by chance, to point to some valid chunk of memory, you
could have silently stored the value 2 anywhere. It's not uncommon for
programs with errors like this to *appear* to work correctly, or to
fail in ways that don't obviously relate to the actual cause.

> (*pt)->data=3;
> printf("\n%d\n%d\n%d\n",y.data,p->data,(*pt)->data);


Spaces after the commas would make this more readable.

There's a delicate balance between too much whitespace and too little.
Consider running your code through a source code formatter; you'll
need to play with the settings to get results that you like. Look at
some existing well-written code, such as the examples in K&R2.

> return 0;


Thank you for remembering to return a value from main; too many people
neglect this. Strictly speaking, this may or may not be necessary,
depending on some details I won't go into here, but it's never wrong
to return 0. [Numerous nit-picking examples where it would be wrong
to return 0 deleted.]

> }
>
> I'm confusing about the use of structure. Anyone can me?


I've probably created more confusion. The more you know, the more you
know you don't know.

--
Keith Thompson (The_Other_Keith) <kst-u@mib.org>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
  Réponse avec citation
Vieux 01/02/2008, 20h38   #9
Keith Thompson
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: A Stupid Question about Structure

Keith Thompson <kst-u@mib.org> writes:
[...]
> But in either case, there's no good reason to use a substantially
> different name for the struct tag than for the typedef. You're using
> two different names, "datastruct" and "dataType", for the same thing;
> you *could* use exactly the same name for both:
>
> struct dataType
> {
> int data;
> struct dataType *next;
> };
> typedef struct dataType dataType;
>
> or even:
>
> typedef struct dataType
> {
> int data;
> struct dataType *next;
> } dataType;
>
> The latter is a very common idiom. There's no ambiguity; the name
> "datastruct" is interpreted as a struct tag if and only if it
> immediately follows the "struct" keyword.

[...]

One thing I forgot to mention: there's no ambiguity to the compiler,
but some development environments provide a command to show or jump to
the definition of an identifier when you click on it or otherwise
indicate it. Such environments might not necessarily know the
difference between a typedef and a struct tag (though they *could*
look for a preceding "struct" keyword). In such an environment, *if*
you choose to use typedefs for structs, there might be some advantage
in using distinct identifiers for the struct tag and for the typedef.
But in that case it's still a good idea to have a simple convention
for deriving one from the other. For example, since you're presumably
going to be using the typedef name much more often than the struct
tag, you might append a "_s" suffix to the tag:

typedef struct dataType_s
{
int data;
struct dataType_s *next;
} dataType;

Or even just a single underscore.

--
Keith Thompson (The_Other_Keith) <kst-u@mib.org>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
  Réponse avec citation
Vieux 02/02/2008, 07h15   #10
henry
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: A Stupid Question about Structure

On Feb 1, 1:23 am, ot_007_2...@hotmail.com wrote:
> Hi, all,
>
> For pricticing defination of structure in C, I wrote a small code as
> follow:
>
> #include<stdio.h>
>
> struct datastruct
> {
> int data;
> struct datastruct *next;};
>
> typedef struct datastruct dataType;
> typedef struct datastruct *dataTypePt;
>
> int main()
> {
> dataType y;
> dataTypePt p;
> dataTypePt *Pt;
>
> y.data=1;
> p->data=2;
>
> /*Here, compiler says "Segmentation falt" */
> (*pt)->data=3;
> printf("\n%d\n%d\n%d\n",y.data,p->data,(*pt)->data);
>
> return 0;
>
> }
>
> I'm confusing about the use of structure. Anyone can me?


After define a pointer, you have to allocate memory by malloc() or
assign p=&y. Then you can assign vale to data. Otherwise, pointer
points to no where.
  Réponse avec citation
Réponse


Outils de la discussion

Règles de messages
Vous ne pouvez pas créer de nouvelles discussions
Vous ne pouvez pas envoyer des réponses
Vous ne pouvez pas envoyer des pièces jointes
Vous ne pouvez pas modifier vos messages

Les balises BB sont activées : oui
Les smileys sont activés : oui
La balise [IMG] est activée : oui
Le code HTML peut être employé : non
Trackbacks are oui
Pingbacks are oui
Refbacks are oui


Fuseau horaire GMT +1. Il est actuellement 17h30.


Édité par : vBulletin® version 3.7.3
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.2.0 RC5 Tous droits réservés.
Version française #16 par l'association vBulletin francophone
PHWinfo est un site Éducation Sans Frontières ©2000-2008
Ad Management by RedTyger
©Tous droits réservés par les parties respectives
Page generated in 0,22182 seconds with 18 queries