From: kagel AT quasar DOT bloomberg DOT com Date: Fri, 7 Feb 1997 10:22:59 -0500 Message-Id: <9702071522.AA27953@quasar.bloomberg.com > To: tudor AT cam DOT org Cc: djgpp AT delorie DOT com In-Reply-To: <32FA7146.3883@cam.org> (message from Tudor on Thu, 06 Feb 1997 16:03:18 -0800) Subject: Re: Question on pointers and arrays Reply-To: kagel AT dg1 DOT bloomberg DOT com Errors-To: postmaster AT ns1 From: Tudor Newsgroups: comp.os.msdos.djgpp Date: Thu, 06 Feb 1997 16:03:18 -0800 Organization: Communications Accesibles Montreal Lines: 23 References: <32f92a6c DOT 0 AT ntnews DOT compusmart DOT ab DOT ca> Reply-To: tudor AT cam DOT org Nntp-Posting-Host: dynamicppp-93.hip.cam.org Mime-Version: 1.0 Content-Transfer-Encoding: 7bit X-Mailer: Mozilla 3.0Gold (Win95; I) Dj-Gateway: from newsgroup comp.os.msdos.djgpp Content-Type: text/plain; charset=us-ascii Content-Length: 558 Demandred wrote: > > Probably a silly question, but... > > If I declare an array of objects of type Foo > > Foo FooArray[5]; > > And pass a pointer to a Foo into a function (or class constructor) > > Bar(Foo *array) {... > > Can I access elements in the array in the function, like so? > > ...array[3]...} I guess you can. When you say Foo array[5] then 'array' is actually a pointer to the first element. char string[5]="abcde" and char *string="abcde" are equivalent. No they are not! char string[5]="abcde" -- This line allocates an array of 5 chars and places the 6 chars "abcde\0" beginning at that location trashing the next byte. (I'll give you the typo.) char *string="abcde" -- This line allocates a pointer variable and assigns the address of the static string "abcde\0" to that pointer. That's the same thing you say? Try this: char *string1 = "abcde", *string2 = "abcde"; char string3[6] = "abcde", string4[6] = "abcde"; printf( "&string1=%p\n", string1 );/* String1 & string2 hold the same address */ printf( "&string2=%p\n", string2 );/* unless -fwritable-strings is included */ printf( "&string3=%p\n", string3 );/* in the compile. String3 and string4 */ printf( "&string4=%p\n", string4 );/* are at different addresses and in a */ /* whole other segment than string1 & 2 */ fflush( stdout ); strcpy( string1, "fghij" ); /* First problem, most compilers, including GCC/DJGPP, will SEGV here because static strings are usually put into an unwritable string space. With all references to the same string pointing to the same single constant value. Some compilers will not fault but string2 will also have been modified. GCC solves both problems with the -fwritable-strings compile argument. */ strcpy( string3, "fghij" ); printf( "string1: %s\n", string1 ); printf( "string2: %s\n", string2 ); printf( "string3: %s\n", string3 ); printf( "string4: %s\n", string4 ); -- Art S. Kagel, kagel AT quasar DOT bloomberg DOT com A proverb is no proverb to you 'till life has illustrated it. -- John Keats