【发布时间】:2014-04-24 15:33:27
【问题描述】:
我写了一个返回分段错误错误的代码。代码很长,但我将其基本部分编写如下。请注意,主函数内定义的函数的所有变量都已定义,我测试了代码广告,它没有进入 Function_1。这就是我认为问题出在声明之类的原因
typedef struct node_type
{
int data;
struct node_type *next;
} node;
typedef node *list;
void Function_1(list R, int *Matrix, int Length, int A);
int main()
{
int S = 5;
int A = 1;
int Mat1[5];
//int *Mat = malloc(S*sizeof(int));
int *Mat = &Mat1[0];
printf("Enter the Matrix with length of 10:\n");
for (int i = 0; i < S; i++)
{
scanf("%i", &(*(Mat+i)));
}
list head;
head = (list)malloc(sizeof(node));
head->next = NULL;
for (int i = 0; i < S; i++)
{
printf("%d\t", *(Mat+i));
}
//printf("\nEnter the Array = \n");
//scanf("\n%d", &A);
printf("\nA = %i", A);
Function_1(head, Mat, S, A);
while (head != NULL)
{
printf("%d\t", head->data);
head = head->next;
}
return 0;
}
void Function_1(list R, int *Matrix, int Length, int A)
{
printf("11111");
list tail;
tail = R;
int Counter = 0;
int i = 0;
while (tail != NULL)
{
if (*(Matrix+i) == A)
{
Counter++;
tail->next = (list)malloc(sizeof(node));
tail->next->data = i;
tail->next->next = NULL;
tail = tail->next;
}
i++;
}
R->data = Counter;
printf("%d", Counter);
}
谢谢
【问题讨论】:
-
我很难从您提供的代码中找到段错误。也许您可以发布一个小(完整)程序来演示段错误?
-
那么,为什么要将矩阵作为指针发送?您是否尝试更新 Function_1 中存储单元中的数据?如果是这样,那你为什么不直接做 Function_1(head, &Mat1, S, A);?您是否还在函数中正确引用了 Mat 的数据?您还需要通过引用发送链接列表的头部。您还应该通过引用传递头部。
-
正如我所说,直到调用 Function_1 之前,它都被完美编译。我认为问题在于该函数参数的一种声明。我检查了所有这些,但我不知道问题出在哪里。
-
你能把整个代码上传到某个地方吗?您也可以在您的问题中添加一份副本。我有几个猜测,但我不想从我的猜测中给出答案。可能其他人也不想这样做。
-
在您调用 Function_1 之前,让我们查看所有代码。
标签: c linked-list segmentation-fault declaration