该程序的任务是使用memcpy
将结构中的所有数据压入堆栈。
执行时,它成功地将数据输入到结构中,但在执行 push()
函数时遇到了段错误。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <mem.h>
typedef struct STD {
char ime [50];
int fn;
float usp;
} STD;
typedef struct STACK {
STD *s;
STACK *next;
} STACK;
int push (void *a, int siz, STACK **sst) {
STACK *snew;
snew = (STACK *) malloc (siz + 1);
memcpy (snew->s, a, siz);
snew -> next = *sst;
*sst = snew;
}
int main () {
STACK *st;
STD ss;
printf ("Vyvedi ime");
gets (ss.ime);
ss.ime[49] = 0;
printf ("Vyvedi fn");
scanf ("%d", &ss.fn);
printf ("Vyvedi usp");
scanf ("%f", &ss.usp);
push (&ss, sizeof(ss) , &st);
system ("pause"); }
不知道是否重要,我使用 DevC 作为编译器。
最佳答案
这段代码是错误的:
STACK *snew;
snew = (STACK *) malloc (siz + 1);
memcpy (snew->s, a, siz);
snew->s
在您memcpy a
时未初始化。我希望看到两个 malloc
- 一个用于 STACK*
,另一个用于 STD*
,然后您将使用它们来播种 snew->s
在将内容复制到其中之前。
STACK *snew;
snew = (STACK *) malloc (sizeof(STACK));
snew->s = (STD*) malloc(sizeof(STD));
memcpy (snew->s, a, siz);
或者,您可以使用单个 malloc
,并将 snew->s
指向其中适当的偏移量(在为 STACK 留出空间之后结构
).
STACK *snew;
snew = (STACK *) malloc (sizeof(STACK) + siz + 1);
snew->s = (char*)snew + sizeof(STACK);
memcpy (snew->s, a, siz);
push
函数中的siz
参数似乎是多余的,因为您总是传入一个struct STD
。
关于c - 将数据从结构体插入 C 中的堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4338701/