Mail Archives: djgpp/1998/08/17/11:15:53
From: | loki AT nectar DOT com DOT au-remove (loki)
|
Newsgroups: | comp.os.msdos.djgpp
|
Subject: | Re: yet more questions about pointers
|
Date: | 17 Aug 98 15:11:20 GMT
|
Organization: | Nectar Online Services
|
Lines: | 54
|
Message-ID: | <slrn6tghog.4a.loki@anima.nectar.com.au>
|
References: | <01bdc7e8$c1ff0e20$4ac3b8cd AT scully>
|
NNTP-Posting-Host: | 203.18.79.30
|
To: | djgpp AT delorie DOT com
|
DJ-Gateway: | from newsgroup comp.os.msdos.djgpp
|
Cephaler <cephaler AT hotmail DOT com> wrote:
>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?
Nope, this is pretty typical I'd say... people use pointers to iterate
over lists, arrays and all sorts of things. There isn't anything wrong with
assigning one pointer to another.
>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)
The important thing is the memory rather than the variable. You can free
the memory by calling free() on any pointer which points to it. Of course,
if you use free(string2) then string1 no longer points to any valid memory
(and vice versa). Calling free() on a null pointer is a bad idea, though
some implementations of free() simply ignore them (relying on this behaviour
would be a bad idea though.)
>3) concerning strcpy...is there any special reason why I shouldn't just use
>string1 = "foobar" ?
You can't do this, "foobar" is not an "rvalue", which is something you can
assign to something. If you want to initialise a string, do so like this:
char string1[] = "foobar";
You can also initialise them the way you can any other array:
char string1[] = {'f','o','o','b','a','r'};
Note that in either case, if you leave out the size of the array the
compiler will automatically calculate the size necessary (in the first
example above the compiler will also add the space for the null-terminator
character).
--
loki
loki (at) nectar.com.au http://puck.nether.net/~loki/
# Dare I disturb the universe? You bet I do!
- Raw text -