[英]How can i modify a matrix using pointers
我正在嘗試使用指針修改矩陣(將每個值乘以2),但是我的代碼無法正常工作。 我已經看到了使用malloc
函數的一些示例,但是我不確定在我的代碼中怎么需要它。
#include<stdio.h>
void changematrix(int **mm,int row, int column)
{
int i,j;
for( i = 0;i < row; i++)
{
for( j = 0; j < column; j++)
{
*(*(mm + i) + j) = 2* *(*(mm + i) + j);
}
}
}
int main()
{
int i,j;
int row, column;
printf("Type the number of row\n");
scanf("%d", &row);
printf("Type the number of columns\n");
scanf("%d",&column);
int mat[row][column];
printf("Now type the numbers\n");
for( i = 0; i < row; i++)
{
for( j = 0; j < column; j++)
{
scanf("%d", &mat[i][j]);
}
}
changematrix(&mat,row,column);
for( i = 0; i < row; i++)
{
for( j = 0; j < column; j++)
{
printf("%d ",mat[i][j]);
}
printf("\n");
}
}
嘗試這個
void changematrix(int row, int column, int (*mm)[column])
{
int i,j;
for( i = 0;i < row; i++)
{
for( j = 0; j < column; j++)
{
mm[i][j] = 2* mm[i][j];
}
}
}
函數調用應如下所示:
changematrix(row, column, mat);
這將使s和l指向數組arr的元素。 如果您只想要整數的值,那么替代方法是在main()中定義int變量,並將其地址傳遞給func()...
void func(int arr[], int** s, int** l, int n){
/* snip */
*l = &arr[n-1];
*s = &arr[0];
}
func(arr, &s, &l, size);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.