C 将值推送到结构时堆栈崩溃
嘿,伙计们,我正在学习c语言,目前正在研究堆栈、结构和指针。我用VisualStudio做我的程序,每当我输入我的输入,程序就会崩溃。我能够确定错误来自产品名称。我也很困惑,因为它包含指针字符。有人能指出我的错误吗?多谢各位 这是我的密码C 将值推送到结构时堆栈崩溃,c,C,嘿,伙计们,我正在学习c语言,目前正在研究堆栈、结构和指针。我用VisualStudio做我的程序,每当我输入我的输入,程序就会崩溃。我能够确定错误来自产品名称。我也很困惑,因为它包含指针字符。有人能指出我的错误吗?多谢各位 这是我的密码 #包括 #包括 #定义最大值10 int top=-1; 结构产品{ int-prodId; char*prodName; }; 结构产品arrP[MAX]; 结构产品pop(); 无效推送(int-id,char*name); int isFull(); i
#包括
#包括
#定义最大值10
int top=-1;
结构产品{
int-prodId;
char*prodName;
};
结构产品arrP[MAX];
结构产品pop();
无效推送(int-id,char*name);
int isFull();
int是空的();
结构产品pop()
{
结构产品温度;
温度=arrP[顶部];
顶部--;
返回温度;
}
无效推送(int-id,char*name)
{
top++;
arrP[top].prodId=id;
strcpy(arrP[top].prodName,名称);
}
int isFull()
{
如果(顶部==最大值)
返回1;
其他的
返回0;
}
int isEmpty()
{
如果(顶部==-1)
返回1;
其他的
返回0;
}
int main()
{
int-myID;
char*myName;
//推动价值
printf(“输入产品id:”);
scanf(“%d”、&myID);
printf(“输入产品名称:”);
scanf(“%s”、&myName);
推送(myID和myName);
printf(“%d%s”,arrP[top].prodId,arrP[top].prodName);
}
当您使用字符类型变量中的%s获取输入时,字符变量地址附近的内存会被覆盖,从而可能导致程序崩溃。如果要输入字符串,可以通过定义字符数组来尝试(如char my name[MAX],MAX可以是适合您的大小) 在使用-Wall
标志编译时,可以避免听到编译器警告的一些简单错误
情况1:-变量myId
假设为整数变量,而不是指针变量。如果希望它是指针变量,那么应该首先为它分配内存
int*myID代码>
printf(“输入产品id:”)代码>
scanf(“%d”和&myID)代码>
取代
int-myID代码>
printf(“输入产品id:”)代码>
scanf(“%d”和&myID)代码>
案例2:-变量myName
应该是一个字符数组,因为您要将产品名称存储在其中
charmyname代码>
printf(“输入产品名称:”)代码>
scanf(“%s”和&myName)代码>
取代
charmyname[50]代码>
printf(“输入产品名称:”)代码>
scanf(“%s”,myName)代码>
调用push()
函数时,只需传递myName
。例如
push(myID,myName)代码>
还有这个声明
strcpy(arrP[top].prodName,名称)代码>
由于prodName
是结构中的指针成员,因此应为此动态分配内存,然后执行复制
arrP[top].prodName=malloc(大小)代码>
strcpy(arrP[top].prodName,名称)代码>a)int*myID代码>==>int-myID代码>b)charmyname代码>==>charmyname[100]代码>c)scanf(“%s”和&myName)代码>==>scanf(“%99s”,myName)
您需要为prodName
指针分配空间。@4386427不工作…@500 InternalServerError我可以知道我该怎么做吗?请参阅achal的答案。一旦使用arrP[index]。prodName
不再需要,释放它以避免内存泄漏。使用valgrind
进行检查。
#include<stdio.h>
#include<string.h>
#define MAX 10
int top = -1;
struct Product {
int prodId;
char *prodName;
};
struct Product arrP[MAX];
struct Product pop();
void push(int id, char *name);
int isFull();
int isEmpty();
struct Product pop()
{
struct Product temp;
temp = arrP[top];
top--;
return temp;
}
void push(int id, char *name)
{
top++;
arrP[top].prodId = id;
strcpy(arrP[top].prodName,name);
}
int isFull()
{
if (top == MAX)
return 1;
else
return 0;
}
int isEmpty()
{
if (top == -1)
return 1;
else
return 0;
}
int main()
{
int myID;
char *myName;
//Push the value
printf("Enter the Product id: ");
scanf("%d", &myID);
printf("Enter the Product Name: ");
scanf("%s", &myName);
push(myID, &myName);
printf("%d %s", arrP[top].prodId ,arrP[top].prodName);
}