Reputation: 39
I have the program (let's call it pr), and I can't understand what happens that suddenly I get an error when everything seem to be right. In terminal, I type:
./pr 2011-11-01/03:20
and I want to store into 2 arrays the date and the time. The date in the array aa == "2011-11-01" and the time in bb == "03:20" and at the end print them. So, I wrote the code below:
EDIT: The new code with malloc()
below:
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main (int argc, char *argv[]) {
int j=0, i=0;
char *aa = malloc(10*sizeof(char));
char *bb = malloc(5*sizeof(char));
while ( j!=10 ) {
aa[j] = *(argv[1]+j);
j++;
}
j++;
while ( *(argv[1]+j) != '\0' ) {
bb[j-11] = *(argv[6]+j++);
}
printf("%s and %s", aa, bb);
}
But the output of the above is:2011-11-01Y and 03:20
where Y is a random character every time...
End of edit...
Old one below:
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main (int argc, char *argv[])
{
char *aa, *bb; int j=0, i=0;
while ( *(argv[1]+j) != '/' )
{
aa[j] = *(argv[6]+j++);
}
j++;
while ( *(argv[1]+j) != '\0' )
{
bb[i++] = *(argv[1]+j++);
}
printf("%s %s", aa, bb);
}
The code above doesn't work for some reason, but when I write:
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main (int argc, char *argv[])
{
char *aa; int j=0;
while ( *(argv[1]+j) != '/' )
{
aa[j] = *(argv[1]+j++);
}
printf("%s", aa);
}
or
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main (int argc, char *argv[])
{
char *bb; int j, i=0;
j=11; printf("%d", j);
while ( *(argv[1]+j) != '\0' )
{
bb[i++] = *(argv[1]+j++);
}
printf("%s", bb);
}
it works fine! Does anybody know why is this happening?
Upvotes: 0
Views: 82
Reputation: 681
You should do
char *aa = malloc(11*sizeof(char));
to account for the \0 character and after the first loop you should write
aa[j] = '\0'
Basically, you are not ending the aa string with a \0 so the printf does not stop at the final character and thus you have a random one afterwards.
Upvotes: 1