delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/08/29/03:47:52

From: bergervo AT iaehv DOT IAEhv DOT nl (Jos Bergervoet)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: More string problems!
Date: 28 Aug 1997 17:19:43 GMT
Organization: Internet Access Eindhoven, the Netherlands
Lines: 42
Message-ID: <5u4bvf$1di$1@news.IAEhv.nl>
References: <34058C10 DOT 254EBF66 AT phs DOT mat-su DOT k12 DOT ak DOT us>
NNTP-Posting-Host: iaehv.iaehv.nl
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Kevin Dickerson <kevind AT phs DOT mat-su DOT k12 DOT ak DOT us> writes:

>Allright, yesterday I posted up some code that would do some stuff
>with strings (that isn't important), but now I've encountered the main
>problem associated with it; it strikes me as strange! This code (which
>requires only <stdio.h>):

>main()                                                             // 01
>{                                                                  // 02
>   int l1;                                                         // 03
>   char *chr, *buf, *text;                                         // 04
>   text = "I Can't Believe It's Not Butter!";                      // 05
>   for (l1=0; l1<strlen(text); l1++)                               // 06
>   {                                                               // 07
>      sprintf( chr, "%c", text[l1] );                              // 08
>      strcat( buf, chr );                                          // 09
>   }                                                               // 10
>   printf("margarine = \"%s\"\n", buf );                           // 11
>}                                                                  // l2

>Will compile and run without any problems, but if you change line 3 to:

>   int l1, newvariable;

>   Then it will report char *buf as "(null)". I'm wondering why in the
>world this will not work! Memory allocation shouldn't be a problem,

Yes, it will. Try allocating some of it with line 4 changed into:
   char chr[2], buf[50], *text;                                         // 04
Remember that arrays are, by nature, pointers with memory pre-allocated
to them (hence no * before chr and buf.) The pointer text doesn't need
memory in advance, since here you only use it to point at something.

Greetings, Jos


>---------------------------------
>                 Kevin Dickerson
>     kevind AT phs DOT mat-su DOT k12 DOT ak DOT us
> Webmaster of Palmer High School
>     http://phs.mat-su.k12.ak.us
>---------------------------------

- Raw text -


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