Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Help? Why the program doesn't work

1 view
Skip to first unread message

Wei Kai Zhang

unread,
Sep 11, 1998, 3:00:00 AM9/11/98
to
I wrote the sample program for testing, but it behaves strange. If
anybody know why, please help.
#include<stdio.h>
#include <dos.h>
#include <dir.h>
#include <stdlib.h>
#include <string.h>

char **GetFileNames(char *Path);

char **GetFileNames(char *Path)
{
char **Names;
struct ffblk ffblk;
int done,Cfiles=0;

done = findfirst(Path,&ffblk,0);
while (!done)
{
Names[Cfiles]=(char *)calloc(14,sizeof(char));
if(Names[Cfiles] == NULL)
perror("Error:");
strcpy(Names[Cfiles],ffblk.ff_name);
Cfiles++;
done = findnext(&ffblk);
}
Names[Cfiles]=NULL;
return Names;
}


void main(void)
{
char **Names;
int i;
Names = GetFileNames("c:\\windows\\*.*");

for(i=0;;i++){
if(Names[i] == NULL) break;
printf("%s\n",Names[i]);
free(Names[i]);
}

}

--
<w...@erols.com>

Ben Pfaff

unread,
Sep 11, 1998, 3:00:00 AM9/11/98
to
Wei Kai Zhang <w...@erols.com> writes:

I wrote the sample program for testing, but it behaves strange. If
anybody know why, please help.
#include<stdio.h>
#include <dos.h>

Ooh there you go, you included a nonstandard header. So it behaves
strangely because you invoked undefined behavior.
--
(supporter of the campaign for grumpiness where grumpiness is due in c.l.c)

Please: do not email me copies of your posts to comp.lang.c
do not ask me C questions via email; post them instead

John Gordon

unread,
Sep 11, 1998, 3:00:00 AM9/11/98
to
Wei Kai Zhang <w...@erols.com> writes:

>char **GetFileNames(char *Path)
>{
> char **Names;
> struct ffblk ffblk;
> int done,Cfiles=0;

> done = findfirst(Path,&ffblk,0);
> while (!done)
> {
> Names[Cfiles]=(char *)calloc(14,sizeof(char));
> if(Names[Cfiles] == NULL)
> perror("Error:");
> strcpy(Names[Cfiles],ffblk.ff_name);
> Cfiles++;
> done = findnext(&ffblk);
> }
> Names[Cfiles]=NULL;
> return Names;
>}

you haven't allocated any space for the Names array. you're allocating
space for the *elements* of Names, but not for Names itself. try this:

Names = malloc(80 * sizeof(char *));

or, if you're always going to have a fixed amount of items, declare
Names as an array of char *'s:

char *Names[80];

---
John Gordon "No Silicon Heaven? Preposterous! Where would
gor...@osiris.cso.uiuc.edu all the calculators go?" -- Kryten, Red Dwarf

0 new messages