问题描述
我正在尝试使用memcpy将C中的一个字符串复制到另一个字符串中,并使用以下代码:
I'm trying to copy one string to another in c using memcpy with the following code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct fullName
{
char* firstName;
char* lastName;
} NAME;
int main()
{
NAME myName, hisName;
myName.firstName = "aaaaaaa";
hisName.firstName = "bbbbbb";
memcpy(myName.firstName, hisName.firstName, sizeof(hisName.firstName));
printf("myName.firstName = %s\n", myName.firstName);
printf("hisName.firstName = %s\n", hisName.firstName);
}
,运行程序后出现分段错误(核心已转储)错误我试图将firstName
和lastName
声明为chars数组的指针,而不是char的指针,但是错误仍然存在.我想念什么?请帮助...
and it gives Segmentation fault (core dumped) Error after running the programI tried to declare firstName
and lastName
as pointer to an array of chars rather than pointer to char but the error persists . what am I missing ?! plz help...
仅供参考..我正在使用Ubuntu 14,正在使用gcc(Ubuntu 4.8.2-19ubuntu1)...
FYI .. I'm working on Ubuntu 14 and I'm using gcc (Ubuntu 4.8.2-19ubuntu1)...
推荐答案
您正在为myName.firstName
和hisName.firstName
分配指向字符串文字的指针.字符串文字无法修改,这就是导致您出错的原因.
You are assigning myName.firstName
and hisName.firstName
with pointers to string literals. String literals cannot be modified, which is what's causing your error.
要实现所需的功能,可以将firstName
声明为char
数组,也可以为其分配内存(作为char
指针).
To achieve what you want, you can either declare firstName
as a char
array, or allocate memory to it (as a char
pointer).
数组方法:
typedef struct fullName
{
char firstName[256]; // a sufficiently large number
char lastName[256];
} NAME;
int main()
{
NAME myName, hisName;
strcpy(myName.firstName, "aaaaaaa"); // You can't assign a string directly
strcpy(hisName.firstName, "bbbbbb");
memcpy(myName.firstName, hisName.firstName, sizeof(hisName.firstName));
printf("myName.firstName = %s\n", myName.firstName);
printf("hisName.firstName = %s\n", hisName.firstName);
}
分配方法:
typedef struct fullName
{
char* firstName;
char* lastName;
} NAME;
int main()
{
NAME myName, hisName;
size_t buffersize = 256; // a sufficiently large number
myName.firstName = malloc(buffersize);
hisName.firstName = malloc(buffersize); // same for lastName
strcpy(myName.firstName, "aaaaaaa");
strcpy(hisName.firstName, "bbbbbb");
memcpy(myName.firstName, hisName.firstName, buffersize); // You can't use sizeof() as this will give the size of a pointer
printf("myName.firstName = %s\n", myName.firstName);
printf("hisName.firstName = %s\n", hisName.firstName);
}
这篇关于memcpy错误:分段错误(核心已转储)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!