简体   繁体   中英

C programming strcat using pointer

I am a beginner in C. I wanted to make strcat function using pointers. I made it but don't know what is wrong with it. I used gcc compiler and it gave segmentation fault output.

#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;
}

This one works:

#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;
}

You have to allocate new space to copy at the end of s . Otherwise, your while loo[ will go in memory you don't have access to.

You shoul learn about malloc() here .

It is undefined behaviour to modify a string literal and s , and eventually p , is pointing to a string literal:

char* s = "james";

s is passed as first argument to scat() to which the local char* p is assigned and then:

*p=*t;

which on first invocation is attempting to overwite the null character an the end of the string literal "james" .

A possible solution would be to use malloc() to allocate a buffer large enough to contain the concatentation of the two input strings:

char* result = malloc(strlen(s) + strlen(p) + 1); /* + 1 for null terminator. */

and copy them into it. The caller must remember to free() the returned char* .

You may find the list of frequently asked pointer questions useful.

Because p goes till the end of the string and then it starts advancing to illegal memory. That is why you get segmentation fault.

It's because s points to "james\\0", string literal & you cannot modify constant.

Change char *s="james"; to char s[50]="james"; .

You need to understand the basics of pointers.

a char * is not a string or array of characters, it's the address of the beginning of the data.

you can't do a char * - char* !!

This is a good tutorial to start with

you will have to use malloc

You get a segmentation fault because you move the pointer to the end of s and then just start writing the data of p to the memory directly following s . What makes you believe there is writable memory available after s ? Any attempt to write data to non-writable memory results in a segmentation fault and it looks like the memory following s is not writable (which is to expect, since "string constants" are usually stored in read-only memory).

Several things look out of order.

First keep in mind that when you want to return a pointer to something created within a function it needs to have been malloc'ed somewhere. Much easier if you pass the destination as an argument to the function. If you follow the former approach, don't forget to free() it when you're done with it.

Also, the function scat has to return a pointer in the declaration ie char *scat , not char scat .

Finally you don't need that loop to print the string, printf("%s", string); will take care of printing the string for you (provided it's terminated).

At first, your code will be in infinte loop because of the below line. you were supposed to use curely braces by including "p++; t++ " statements.

while(*t!='\0')
 *p=*t;

though you do like this, you are trying to alter the content of the string literal. which will result in undefined behavior like segmentation fault.

A sequence of characters enclosed with in double quotes are called as string literal. it is also called as "string". String is fixed in size. once you created, you can't extend its size and alter the contents. Doing so will lead to undefined behavior.

To solve this problem , you need to allocate a new character array whose size is sum of the length of two strings passed. then append the two strings into the new array. finally return the address of the new array.

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

char* scat(char *,char *);
void append(char *t , char *s);

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

    char *n = scat(s,t);        
    printf("the concatenated string is %s",n);

    return 0;
}

char* scat(char *s,char *t)
{
    int len = strlen(s) + strlen(t);
    char *tmp = (char *)malloc(sizeof(char)* len);

    append(tmp,s);
    append(tmp,t);

    return tmp;
} 


void append(char *t , char *s)
{   
     //move pointer t to end of the string it points. 
    while(*t != '\0'){
        t++;
    }

    while( *s != '\0' ){
        *t = *s;
        t++;
        s++;    
    }       
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM