简体   繁体   English

C编程strcat使用指针

[英]C programming strcat using pointer

I am a beginner in C. I wanted to make strcat function using pointers. 我是C的初学者。我想用指针创建strcat函数。 I made it but don't know what is wrong with it. 我做到了,但不知道它有什么问题。 I used gcc compiler and it gave segmentation fault output. 我使用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;
}

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 . 你必须在s的末尾分配新的空间来复制。 Otherwise, your while loo[ will go in memory you don't have access to. 否则,你的厕所[将进入内存,你没有访问权限。

You shoul learn about malloc() here . 你应该在这里了解malloc()

It is undefined behaviour to modify a string literal and s , and eventually p , is pointing to a string literal: 修改字符串文字和s是未定义的行为,并且最终p指向字符串文字:

char* s = "james";

s is passed as first argument to scat() to which the local char* p is assigned and then: s作为第一个参数传递给分配了本地char* p scat() ,然后:

*p=*t;

which on first invocation is attempting to overwite the null character an the end of the string literal "james" . 在第一次调用时,它试图将空字符覆盖在字符串文字"james"的末尾。

A possible solution would be to use malloc() to allocate a buffer large enough to contain the concatentation of the two input strings: 一个可能的解决方案是使用malloc()来分配足够大的缓冲区来包含两个输入字符串的连接:

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* . 调用者必须记住free()返回的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. 因为p一直持续到字符串的末尾,然后它开始前进到非法内存。 That is why you get segmentation fault. 这就是你得到分段错误的原因。

It's because s points to "james\\0", string literal & you cannot modify constant. 这是因为s指向“james \\ 0”,字符串文字并且你不能修改常量。

Change char *s="james"; 改变char *s="james"; to char s[50]="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. char *不是字符串或字符数组,它是数据开头的地址。

you can't do a char * - char* !! 你不能做一个char * - char * !!

This is a good tutorial to start with 这是一个很好的教程

you will have to use malloc 你将不得不使用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 . 你得到一个分段错误,因为你将指针移动到s的末尾然后开始直接在sp的数据写入内存。 What makes you believe there is writable memory available after s ? 是什么让你相信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). 将数据写入不可写内存的任何尝试都会导致分段错误,并且看起来s后面s内存不可写(这是预期的,因为“字符串常量”通常存储在只读内存中)。

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. 首先请记住,当你想要返回指向函数内创建的东西的指针时,它需要在某处进行malloc。 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. 如果您遵循前一种方法,请不要忘记在完成后将其free()

Also, the function scat has to return a pointer in the declaration ie char *scat , not char scat . 此外,函数scat必须返回声明中的指针,即char *scat ,而不是char scat

Finally you don't need that loop to print the string, printf("%s", 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. 首先,由于以下行,您的代码将处于infinte循环中。 you were supposed to use curely braces by including "p++; t++ " statements. 你应该通过包含“p ++; t ++”语句来使用实心大括号。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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