C語言動態申請一維數組
首先 添加
#include <stdio.h>
#include <stdlib.h>
int *a;
int N;
scanf("%d", &N);
a = (int *) malloc(N * sizeof(int));
....
free(a);
這樣就動態分配了數組a[N]。數組的長度N可輸入確定,也可用程序中的變量確定。但要注意程序結束后要用free()將其釋放,否則內存會泄漏。
驗證一下:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0;
int *a;
int N;
printf("Input array length: ");
scanf("%d", &N);
printf("\n");
a = (int *) malloc(N * sizeof(int));
for(i = 0; i < N; i++)
{
a[i] = i + 1;
printf("%-5d", a[i]);
if ((i + 1) % 10 == 0)
printf("\n");
}
free(a);
printf("\n");
return 0;
}
C語言動態申請二維數組
一、利用一個二級指針來實現
思路:二級指針的使用類似於二維數組名的使用
#include<stdio.h> #include<malloc.h> int main() { //5行2列的數組 int **p = (int **)malloc(sizeof(int *) * 5); for (int i = 0; i < 5; ++i) { p[i] = (int *)malloc(sizeof(int) * 2); } for (int i = 0; i < 5; ++i) { for (int j = 0; j < 2; ++j) { //輸出數組每個元素地址 printf("%p\n", &p[i][j]); } } for (int i = 0; i < 5; ++i) free(p[i]); free(p); return 0; }
二、利用數組指針來實現
數組指針和指針數組是不同的。數組指針是指針變量,其本質仍然是一個變量。指針數組其本質是一個數組,存放的元素類型是指針類型。
就算很了解它們之間的區別,時間長了,在定義的時候還是容易混淆。運算符的優先級也是很重要的。()> [] > *。牢記於心。
#include<stdio.h> #include<malloc.h> int main() { //申請一個5行2列的整型數組 int(*p)[2] = (int(*)[2])malloc(sizeof(int) * 5 * 2); for (int i = 0; i < 5; ++i) { for (int j = 0; j < 2; ++j) { //輸出數組每個元素地址 printf("%p\n", &p[i][j]); } } free(p); return 0; }
三、利用一維數組來模擬二維數組
#include<stdio.h>
#include<malloc.h>
int main()
{
int *p = (int *)malloc(sizeof(int) * 5 * 2);
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 2; ++j)
{
//輸出數組每個元素地址
printf("%p\n", &p[i*2+j]);
}
}
free(p);
return 0;
}