【发布时间】:2021-02-22 06:45:42
【问题描述】:
试图了解C中双指针的使用和内存分配。
下面是我的代码:-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
printf("Enter rows and columns respectively: -\n");
int rows, columns;
scanf("%d%d", &rows, &columns);
int **matrix;
matrix = calloc(rows, sizeof(int));
int i, j;
for(i = 0; i < rows; i++)
{
matrix[i] = calloc(columns, sizeof(int));
}
printf("Enter your elements\n");
for(i = 0; i < rows; i++)
{
for(j = 0; j < columns; j++)
{
scanf("%d", &matrix[i][j]);
}
}
printf("Your elements are: -\n");
for(i = 0; i < rows; i++)
{
for(j = 0; j < columns; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
free(matrix);
return 0;
}
得到Segmentation fault: 11后,我在网上搜索,发现不是这样写的:-
int **matrix;
matrix = calloc(rows, sizeof(int));
我应该写:-
int **matrix;
matrix = calloc(rows, sizeof(int*));
进行上述更改后,我的代码工作正常。
我的问题是:-
- sizeof(int) 和 sizeof(int *) 有什么区别?
- 他们不是都分配4个字节吗? (int 占用 4 个字节和 int* (注意的不过是一个指针)也占4个字节?
- 如果它们都分配相同的空间,那为什么我得到一个 第一种情况下的分段错误?
【问题讨论】:
-
指针并不总是 4 个字节。它们是 64 位二进制文件中的 8 个字节。只需打印出
sizeof(int *)亲自查看。
标签: c pointers matrix dynamic-memory-allocation sizeof