简体   繁体   English

strcpy崩溃C程序

[英]strcpy Crashes C Program

Please tell me why strcpy fails. 请告诉我为什么strcpy失败。 Im trying to copy the value str1 into one of the element of str2. 我试图将值str1复制到str2的元素之一。

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

int main(int argc, char *argv[]) {

    char str1[]={"cat"}; //string
    char *str2[]={"mouse","dog"}; //array
    strcpy(str2[0],str1);       

    return 0;
}   
char str1[]={"cat"}; //string

is wrong in this context 在这种情况下是错误的

"" is a replacement for tedious {'a','b'...'\\0'} . ""代替乏味的{'a','b'...'\\0'}

Do either 要么做

char str1[]="cat";

or 要么

char str1[]={'c','a','t','\0'};

Even then your code wouldn't work 即使那样,您的代码也无法正常工作

strcpy(str2[0],str1); 

because you are trying to write into a read-only hard coded memory 因为您正在尝试写入只读硬编码存储器

as [ @michi ] mentioned in his comment. 正如[@michi]在他的评论中提到的。

But below would work 但是下面会工作

str2[0]=malloc(sizeof(str1)); // You allocate memory for str2[0];
strcpy(str2[0],str1); 
printf("str2[0] : %s\n",str2[0])

Also remember to free the allocated memory after use 还记得使用后释放分配的内存

free(str2[0]);

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

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