delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/06/25/01:15:34

From: Chris Mears <cmears AT bigpond DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Pointers and Arrays (Newbie.)
Organization: only if absoultely necessary
Message-ID: <pb4blsg62j72iaajejp50a766p5bl0sb4s@4ax.com>
References: <39533dab$1 AT news DOT telinco DOT net> <nvm8lsgqmcgdur1to6vbgnlit7jn2mdalk AT 4ax DOT com>
X-Newsreader: Forte Agent 1.8/32.548
MIME-Version: 1.0
Lines: 76
Date: Sun, 25 Jun 2000 15:12:03 +1000
NNTP-Posting-Host: 203.54.58.86
X-Trace: newsfeeds.bigpond.com 961909426 203.54.58.86 (Sun, 25 Jun 2000 15:03:46 EST)
NNTP-Posting-Date: Sun, 25 Jun 2000 15:03:46 EST
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

On Sat, 24 Jun 2000 07:39:47 GMT, that hoopy frood Damian Yerrick
scribbled the following:

>On Fri, 23 Jun 2000 11:29:15 +0100, "Adrian Smith"
><Adrian AT atpelectronics DOT connectfree DOT co DOT uk> wrote:
>
>>My program has a header file  in which I've got  :-
>>
>>const char * message = "This is an error message \n"
>>
>>In the main .cpp file I've got :-
>>
>>cout << message << endl;
>>
>>When i try to compile, it comes up with:-
>>
>>error :<filename.cpp> :  multiple defenition of 'message'
>>
>>If i use an array - ie, const char message[30] = "This is an error message
>>\n"
>>this works perfectly. Could somebody please tell me where Iam going wrong
>>with the pointer method.
>
>You're trying to store a string inside a pointer.

No, he's not trying to do anything of the sort.  He's trying to have a
pointer point to an array of char, which is perfectly normal.

>  This is just wrong.

No, it's just right.

>Strings are supposed to go into character arrays.

A string literal is a character array.

>If you want an
>array that is just big enough to hold what you put into it, do this:
>
>const char message[] = "hello world\n";

That's not what you do if you want a pointer to a string literal,
though.

To the OP:
You were getting a multiple definition error.  I can't be certain of
the problem from what you've posted, but my guess is that you are
including the header from two different modules and linking them
together, which creates two definitions of the one variable (hence the
"multiple definition").

Change the definition in the header to a declaration by removing the
initialisation and in exactly one of the source files, add an
initialiser.

== a.h ==

char *message;

== b.c ==

char *message = "I am a foo bird.";

== c.c ==

#include <stdio.h>
#include "a.h"
void foo(void)
{
    /* prints "I am a foo bird." */
    puts(message);
}

-- 
Chris Mears
ICQ: 36697123

- Raw text -


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