-2

I coded a strcat function. But my function doesn't run in this way -----> char * mystrcat(char *s,char *t). I want to return a pointer. Can you help me?

#include <stdio.h>

void mystrcat(char *s,char *t)
{
    while(*s!='\0')
        s++;
        s--;
    while((*(s+1)=*t)!='\0')
    {   s++;
        t++;
    }
}

int main()
{

    char str[30], str1[30];
   gets(str);
   gets(str1);
   mystrcat(str, str1);
    printf("%s\n",str);
    return 0;
}
user1946383
  • 1
  • 1
  • 2

2 Answers2

0

Your function has no return value. If you want to return a pointer from it then just return it. And also void is incorrect for that

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
0

When you write void mystrcat(char *s,char *t) you are saying "I will not have a return value" by using void. If you want to return a pointer, this must not be void.

To return a pointer to your string, use char**.

Your string, a series of characters, is represented as a char*.

Here's an example using your code.

#include <stdio.h>

char** mystrcat(char *s,char *t)
{
    char *sOrig = s;
    while(*s!='\0'){
        s++;
    }
    s--;

    while( ( *(s+1) = *t) != '\0')
    {
        s++;
        t++;
    }
    return &sOrig;
}

int main()
{
   char str[30], str1[30];
   gets(str);
   gets(str1);
   char** concatValuePointer = mystrcat(str, str1);
   printf("Pointer is %p\n",concatValuePointer);
   return 0;
}
Mat Kelly
  • 2,327
  • 7
  • 29
  • 51
  • The issue, and the basis for this approach, is that you are corrupting the original pointer location that you pass in. By retaining that value (sOrig) prior to incrementing it (s++), you are keeping a reference (i.e. a pointer) to the original pointer. Does this answer your question? If not, please describe further what you would like to accomplish. – Mat Kelly Jan 04 '13 at 21:01