简体   繁体   English

在c中传递指向strcpy函数的指针

[英]passing pointers to a strcpy function in c

I am trying to pass pointers to strcpy() function.我正在尝试将指针传递给 strcpy() 函数。 But on running this code, I get no output and the program stops responding, even though I don't get any compile error.但是在运行此代码时,我没有得到任何输出并且程序停止响应,即使我没有收到任何编译错误。 I know that strcpy() function takes the arguments as pointers, and here I am passing the pointers directly.我知道 strcpy() 函数将参数作为指针,在这里我直接传递指针。 So I want to know why the following code is not working properly.所以我想知道为什么下面的代码不能正常工作。 And also tell me how to modify the code and if possible using same concept, ie by passing pointers to strcpy() function并告诉我如何修改代码,如果可能的话,使用相同的概念,即通过将指针传递给 strcpy() 函数

# include<stdio.h>
# include<conio.h>
# include<stdlib.h>
# include<string.h>
int main() {
    char *rt = "dart";
    char *ft = "gart";
    strcpy(rt, ft);
    printf("%s", rt);
    system("PAUSE");
}

First of all you need a placeholder to store your to be copied source string using strcpy().首先,您需要一个占位符来使用 strcpy() 存储要复制的源字符串。 You need to declare a char array[] where you will copy the source string.您需要声明一个字符数组[],您将在其中复制源字符串。

int main() {
    char rt[10];
    char *ft = "gart";
    strcpy(rt, ft);
    printf("%s", rt);
    return 0;
}

Also make sure destination array 'rt' in this case has sufficient memory to store the to be copied string.还要确保在这种情况下目标数组 'rt' 有足够的内存来存储要复制的字符串。 Otherwise avoid using strcpy() and you should use strlcpy().否则避免使用 strcpy() 而你应该使用 strlcpy()。

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

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