🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: gnu.gcc.help
Article #50413

Re: char * vs char[]

#50413
From: D. Erway
Date: Tue, 28 Sep 1993 03:09
48 lines
2390 bytes
>>>>> On Fri, 24 Sep 1993 19:23:11 GMT, swmckeou@undergrad.math.uwaterloo.ca
>>>>> (Sean McKeough) said:

 swmckeou> The following code gives seg faults when run

 swmckeou> char *pword
 swmckeou> fscanf(stdin, "%s", pword);

Of course. You have asked fscanf to write stuff out to wherever pword happens
to point. This is very likely address 0, if pword is outside a function, or
could be anywhere if it is on the stack. The memory management hardware
detects that you are trying to write to an address that you do not have
permission to write.

 swmckeou> however, it works if I replace *pword by pword[50] why is this?

Yes, because you have created enough space, (enough for 50 pointers, very
likely this is 200 bytes), and changed what it means when you just say
"pword".

Remember, when you have an array in C, referring to the name of the array, it
refering to the  address of it's zeroth element:

	char foo[20];

	foo == &foo[0]  /* these are equivalent, and both refer the the base
			 * address of foo
			 */

So, what you really want is:

char word[50];
fscanf(stdin, "%s", word);

Better to get K&R, and ask comp.lang.c. This group is really just about the
gnu compiler.

	Good luck,
	  -Don

--
\-----------------------------------------------------------------------/
| Don Erway			   			 derway@ndc.com	|
| NDC Systems								|
| Monrovia, CA			   Opinions expressed herein apparently	|
| (Somewhere Near Pasadena)	   spontaneously organized  themselves.	|
/-----------------------------------------------------------------------\
Technical Details
Message-ID: <DERWAY.93Sep27200921@alumni.ndc.com>
Path: arc1-ca.pugleaf.net!gmd.de!newsserver.jvnc.net!howland.reston.ans.net!usc!elroy.jpl.nasa.gov!news.claremont.edu!nntp-server.caltech.edu!nntp-server.caltech.edu!derway
References: <CDvHuo.2su@undergrad.math.uwaterloo.ca>

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: 11318c,f249bebc260afb3e
X-Google-Attributes: gid11318c,public
X-Google-ArrivalTime: 1993-09-27 23:56:14 PST
Path: arc1-ca.pugleaf.net!gmd.de!newsserver.jvnc.net!howland.reston.ans.net!usc!elroy.jpl.nasa.gov!news.claremont.edu!nntp-server.caltech.edu!nntp-server.caltech.edu!derway
From: derway@ndc.com (D. Erway)
Newsgroups: gnu.gcc.help
Subject: Re: char * vs char[]
Date: 28 Sep 1993 03:09:18 GMT
Organization: NDC Systems - Monrovia, CA
Lines: 48
Message-ID: <DERWAY.93Sep27200921@alumni.ndc.com>
References: <CDvHuo.2su@undergrad.math.uwaterloo.ca>
NNTP-Posting-Host: alumni.caltech.edu
To: swmckeou@undergrad.math.uwaterloo.ca (Sean McKeough)
In-reply-to: swmckeou@undergrad.math.uwaterloo.ca's message of Fri, 24 Sep 1993 19:23:11 GMT