返回c语言中的多维指针

  • 本文关键字:指针 语言 返回
  • 更新时间 :
  • 英文 :


错误左值作为赋值的左操作数返回这个程序的错误是什么?

int(*matrix)[row][col];
int i = 0;
if(n == 1)
{
    for (int i = 0; i < no_matrices; i++)
    {
        printf("Matrix %d", i + 1);
        (matrix + i) = GetMatrixU(row, col); // (error here)
    }
}
int* GetMatrixU(int row, int col)
    srand(time(NULL));
    int(* matrix)[col] = malloc(col*sizeof(int));
    for (int i = 0; i < row; i ++)
    {
        for (int j = 0; j < col; j ++)
        {
            matrix[i][j] = rand()%100;
        }
    }
    return matrix[];
}

问题出在这一行:

(matrix + i) = GetMatrixU(row, col);

这将尝试进行赋值。对右边的表达式求值;这是"r值"("r"代表"右")。然后将结果赋值给左侧的表达式,即"l值"("l"代表"left")。

好,(matrix + i)不是一个有效的l值。matrix本身是一个指向二维数组的单指针。在C语言中,你不能只是指定一个指针值然后赋值;必须使用*操作符数组解引用,并通过该操作符进行赋值。

下面是一个简短的代码示例,演示了如何解引用指针,然后重复错误。

main()
{
    int a[10];
    *(a + 1) = 0;  // proper use of * to dereference
    a + 1 = 0; // will not compile; error is "l-value required"
}

但是在C语言中,有一种快捷方式可以对指针进行添加,然后对其进行解引用。它使用方括号和索引值:

a[1] = 0;  // index the array

在C中,根据定义,表达式*(a + i)a[i]的意思完全相同。

http://en.wikipedia.org/wiki/C_syntax Accessing_elements

看起来你正在尝试创建一个随机矩阵,一次一行。你要为每一行分配内存。你的基本矩阵声明应该是一个指向行指针的数组。

int *matrix[rows];
for (i = 0; i < rows; ++i)
{
    // either of these lines will work; pick just one
    *(matrix + i) = AllocateRandomRow(cols);  // explicit add-and-dereference
    matrix[i] = AllocateRandomRow(cols);  // simpler: just index array
}

我倾向于用第二种更简单的语法来解决这个问题。你正在索引一个数组;请使用方括号。

这是一个免费的在线文本,描述如何动态分配矩阵。

http://www.eskimo.com/scs/cclass/int/sx9b.html

这里有一个简单的例子来理解这个更复杂的情况:

int b = 4;
int *a = &b; // Allowed and works because a is a pointer to an integer
a+1 = 5; // Not allowed no idea about the type of a+1 and it could be used!!

为什么这和你的问题有关?

int(*matrix)[5][5];
printf("%pn",matrix);
printf("%pn",matrix+1);

0xb7753000
0xb7753064

以上指针之差为6*16 + 4 = 100。这个数字就是row*col*sizeOf(int) = 5*5*4 = 100

因此,你想做的是访问矩阵中的单元格,然而你实际上在做的是试图访问一个你不允许使用的内存,就像在第一个简单的例子中。

你实际在做什么和你想让程序做什么的例子:

int(*matrix)[5][5];
matrix + 0 => address of matrix
matrix + 1 => address of matrix + 100 bytes (you expected + 4 bytes instead)
matrix + 2 => address of matrix + 200 bytes (you expected + 8 bytes instead)
etc...

最新更新