Mail Archives: djgpp/1997/08/29/03:47:52
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 -