R
Roy
Hi all :
My code below :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *cat(char *s, const char *t)
{
char *tmp;
if (s == NULL)
tmp = realloc(s,strlen(t) + 1);
else
tmp = realloc(s,strlen(s) + strlen(t) + 1);
if (tmp == NULL) {
fputs("realloc error",stderr);
exit(1);
}
while (*tmp++); // search for '\0' and stop
tmp--; //the position of '\0'
while (*tmp++ = *t++) ;
s = tmp;
return s;
}
int main()
{
char *tmp;
char *s;
s = NULL;
tmp = cat(s,"oh");
printf("%s\n",tmp);
tmp = cat(s,"haha");
printf("%s\n",tmp);
return 0;
}
my problem is when I run the program the reslut is some blanks. I just
wrote a small routine like strcat and check the realloc and tmp pointer
carefully but found nothing.
My code below :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *cat(char *s, const char *t)
{
char *tmp;
if (s == NULL)
tmp = realloc(s,strlen(t) + 1);
else
tmp = realloc(s,strlen(s) + strlen(t) + 1);
if (tmp == NULL) {
fputs("realloc error",stderr);
exit(1);
}
while (*tmp++); // search for '\0' and stop
tmp--; //the position of '\0'
while (*tmp++ = *t++) ;
s = tmp;
return s;
}
int main()
{
char *tmp;
char *s;
s = NULL;
tmp = cat(s,"oh");
printf("%s\n",tmp);
tmp = cat(s,"haha");
printf("%s\n",tmp);
return 0;
}
my problem is when I run the program the reslut is some blanks. I just
wrote a small routine like strcat and check the realloc and tmp pointer
carefully but found nothing.