Problem with string [ULTRA-BEGINNER]

Hi all
I have a newbie problem. The array "hours_match" is not being filled correctly. I dont know why. On the first printf i see that's OK, but on the second it's not. I have this code (please see the BOLD part).

void populate()
{
int i=0;
char line [ MAX_LINE_SIZE ];
char date[12];
char hour[12];
count = 0;

files_match=(char**)calloc (MAX_MATCHES,sizeof(char*));
hours_match=(char**)calloc (MAX_MATCHES,sizeof(char*));
while ( fgets ( line, MAX_LINE_SIZE, fp_file ) != NULL )
{
if(hasString(line,search_string))
{
files_match[count]=fileName;
sscanf(line,"%12s %12s",&date,&hour);
printf("Hour=%s\n",hour);
hours_match[count]=hour; count++;
}
}

printf("FINISH\n");

for(i=0; i<=count-1; i++)
{
printf("Hour=%s\n",hours_match[i]);
}
}


Ouput of this function:
Hour=10:00
Hour=10:10
FINISH
Hour=10:10
Hour=10:10

Can anyone tell me why the hours_match array has:
10:10
10:10
instead of:
10:00
10:10

?

Thanks:)

files_match and hours_match (from now on, simply 'match') are pointers to arrays of pointers to arrays of characters. You are initialing match, but you aren't initializing the pointers inside the array to point to valid memory locations. Instead, you're giving them all the memory location of fileName/hour. Every element in match points to this array.

EDIT: Oh, yeah. Don't use C allocation. We have facilities for that stuff, now. It's called 'new' operator.
Last edited on
Thanks for the reply:)
you said
"It's called 'new' operator"

Can you give me a small example please?
thanks!
You can find about new and delete in the tutorial from this site:
http://www.cplusplus.com/doc/tutorial/dynamic.html

It can really make your life easier because your line:
files_match=(char**)calloc (MAX_MATCHES,sizeof(char*));
can be changed to:
files_match = new char*[MAX_MATCHES];
The new operator automatically allocate the necessary amount of memory.
Thanks for the fast help guys... but i'm using C :(...
there are no "new char*" etc....
i used the
files_match = new char*[MAX_MATCHES];

like you said, but i get this error:
"new undeclared identifier"

do you know how can i fix this in C?
thanks
Oh, if you're using C then never mind.
The solution was "typedef struct" :)
thanks again guys!
Topic archived. No new replies allowed.