[英]Error in the program with structures -segmentation fault
#include <stdio.h>
struct p
{
char *name;
struct p *next;
};
struct p *ptrary[10];
int main()
{
struct p p, q;
p.name = "xyz";
p.next = NULL;
ptrary[0] = &p;
strcpy(q.name, p.name);
ptrary[1] = &q;
printf("%s\n", ptrary[1]->name);
return 0;
}
The program is giving segmention fault on execution. 该程序在执行时出现分段错误。 What is wrong here? 怎么了 Do I need to allocate memory for ptrary? 我是否需要为记忆分配内存?
You will have to allocate some memory before using it. 使用前,您必须分配一些内存。
q.name = malloc(10);
strcpy(q.name, p.name);
Edit: As correctly pointer out by unwind, sizeof
char
will be always 1. Hence removing from malloc
. 编辑:作为正确的指针,通过unwind, sizeof
char
将始终为1。因此从malloc
删除。
You need to allocate room for the string, before using strcpy()
. 在使用strcpy()
之前,您需要为字符串分配空间。 You're trying to copy a new string into memory that is holding a string initialized from a string literal, which is totally invalid. 您正在尝试将新字符串复制到内存中,该内存中包含从字符串文字初始化的字符串,这完全无效。 Such strings should be considered read-only. 此类字符串应被视为只读。
You can avoid this problem by copying the pointer, which will then copy the string created by the string literal: 您可以通过复制指针来避免此问题,该指针随后将复制由字符串文字创建的字符串:
q.name = p.name;
struct p
{
char *name; //name points nowhere
struct p *next;
};
strcpy(q.name, p.name); // q.name is any arbitrary value
Allocate memory for name
before using it. 在使用内存之前,先为其分配name
。
OR declare as: 或声明为:
struct p
{
char name[4]; //the number of characters you require
struct p *next;
};
#include <stdio.h>
struct p
{
char name[10];
struct p *next;
};
struct p *ptrary[10];
int main()
{
struct p p, q;
strcpy(p.name , "xyz");
p.next = NULL;
ptrary[0] = &p;
strcpy(q.name, p.name);
ptrary[1] = &q;
printf("%s\n", ptrary[1]->name);
return 0;
}
or you can use p.name = malloc(sizeof(char)*10);
或者您可以使用p.name = malloc(sizeof(char)*10);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.