C编程strcat使用指针

Kun*_*egi 2 c

我是C的初学者.我想用指针创建strcat函数.我做到了,但不知道它有什么问题.我使用gcc编译器,它给出了分段错误输出.

#include<stdio.h>
#include<string.h>

char scat(char *,char *);

void main()
{
    char *s="james";
    char *t="bond";

    char *q=scat(s,t);
    while(*q!='\0') printf("the concatenated string is %c",*q);
}

char *scat(char *s,char *t)
{
    char *p=s; 
    while(*p!='\0'){
        p++;
    } 
    while(*t!='\0'){
        *p=*t;
        p++;
        t++;
    }
    return p-s-t;
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*chs 6

这个工作:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *scat(char *,char *);                 /* 1: your prototype was wrong */

void main()
{
    char *s="james";
    char *t="bond";

    char *q=scat(s,t);   
    printf("cat: %s\n", q);               /* 2: you can use %s to print a string */
    free(q);
}

char *scat(char *s,char *t)
{
    char *p=malloc(strlen(s)+strlen(t)+1);    /* 3: you will have to reserve memory to hold the copy. */
    int ptr =0, temp = 0;                   /* 4 initialise some helpers */

    while(s[temp]!='\0'){                  /* 5. use the temp to "walk" over string 1 */
        p[ptr++] = s[temp++];
    }
    temp=0;
    while(t[temp]!='\0'){                   /* and string two */
        p[ptr++]=t[temp++];
    }
    return p;
}
Run Code Online (Sandbox Code Playgroud)