An example of C implementing an indefinite array
- 2020-06-07 04:57:01
- OfStack
When writing programs, we often need to define such an array, and the size of the array can only be known after the previous program runs. However, C language does not support the definition of indefinite array directly, but we can achieve an indefinite array through dynamic array.
1 dimensional array:
#include<stdio.h>
#include<stdlib.h>// In order to use malloc Is to include this header file
#include <memory.h>// In order to use memset Is to include this header file
int main()
{
int m;
scanf("%d", &m);//scanf It just ends when it hits a carriage return, and it doesn't enter a carriage return, so there's also a carriage return in the input stream 1 A carriage return
getchar();// Read the carriage return character in the input stream
int *p;
p = (int*)malloc(m*(sizeof(int)));// Dynamic memory request
memset(p, 0, m);// Initialize, each element is zero
int i;
for (i=0;i<m; i++)// Array assignment
{
p[i] = i;
}
for (i = 0; i <m; i++)// Print the array
{
printf("%d,", p[i]);
}
free(p);// Free memory
getchar();// Let the program pause so you can see the output
return 0;
}
2 dimensional indefinite array
#include <stdio.h>
#include <stdlib.h>// In order to use malloc Is to include this header file
#include <memory.h>// In order to use memset Is to include this header file
int main()
{
int m, n;
scanf("%d%d", &m,&n);//scanf It just ends when it hits a carriage return, and it doesn't enter a carriage return, so there's also a carriage return in the input stream 1 A carriage return
getchar();// Read the carriage return character in the input stream
int **p;
p = (int**)malloc(m*(sizeof(int*)));//2 The address where the level pointer resides applies to memory
int i, j;
for (i = 0; i<m; i++)
p[i] = (int*)malloc(sizeof(int)*n);//1 The address where the level pointer resides applies to memory
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
p[i][j] = i + j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d %p ", p[i][j], &p[i][j]); // The output of each element and address, the address between the columns of each row is continuous, the address between the rows is discontinuous
}
printf("\n");
}
for (i = 0; i < m; i++) free(p[i]);
free(p);
getchar();// Let the program pause so you can see the output
return 0;
}