delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/08/15/11:15:39

Message-ID: <35D5B384.9FDF797B@sprynet.com>
Date: Sat, 15 Aug 1998 09:12:52 -0700
From: Ishpeck <aTedjamulia AT sprynet DOT com>
Organization: Lunaticnologies
MIME-Version: 1.0
Newsgroups: comp.os.msdos.djgpp
Subject: Re: yet more questions about pointers
References: <01bdc7e8$c1ff0e20$4ac3b8cd AT scully>
NNTP-Posting-Host: 192.41.73.95
Lines: 71
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Well, what you're doing, here, is you're saying string1 points to a
section of memory, 80 bytes big.  Then saying, in that memory, you have
the characters   f, o, o, b, a, and r.

When you say "string2 = string1", you're actually saying, now string2
also points to that same memory.  So, if you change your little string
of characters to "faabor", then, both string2 and string1 will print
"faabor" -- as you discovered.  This is because you're changing the
actual data inside your memory -- you're not changing a string.  All
string1 and string2 are are POINTERS to a string IN MEMORY.

It is impossible to say:   string1="foobar"
because then, you're trying to assign a memory pointer a string, and
that's not possible -- unless you make a string class and utilize the
inline operator... but that's C++.  In any case, Strings don't cast to
pointers very well.

And yes, you should always free your memory.  Sometimes, it gets very
messy, and forgeting to free memory is a bad thing.

I usually put the "free()" command before I type anything else -- so I
don't forget.

I hope this answers your questions.

Have a happy day!
Ishpeck

Cephaler wrote:
> 
>   Ok just concluded several tests concerning pointers, now I have some
> questions to verify my results:
> 
> 1) A simple test program:
> int main(void) {
>   char *string1=(char *)malloc(80);
>   char *string2;
> 
>   strcpy(string1,"foobar");
> 
>   string2 = string1;
> 
>   strcpy(string2,"raboof");
> 
>   printf("%s\n",string1);
>   return(0);
> }
> 
> This yielded 'raboof' to my delight... Now, have I found a good use for
> pointers? Or is this bad bad code?
> 
> 2) Having not initialized string2, a) do I have to free string2 and b) does
> that have any effect on string1? (oops didn't free string1)
> 
> 3) concerning strcpy...is there any special reason why I shouldn't just use
> string1 = "foobar" ?
> 
> If the answers to these questions are what I think they are my pointer
> dilemmas are over... (game still crashes though :( )
> 
> - Cephaler -
> 
> p.s. thanks! <-- insert in previous messages as well

-- 

-------------------
See Ishpeck's Programming page!
Example source, Utils, links, 
and help on your programs.
http://members.xoom.com/ishpeck/

- Raw text -


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