当前位置: 动力学知识库 > 问答 > 编程问答 >

passing pointers to a strcpy function in c

问题描述:

I am trying to pass pointers to strcpy() function. 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. 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, i.e. by passing pointers to strcpy() function

# 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(). 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. Otherwise avoid using strcpy() and you should use strlcpy().

分享给朋友:
您可能感兴趣的文章:
随机阅读: