我有一个很大的问题,我尝试了很多不同的方法来解决,但找不到解决方案。
我必须做的是:
- 创建一个引入 2 组的函数
- 显示这些集合的另一个函数
需要使用一个结构,其组件将是:
相应集合的元素个数;
一个指针(用于存储这两个集合的元素);
我不知道为什么,但是当我执行程序(如下所示)时,第一组的第二个元素没有显示。拜托,如果你有时间,你能帮我找到问题吗?当一切似乎都很好,但程序仍然无法运行时,这真的很令人沮丧。非常感谢!!!
在 header 我有:
#ifndef L8_3H_H_
#define L8_3H_H_
struct Set
{
unsigned int card;
double *p[2];
};
typedef struct Set MULTIME;
MULTIME *introduce_data();
void showSet(MULTIME *m, int j);
#endif /* L8_3H_H_ */
在 main 我有:
#include "L8_3h.h"
#include <stdio.h>
int main( void )
{
MULTIME *mult;
mult = introduce_data();
showSet(mult, 0);
showSet(mult, 1);
return 0;
}
我的职能是:
#include "L8_3h.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void showSet(MULTIME *m, int j)
{
int i;
if ( j == 0 )
{
printf("\nA = {");
}else
{
printf("\nB = {");
}
for (i = 0; i < (m + j)->card; ++i)
{
printf("%lf", *((m + j)->p[j]+i));
if (i != (m + j)->card - 1)
{
printf(", ");
}
}
printf("}");
}
MULTIME *introduce_data()
{
MULTIME *mult = (MULTIME*)malloc(sizeof(MULTIME));
int i, j;
for (i = 0; i < 2; ++i)
{
printf("\nIntroduce the number of elements of set %d", i + 1);
scanf("%u", &(mult + i)->card);
(mult+i)->p[i] = (double*)malloc(sizeof(double)*((mult+i)->card));
printf("\nIntroduce the element of set %d\n", i+1);
for (j = 0; j < (mult + i)->card; ++j)
{
scanf("%lf", ((mult + i)->p[i]+j));
//It's interesting that when I put a printf right after introducing the
//element everything is fine(I get the right element)
}
}
printf("\nHeres the problem");
printf("\nThis should not be zero: %lf", *((mult + 0)->p[0]+1));
return mult;
}
最佳答案
introduce_data()
中存在许多问题我可以快速看一下。
首先对malloc()
的返回值进行转换,如
MULTIME *mult = (MULTIME*)malloc(sizeof(MULTIME));
是不必要的。删除 (MULTIME *)
转换并确保有一个 #include <stdlib.h>
在你的代码的顶部。遗漏#include <stdlib.h>
并使用转换会导致您的代码具有未定义的行为。 (唯一的异常(exception)是如果您的 C 编译器实际上是 C++ 编译器 - 在这种情况下您需要 #include <stdlib.h>
和转换。否则不要使用转换。)
二、malloc()
in 为 mult
分配内存作为一个MULTIME
.然后循环使用 mult
好像它是两个 MULTIME
的数组.那从(动态分配的数组)的末尾掉下来。行为未定义。
第三,你弄错了数组语法和指针语法之间的映射。声明
(mult+i)->p[i] = (double*)malloc(sizeof(double)*((mult+i)->card));
在功能上等同于(删除类型转换)
mult[i].p[i] = malloc(sizeof(double)*(mult[i].card));
同理,声明
scanf("%lf", ((mult + i)->p[i]+j));
相当于
scanf("%lf", mult[i].p[i]+j);
这两者可能都不是您想要的。
潜在的问题是您没有正确理解指针如何与数组一起工作。您需要更仔细地阅读教科书。
关于c - 处理指针和结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29659246/