delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/12/15/04:57:23

From: Erik Max Francis <max AT alcyone DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Pointers, arrays and assignments
Date: Sat, 14 Dec 1996 22:25:55 -0800
Organization: Alcyone Systems
Lines: 43
Message-ID: <32B399F3.685CE183@alcyone.com>
References: <32B3AA6F DOT 1302 AT synapse DOT net>
NNTP-Posting-Host: newton.alcyone.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Bill Lachance wrote:

> I'm re-writing my tile-based game under Allegro to work better,
> cleaner, and faster. That means switching from global variables
> to pointers. ;)

Probably not; I'm not familiar with Allegro, but certainly you can just
pass the _address_ of what you're trying to send it.

> For some reason though, when I try to assign values to my pointer
> to player structures, the thing crashes.
> 
> I've initialised them like so: player *plyr[3] (the game will
> support up to three players, and the array seemed to be the
> best way of supporting that). But when I try a stunt like:
> plyr[0]->X=4960, the program crashes abruptly (I've isolated the
> problem).
> 
> Am I breaking some unknown rule here?

You're breaking the fundamental rule with dealing with pointers; pointers
have to point to something.

Declaring, say, a pointer to an int does _not_ allocate the memory for the
int -- you have to do that yourself.  A pointer, after all, is merely an
address where the object it's pointing to is located.  An uninitialized
pointer (or an array of pointers) will be pointing to random places, and
thus when dereferenced (i.e., when you try to assign to what the pointer is
pointing at) will crash.

You need to dynamically allocate (and then free when you're finished) the
pointers that you're trying to use.  My suggestion to you is that you get
_A book on C_ or _C by dissection_ or some other simple introductory C book
and very carefully read the sections on arrays, pointers, and strings.
Pointers are not a trivial concept to get down, but they're essential for
good C programming.

-- 
                             Erik Max Francis | max AT alcyone DOT com
                              Alcyone Systems | http://www.alcyone.com/max/
                         San Jose, California | 37 20 07 N 121 53 38 W
                                 &tSftDotIotE | R^4: the 4th R is respect
     "You must surely know if man made heaven | Then man made hell"

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019