[英]Error: segmentation code dump fault in c programming
以下代碼顯示了代碼轉儲分段錯誤,有人可以幫我解決它以使代碼順利運行嗎
#include<stdio.h>
int n,m,p;
int** send(int (*a)[m],int (*b)[p] )
{
int **c;
for(int i=0;i<n;i++)
{
for(int j=0;j<p;j++)
{c[i][j]=0;
for(int k=0;k<m;k++)
c[i][j]+=a[i][k]*b[k][j];
}
}
return c;
}
int main()
{
printf("Enter the number of rows for the first matrix:");
scanf("%d",&n);
printf("Enter the number of columns for the first matrix/the number of rows for the second matrix:");
scanf("%d",&m);
printf("Enter the number of columns for the second matrix:");
scanf("%d",&p);
int a[n][m],b[m][p];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
printf("Enter value for a[%d][%d]:",i,j);
scanf("%d",&a[i][j]);
}
}
for(int i=0;i<m;i++)
{
for(int j=0;j<p;j++)
{
printf("Enter value for b[%d][%d]:",i,j);
scanf("%d",&b[i][j]);
}
}
int** (ptr)(int()[m],int(*)[p])=send;
int**c=ptr(a,b);
printf("The multiplication matrix is:\n");
for(int i=0;i<n;i++)
{
for(int j=0;j<p;j++)
printf("%d ",c[i][j]);
printf("\n");
}
return 0;
}
以下c程序代碼顯示了代碼轉儲-分段錯誤,誰能幫我解決以下錯誤以使代碼順利運行
我不會使用 VLA 所以我改變了它。 我沒有,但你不要忘記釋放。 正如@TomKarzes 所說,您忘記在發送函數中為 c 分配位置。
#include<stdio.h>
#include <malloc.h>
int n,m,p;
int** send(int **a,int **b ) //used pointers as inputs
{
int **c;
c = malloc(sizeof (int *) * n);
for (int i = 0; i < n; ++i) {
c[i] = malloc(sizeof (int ) * p);
}
for(int i=0;i<n;i++)
{
for(int j=0;j<p;j++)
{
c[i][j]=0;
for(int k=0;k<m;k++)
c[i][j]+=a[i][k]*b[k][j];
}
}
return c;
}
int main()
{
printf("Enter the number of rows for the first matrix:");
scanf("%d",&n);
printf("Enter the number of columns for the first matrix/the number of rows for the second matrix:");
scanf("%d",&m);
printf("Enter the number of columns for the second matrix:");
scanf("%d",&p);
int **a, **b; //changed them to pointers as well
//allocation
a = malloc(sizeof (int*) * n);
for(int i = 0 ; i < n ; i++){
a[i] = malloc(sizeof (int) * m);
}
b = malloc(sizeof (int *) * m);
for (int i = 0; i < m; ++i) {
b[i] = malloc(sizeof (int) * p);
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
printf("Enter value for a[%d][%d]:",i,j);
scanf("%d",&a[i][j]);
}
}
for(int i=0;i<m;i++)
{
for(int j=0;j<p;j++)
{
printf("Enter value for b[%d][%d]:",i,j);
scanf("%d", &b[i][j]);
}
}
//int** (ptr)(int()[m],int(*)[p])=send;
int**c=send(a,b);
printf("The multiplication matrix is:\n");
for(int i=0;i<n;i++)
{
for(int j=0;j<p;j++)
printf("%d ",c[i][j]);
printf("\n");
}
return 0;
}
它適用於 3x3 3x3 矩陣乘法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.