简体   繁体   English

使用字符指针复制字符串时出错

[英]error in string copy using character pointers

I was implementing string copy function using character pointers but it is showing error. 我正在使用字符指针实现字符串复制功能,但显示错误。 Here is the code: 这是代码:

#include<stdio.h>
#include<string.h>
int main()
{
    char *s="abc";
    char *t;
    while((*s)!='\0')
    {
        *t++=*s++;
    }
    *t='\0';
    printf("%s\n",t);
    return 0;
}
char *t;

There is no memory allocated to your pointer and you are trying to write to it which will lead to undefined behavior.So allocate memory 没有为您的指针分配内存,您正在尝试对其进行写入,这将导致未定义的行为。因此分配内存

char *t = malloc(30); /* size of your choice or strlen(s) + 1*/

Once done using the memory free it using 一旦使用完内存,使用

free(t);

This might result in a segmentation fault 这可能会导致segmentation fault

The reason being : Just think where is char *t pointing to right now? 原因是: 想一想char *t现在指向哪里?

Let's have a look at the possibilities : 让我们看一下可能性:

1.Your char *t is pointing to some memory location which can not be accessed or write-protected; 1.您的char *t指向某个无法访问或写保护的内存位置;

2.It might work in some cases where your pointer is pointing to a memory location that can be accessed and has required space.The possibilities of that being very small. 2.在某些情况下,如果您的指针指向一个可以访问并具有所需空间的内存位置,则这种方法可能会起作用。

So, it's better to use 因此,最好使用

char *t=NULL;
t=malloc(sizeof(char)*n); //Dynamic approach

here n is the no of bytes you are allocating to t 这里n是您要分配给t的字节t

If you're not comfortable with dynamic memory allocation right now reserve some space for t which you think is enough. 如果你不舒服的动态内存分配,现在预留一些空间t ,你认为是足够的。 This will waste some space though. 但是,这将浪费一些空间。

After you're done, free the space allocated; 完成后,释放分配的空间。

free(t);

Note : Always include <stdlib.h> else malloc will result in a warning. 注意 :始终包含<stdlib.h>否则malloc将导致警告。

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

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