简体   繁体   English

使用 C 中的指针进行矩阵加法

[英]matrix addition using pointers in C

Write a program to add 2 m*n matrices using just pointer referencing/dereferencing.编写一个程序,仅使用指针引用/解引用来添加 2 m*n 矩阵。 That is, no array use allowed.也就是说,不允许使用数组。 my code is as:我的代码如下:

#include<stdio.h>
int main()
{
    int row,col;
    scanf("%d %d",&row,&col);
    int* ptr1;
    int* ptr2 = ptr1 + (row*col);/*if ptr1+(row*col) is not there then runtime error is given*/
    int* ptr3 = ptr2 + (row*col);
    for(int i=1;i<=(row*col);i++)
    {
        scanf("%d",(ptr1+i));
    }
    for(int i=1;i<=(row*col);i++)
    {
        scanf("%d",(ptr2+i));
        *(ptr3+i)=(*(ptr1+i) + *(ptr2+i));
    }
    for(int i=1;i<=(row*col);i++)
    {
        printf("%d ",(*(ptr3+i)));
        if(i%col == 0) printf("\n");
    }
    return 0;
}

problem is that it works fine for upto 3*3 matrices and after that it gives runtime error.问题是它适用于最多 3*3 的矩阵,之后它会给出运行时错误。

  1. You need to allocate space for your arrays on the heap using malloc or similar:您需要使用malloc或类似方法在堆上为您的 arrays 分配空间:
#include <stdlib.h>
...
    int* ptr1 = malloc(3 * (row*col) * sizeof(int));
...
  1. Your loops should start at 0 and end at (row*col)-1 .您的循环应该从0开始并在(row*col)-1结束。
...
    for(int i=0;i<=(row*col)-1;i++)
...

... or more conventionally: ...或更传统的:

...
    for(int i=0;i<(row*col);i++)
...

for example, ptr1 point to the offset 0 of the memory system as below, the matrix size if 2x2 .例如ptr1指向 memory 系统的偏移量0如下,矩阵大小为2x2

----- ----- ----- ----- ----- ----- --------------------
|    |     |     |     |     |      |
----- -----  ----- ----- ----- ----- -------------------
0                      16
^                       ^
|                       |
ptr1                   ptr2
<--readable/writable---><--------read-only/write-only---

In this case, you can dereference the pointer to read and write value from offset 0 to 16 .在这种情况下,您可以取消引用从偏移量016读取和写入值的指针。 But the problem is when you try to modify the value from the offset 16 that is pointed by ptr2 , those address is read-only or write-only, so the system does not accept you to read or write respectively.但问题是当您尝试修改ptr2指向的偏移量16的值时,这些地址是只读或只写的,因此系统不接受您分别读取或写入。

So you have to allocate for ptr1 AT LEAST 3*(row*col)*sizeof(int) (from ptr1 to ptr3+row*col ).所以你必须为ptr1分配至少3*(row*col)*sizeof(int) (从ptr1ptr3+row*col )。

int* ptr1 = malloc(3 * (row*col) * sizeof(int));
if(!ptr1) { // handle the error, because if you cannot allocate the memory, you do not need to do the rest of code.
   return -1; 
}

if you want to do:如果你想做:

    for(int i=1;i<=(row*col);i++)
    {
        printf("%d ",(*(ptr3+i)));
        if(i%col == 0) printf("\n");
    }

You have allocate (3*row*col+1)*sizeof(int) or you can change the iterator of the for loop from 0 to row*col-1 (i recommend this option):你已经 allocate (3*row*col+1)*sizeof(int)或者你可以将for循环的迭代器从0更改为row*col-1 (我推荐这个选项):

    for(int i=0;i< (row*col);i++)
    {
        printf("%d ",(*(ptr3+i)));
        if(i%col == 0) printf("\n");
    }

Do not forget to free(ptr1) at the end of your program.不要忘记在程序结束时free(ptr1)

  1. Where are the matrices defined?矩阵在哪里定义? Why do you write:你为什么写:
 int row,col;
 scanf("%d %d",&row,&col);
 int* ptr1;  /* <<<WERE DO YOU INITIALIZE THIS ****POINTER**** ???>>> */
 int* ptr2 = ptr1 + (row*col);/*if ptr1+(row*col) is not there then runtime error is given*/  /* <<<BUT YOU ARE USING ITS VALUE HERE !!! >>> */
 int* ptr3 = ptr2 + (row*col);
  1. A pointer, in C, is not the same as any kind of array. C 中的指针与任何类型的数组都不相同。 They have uses that allow you to interchange their roles at some points, but when you dominate the field.它们的用途可以让你在某些时候交换他们的角色,但是当你统治这个领域时。 Until then, be aware that a pointer and an array are very different things .在那之前,请注意指针和数组是非常不同的东西

Pointer指针

As you have defined above, you have defined a pointer.正如您在上面定义的那样,您已经定义了一个指针。 A pointer holds the address of something in memory, and so, has only space for one address storage.指针保存 memory 中某物的地址,因此,只有一个地址存储空间。

Declaration of a pointer:指针声明:

int *reference;

Array大批

An array is an object that provides storage for a definite (at compilation time) number of elements, all of them of the same type.数组是一个 object,它为确定(在编译时)数量的元素提供存储,所有元素都是相同的类型。

Declaration of an array:数组声明:

int vector[100]; /* this is an array of 100 ints */

If you want your pointer to point to some of the elements of the array, you can assign it its address, with something like:如果您希望指针指向数组的某些元素,您可以为其分配地址,例如:

reference = &vector[53];

and you can access the element pointed to by reference with:您可以通过以下方式访问reference指向的元素:

printf("the 54th element of the array is %d\n", *reference);

or或者

printf("the 54th element of the array is %d\n", vector[53]);

(as the arrays are zero based, the first element is vector[0] , the second is vector[1] , etc.) (因为 arrays 是从零开始的,第一个元素是vector[0] ,第二个是vector[1]等)

  1. The notation *(array + i) is completely nasty.符号*(array + i)非常讨厌。 Nobody uses it, except to obscure the code.没有人使用它,除了掩盖代码。 The correct notation is array[i] , and you should avoid using pointer arithmetic until you have a clear idea of the differences between pointers and arrays.正确的表示法是array[i] ,在您清楚地了解指针和 arrays 之间的区别之前,您应该避免使用指针算术。

  2. You can use multidimensional arrays, with the following notation:您可以使用多维 arrays,具有以下符号:

    • To declare a bidimensional array, eg a 2 rows by three columns array, you use:要声明一个二维数组,例如 2 行乘三列数组,您可以使用:
int A[2][3];
* You can access its elements (remember, zero based) as `A[0][0]`...`A[0][2]`, `A[1][0]`...`A[1][2]` and stop... no more elements in your array.

Let's see how to initialize and add two such arrays:让我们看看如何初始化和添加两个这样的 arrays:


#include <stdio.h>

/* declaration and initialization of both matrices A and B */
double A[2][3] = { { 0.0, 1.3, 3.14 }, { 5.6, 4.2, 3.8 } },
       B[2][3] = { {53.0, 42.8, 90.0}, { 2.718, 3.16, 1.4142135} };

/* the following function prints a matrix (of 2 rows by 3 columns) of 
 * name 'name' */
void
print_matrix(char *name, double M[2][3])
{
    printf("Matrix %s:\n", name);
    int row, col;
    for (row = 0; row < 2; row = row + 1) {
        for (col = 0; col < 3; col = col + 1) {
            if (col > 0) printf("\t");
            printf("%8.4f", M[row][col]);
        }
        printf("\n");
    }
    printf("\n");
}

int main()
{
    /* lets print matrix A */
    print_matrix("A", A);
    print_matrix("B", B); /* ... and B */

    double C[2][3]; /* declaration of matrix C */
    int r, c; /* row and column, for the loops */

    /* let's sum all the elements */
    for (r = 0; r < 2; r = r + 1) {
        for (c = 0; c < 3; c = c + 1) {
            C[r][c] = A[r][c] + B[r][c];
        }
    }

    /* and print the results */
    print_matrix("C", C);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM