Mail Archives: djgpp/2000/02/15/18:08:31
From: | merkur AT my-deja DOT com
|
Newsgroups: | comp.os.msdos.djgpp
|
Subject: | Re: sprintf woes
|
Date: | Tue, 15 Feb 2000 21:37:21 GMT
|
Organization: | Deja.com - Before you buy.
|
Lines: | 115
|
Message-ID: | <88cguh$1h9$1@nnrp1.deja.com>
|
References: | <87pssv$12f$1 AT nnrp1 DOT deja DOT com>
|
NNTP-Posting-Host: | 195.186.242.20
|
X-Article-Creation-Date: | Tue Feb 15 21:08:07 2000 GMT
|
X-Http-User-Agent: | Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)
|
X-Http-Proxy: | 1.1 x41.deja.com:80 (Squid/1.1.22) for client 195.186.242.20
|
To: | djgpp AT delorie DOT com
|
DJ-Gateway: | from newsgroup comp.os.msdos.djgpp
|
Reply-To: | djgpp AT delorie DOT com
|
In article <87pssv$12f$1 AT nnrp1 DOT deja DOT com>,
mrdang AT my-deja DOT com wrote:
> I am having a lot of trouble with sprintf. I
can not seem to make it
> do what I want within a subroutine /
procedure. As an example:
>
> #include <stdio.h>
>
> void testing(void);
>
> int main()
> {
> char *f, *g, *j;
>
> testing();
> testing();
>
> sprintf(f, "q");
> sprintf(g, "w");
>
> printf("%s\n", f);
> printf("%s\n", g);
>
> sprintf(j, "s: %s %s", f, g);
> printf("%s\n\n", j);
>
> return 0;
> }
>
> void testing()
> {
> char *t, *m, *h;
>
> sprintf(m, "b");
> sprintf(h, "d");
>
> printf("%s\n", m);
> printf("%s\n", h);
>
> sprintf(t, "s: %s %s", m, h);
> printf("%s\n\n", t);
> }
>
> The above gives me:
> (null)
> (null)
> (null)
>
> (null)
> (null)
> (null)
>
> q
> w
> s: q w
>
> When I wanted it to give me:
> b
> d
> s: b d
>
> b
> d
> s: b d
>
> q
> w
> s: q w
>
> Can anybody point out whjat I am doing wrong
here? Thanks :)
>
> Dan G
>
> Sent via Deja.com http://www.deja.com/
> Before you buy.
>
Hello Dan
In the above code all the pointers (f. g, j etc)
are not initialized i.e. they point to an unknown
memory location. Writing to these pointers can
crash your system.
If you want to format strings with sprintf you
need to allocate a char buffer
char buffer[20];
char *pc = &buffer[0]; // Initialize pointer
Then you can use sprintf to generate a formatted
string
sprintf (pc, "Hello");
Printing the string with
printf ("String: %s\n", pc);
should produce the output
String: Hello
If your buffer is 20 bytes in length you can only
write 19 bytes of text because 1 byte is needed
for the terminating \0 (eos) character.
MR
Sent via Deja.com http://www.deja.com/
Before you buy.
- Raw text -