I would like to create a dynamic array which store permutation sequence, such that
order[0][]={1,2,3}
order[1][]={2,1,3}
order[2][]={2,3,1}
let say order[m][n], m = number of permutation, n = number of term, m and n are identified in real-time.
I did the below, and found that the pointer address is overlapping, resulting in incorrect value storage. How can do it correctly using dynamic array via double pointer?
void permute(int num_permute, int num_term, int** order) {
int x, y;
int term[5];
/* debug only */
for(y=num_term, x=0; y>0; y--, x++){
term[x] = y;
}
fprintf(stderr, "\n");
printf("order%12c", ' ');
for (x=0; x<num_permute; ++x) {
printf(" %-11d", x);
}
printf("\n");
for(y=0; y<num_permute; y++){
printf("%-5d%12p", y, (order+y));
memcpy(&(order[y]), term, sizeof(term));
for (x=0; x<num_term; x++)
printf(" %12p", order+y+x);
printf("\n");
}
}
int main(){
int y, z;
int** x;
x = (int*) malloc(5*5*sizeof(int*));
permute(5, 5, x);
printf("\n");
printf("x ");
for(z=0; z<5; z++){
printf(" %2d ", z);
}
printf("\n");
for(y=0; y<5; y++){
printf("%-4d", y);
for(z=0; z<5; z++){
printf(" %2d ", *(x+y+z));
}
printf("\n");
}
free(x);
return 0;
}
Result: order[0][1] and order[1][0] point to same address... and so do others. With rows as the major axis and columns the minor:
order 0 1 2 3 4
0 0x100100080 0x100100080 0x100100084 0x100100088 0x10010008c 0x100100090
1 0x100100084 0x100100084 0x100100088 0x10010008c 0x100100090 0x100100094
2 0x100100088 0x100100088 0x10010008c 0x100100090 0x100100094 0x100100098
3 0x10010008c 0x10010008c 0x100100090 0x100100094 0x100100098 0x10010009c
4 0x100100090 0x100100090 0x100100094 0x100100098 0x10010009c 0x1001000a0
x 0 1 2 3 4
0 5 5 5 5 5
1 5 5 5 5 4
2 5 5 5 4 3
3 5 5 4 3 2
4 5 4 3 2 1
Source Code:
The code will be something like:
#include <stdlib.h>
int **array;
array = malloc(nrows * sizeof(int *));
if(array == NULL)
{
fprintf(stderr, "out of memory\n");
/*exit or return*/
}
for(i = 0; i < nrows; i++)
{
array[i] = malloc(ncolumns * sizeof(int));
if(array[i] == NULL)
{
fprintf(stderr, "out of memory\n");
/*exit or return*/
}
}
Concept:
array is a pointer-to-pointer-to-int: at the first level, it points to a block of pointers, one for each row. That first-level pointer is the first one to be allocated; it has nrows elements, with each element big enough to hold a pointer-to-int, or int *. If the allocation is successful then fill in the pointers (all nrows of them) with a pointer (also obtained from malloc) to ncolumns number of ints, the storage for that row of the array.
Pictorial Depiction:
It is simple to grasp if you visualize the situation as:
Taking this into account, the sample code could be rewritten as:
void permute(int num_permute, int num_term, int** order) {
int x, y;
int term[5];
int* ptr = NULL;
for (y=num_term, x=0; y>0; y--, x++) {
term[x] = y;
}
printf("\n");
printf("order%12c", ' ');
for (x=0; x<num_permute; ++x) {
printf(" %2d ", x);
}
printf("\n");
for (y=0; y<num_permute; y++) {
ptr = order[y];
memcpy(ptr, term, sizeof(term));
printf("%-5d%12p", y, ptr);
for (x=0; x<num_term; x++) {
printf(" %2d ", ptr[x]);
}
printf("\n");
}
}
int main() {
int y, z;
int** x = NULL;
int num_term = 5;
int num_permutation = 5;
int* pchk = NULL;
x = (int**) malloc(num_permutation * sizeof(int*));
for (y=0; y<num_permutation; y++){
x[y] = (int*) malloc(num_term * sizeof(int));
printf("x[%d]: %p\n", y, x[y]);
}
permute(num_permutation, num_term, x);
printf("\nx: ");
for(z=0; z<5; z++){
printf(" %2d ", z);
}
printf("\n");
for(y=0; y<num_permutation; y++){
pchk = x[y];
printf("%-4d", y);
for(z=0; z<num_term; z++){
printf(" %2d ", pchk[z]);
}
printf("\n");
}
for (y=0; y<num_permutation; y++) {
free(x[y]);
}
free(x);
return 0;
}
The code sample only simulates a multidimensional array, and does it incorrectly. To see what's going wrong, start by considering what happens when you declare a multidimensional array:
int foo[3][5];
This allocates a contiguous region of memory of size 3*5*sizeof(int). In an expression such as foo[i], the foo is converted to a int [5] pointer, then the index operator is applied. In other words, foo[i] is equivalent to *( (int (*)[5])foo) + i). Each foo[i] would be considered as having size 5*sizeof(int).
x,y: 0,0 0,1 0,2 0,3 0,4 1,0
foo --> | 1 | 2 | 3 | 4 | 5 | 1 |...
<- 5 * sizeof(int) ->
When you create x in the sample code, you're replicating this type of multidimensional array. The index expression you're using (*(order + y + x)) is thus wrong, as it doesn't properly handle the size of order[y]: order + 1 + 0 == order + 0 + 1, which is the problem you're seeing in the sample output.
The correct expressions are: (order + num_term * y) for the yth permutation and *(order + num_term * y + x) for element order[y][x].
This suggests another class of error in the sample. For this kind of simulated multidimensional array, the array types are actually pointers to single dimensional arrays. The declared types of x and order should be int*, not int**. This should be reinforced by the type warnings the sample code should generate:
when allocating space for x, the type of the pointer (int*) doesn't match the type of x
when printing the elements of x, the type of *(x+y+z) doesn't match the format "%d".
However, while simulating a multidimensional array saves space, it's more error prone when used (unless you write a function to handle indexing). A solution such as Als' may be safer, as you can use the standard indexing operator.
Emulating a 2D array with pointer arrays is a complete overkill if you have C99 (or C11). Just use
void permute(size_t num_permute, size_t num_term, unsigned order[][num_term]);
as your function signature and allocate your matrix in main with something like
unsigned (*order)[m] = malloc(sizeof(unsigned[n][m]));
Also, as you can see in the examples above, I'd suggest that you use the semantically correct types. Sizes are always best served with size_t and your permutation values look to me as if they will never be negative. Maybe for these you also should start counting from 0.
The following code snippet creates a 2d matrix for a given row and column. Please use this as a reference to debug your program.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int row, column;
int **matrix;
int i, j, val;
printf("Enter rows: ");
scanf("%d", &row);
printf("Enter columns: ");
scanf("%d", &column);
matrix = (int **) malloc (sizeof(int *) * row);
if (matrix == NULL) {
printf("ERROR: unable to allocate memory \n");
return -1;
}
for (i=0 ; i<row ; i++)
matrix[i] = (int *) malloc (sizeof(int) * column);
val=1;
for (i=0 ; i<row ; i++) {
for (j=0 ; j<column; j++) {
matrix[i][j] = val++;
}
}
for (i=0 ; i<row ; i++) {
for (j=0 ; j<column; j++) {
printf("%3d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
/*
Allocation of 2d matrix with only one call to malloc and
still get to access the matrix with a[i][j] format
the matrix is divided into headers and data.
headers = metadata to store the rows
data = actual data storage - buffer
allocate one contigious memory for header and data
and then make the elements in the header to point to the data are
<- headers -----><----------- data -----------
-----------------------------------------------------------------
| | | | | | .. |
| | | | | | .. |
-----------------------------------------------------------------
| ^
| |
|-----------------|
header points to data area
*/
/*
Output:
$ gcc 2darray.c
$ ./a.out
Enter rows: 10
Enter columns: 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
$
*/
Related
I have the code below that can produce
[p18d541#csci112 program1]$ ./main 17 < inp17.txt
12 25 110 168
35 64 113 134
91 158 183 217
102 129 130 146
26 116 215 223
0 78 81 162
19 25 204 222
124 138 157 245
137 183 201 249
61 67 106 236
60 71 106 236
63 81 106 240
14 27 111 168
17 27 111 168
26 116 215 220
111 137 202 249
111 137 202 246
from an input of
168.12.110.25
64.113.134.35
217.158.91.183
102.130.129.146
215.116.26.223
81.162.78.0
19.204.25.222
245.124.138.157
137.249.183.201
106.61.236.67
106.71.236.60
106.81.240.63
168.14.111.27
168.17.111.27
215.116.26.220
137.249.111.202
137.246.111.202
so my code scans in the input stores the values in network
and then I need to arrange them by the column from least to greatest starting at the first number and working its way to the right. an example of a the first few would be
0 78 81 162
12 25 110 168
14 27 111 168
.
.
.
111 137 202 246
111 137 202 249
.
.
.
.
//declare libraries
#include <stdio.h>
#include <stdlib.h>
//declare other functions/files to be used in the program
void print_fun(void);
int sort_fun(int arg, unsigned char networks[arg][4]);
void read_fun(void);
//read command line input and store the information
int main(int argc, char** argv){
//declar variable
int arg = 0;
//make argv into an int
arg = atoi(argv[1]);
//assign size to networks
unsigned char networks[arg][4];
//assign input to networks
for (int j =0; j<1; ++j){
if(argc == 1)
{
printf("ERROR ERROR, you messed up\n");
}
else
{
// hold network addresses in a 2-d array, with 4 nsigned char
for(int k = 0; k<arg; k++){
for (int i =0; i<4; i++){
scanf("%hhu.", &networks[k][i]);
//checks to see if scanf was working roperly
// printf(" %hhu",networks[k][i]);
}
//printf("\n");
}}}
sort_fun(arg, networks);
//sort array
//count networks
//print info about the array
return(0);
}
int sort_fun(int arg, unsigned char networks[arg][4]){
//declaring variabes
//sorting by comlumn p
for (int k = 0; k < arg; k++){
for( int i = 0; i < 4; i++){
for (int j = i+1; j<4; ++j){
if (networks[k][i] > networks[k][j]) {
int swap = networks[k][i];
networks[k][i] = networks[k][j];
networks[k][j] = swap;
}
}
}
}
for (int i =0; i<arg; i++){
for (int j =0; j < 4; j++){
printf(" %hhu", networks[i][j]);
}
printf("\n");
}
return(0);
}
I have tried switching around the variables in my for loop and messing with the values, but I cannot seem to figure out how to change my code to work in columns instead of rows.
and by the way each value is stored in a separate array element but they need to stick together like in the input, so when one number moves the whole line moves with it. please let me know what you think. thank you.
I have the code below that can produce
[p18d541#csci112 program1]$ ./main 17 < inp17.txt
12 25 110 168
35 64 113 134
91 158 183 217
102 129 130 146
26 116 215 223
0 78 81 162
19 25 204 222
124 138 157 245
137 183 201 249
61 67 106 236
60 71 106 236
63 81 106 240
14 27 111 168
17 27 111 168
26 116 215 220
111 137 202 249
111 137 202 246
from an input of
168.12.110.25
64.113.134.35
217.158.91.183
102.130.129.146
215.116.26.223
81.162.78.0
19.204.25.222
245.124.138.157
137.249.183.201
106.61.236.67
106.71.236.60
106.81.240.63
168.14.111.27
168.17.111.27
215.116.26.220
137.249.111.202
137.246.111.202
so my code scans in the input stores the values in network
and then I need to arrange them by the column from least to greatest starting at the first number and working its way to the right. an example of a the first few would be
0 78 81 162
12 25 110 168
14 27 111 168
.
.
.
111 137 202 246
111 137 202 249
.
.
.
.
//declare libraries
#include <stdio.h>
#include <stdlib.h>
//declare other functions/files to be used in the program
void print_fun(void);
int sort_fun(int arg, unsigned char networks[arg][4]);
void read_fun(void);
//read command line input and store the information
int main(int argc, char** argv){
//declar variable
int arg = 0;
//make argv into an int
arg = atoi(argv[1]);
//assign size to networks
unsigned char networks[arg][4];
//assign input to networks
for (int j =0; j<1; ++j){
if(argc == 1)
{
printf("ERROR ERROR, you messed up\n");
}
else
{
// hold network addresses in a 2-d array, with 4 nsigned char
for(int k = 0; k<arg; k++){
for (int i =0; i<4; i++){
scanf("%hhu.", &networks[k][i]);
//checks to see if scanf was working roperly
// printf(" %hhu",networks[k][i]);
}
//printf("\n");
}}}
sort_fun(arg, networks);
//sort array
//count networks
//print info about the array
return(0);
}
int sort_fun(int arg, unsigned char networks[arg][4]){
//declaring variabes
//sorting by comlumn p
for (int k = 0; k < arg; k++){
for( int i = 0; i < 4; i++){
for (int j = i+1; j<4; ++j){
if (networks[k][i] > networks[k][j]) {
int swap = networks[k][i];
networks[k][i] = networks[k][j];
networks[k][j] = swap;
}
}
}
}
for (int i =0; i<arg; i++){
for (int j =0; j < 4; j++){
printf(" %hhu", networks[i][j]);
}
printf("\n");
}
return(0);
}
I have tried switching around the variables in my for loop and messing with the values, but I cannot seem to figure out how to change my code to work in columns instead of rows.
and by the way each value is stored in a separate array element but they need to stick together like in the input, so when one number moves the whole line moves with it. please let me know what you think. thank you.
So this is my code for printing pascal triangle using 2d arrays but its not giving me the desired output and I cannot determine what's wrong with the logic/code.
#include <stdio.h>
int main()
{
int num, rows, col, k;
printf("Enter the number of rows of pascal triangle you want:");
scanf("%d", &num);
long a[100][100];
for (rows = 0; rows < num; rows++)
{
for (col = 0; col < (num - rows - 1); col++)
printf(" ");
for (k = 0; k <= rows; k++)
{
if (k == 0 || k == rows)
{
a[rows][k] = 1;
printf("%ld", a[rows][k]);
}
else
a[rows][k] = (a[rows - 1][k - 1]) + (a[rows - 1][k]);
printf("%ld", a[rows][k]);
}
printf("\n");
}
return 0;
}
You don't have curly braces around the statements after the else, so it looks like you'll double-printf() when the condition of the if-statement is true.
I copied the source into codechef.com/ide and changed the io for num to be just assigned to 6 which produced the following output:
Enter the number of rows of pascal triangle you want:
11
1111
11211
113311
1146411
1151010511
It looks like your close, but you want 1, 11, 121, 1331 etc right?
Wraping the else case produced the following output:
if (k == 0 || k == rows)
{
a[rows][k] = 1;
printf("(%ld)", a[rows][k]);
}
else{// START OF BLOCK HERE
a[rows][k] = (a[rows - 1][k - 1]) + (a[rows - 1][k]);
printf("(%ld)", a[rows][k]);
}//END OF BLOCK HERE, NOTE THAT IT INCLUDES THE PRINT IN THE ELSE CASE NOW
OUTPUT:
Enter the number of rows of pascal triangle you want:
(1)
(1)(1)
(1)(2)(1)
(1)(3)(3)(1)
(1)(4)(6)(4)(1)
(1)(5)(10)(10)(5)(1)
But i added () to make it clearer to me. I also added a "/n" to the end of the first printf that asks for the value of num, so that the first line is on a new line.
printf("Enter the number of rows of pascal triangle you want:\n");
You can do that without using any arrays:
#include <stdlib.h>
#include <stdio.h>
int num_digits(int number)
{
int digits = 0;
while (number) {
number /= 10;
++digits;
}
return digits;
}
unsigned max_pascal_value(int row)
{
int result = 1;
for (int num = row, denom = 1; num > denom; --num, ++denom)
result = (int)(result * (double)num / denom );
return result;
}
int main()
{
printf("Enter the number of rows of pascals triangle you want: ");
int rows;
if (scanf("%d", &rows) != 1) {
fputs("Input error. Expected an integer :(\n\n", stderr);
return EXIT_FAILURE;
}
int max_digits = num_digits(max_pascal_value(rows));
for (int i = 0; i <= rows; ++i) {
for (int k = 0; k < (rows - i) * max_digits / 2; ++k)
putchar(' ');
int previous = 1;
printf("%*i ", max_digits, previous);
for (int num = i, denom = 1; num; --num, ++denom) {
previous = (int)(previous * (double)num / denom );
printf("%*i ", max_digits, previous);
}
putchar('\n');
}
}
Output:
Enter the number of rows of pascals triangle you want: 15
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
I am trying to delete first 20 columns from each of the slices of my 3D dynamic array. I guessed trying to write a function for 2D dynamic array would solve the problem which I would iterate over each of the levels of 3D array. I got an example in stackoverflow which I am trying to make work.
But the problem is the function can not delete the whole column. Instead it only delete one element. Can anyone give me idea how to delete whole column from a 2D dynamic array?
void removeColumn(int** matrix, int col){
MATRIX_WIDTH--;
for(int i=0;i<MATRIX_HEIGHT; i++) {
while(col<MATRIX_WIDTH)
{
//move data to the left
matrix[i][col]=matrix[i][col+1];
col++;
} matrix[i] = realloc(matrix[i], sizeof(double)*MATRIX_WIDHT); }
My expected ouput is like
Sample input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
sample output:
1 3 4
5 7 8
9 11 12
13 15 16
Update: here is the code which delete the column completely after using #frslm advice
but matrix is not resizing.
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int** fill(size_t rows, size_t cols, int input[][cols])
{
int i,j,count=1;
int** result;
result = malloc((rows)*sizeof(int*));
for(i=0;i<rows;i++)
{
result[i]=malloc(cols*sizeof(int));
for(j=0;j<cols;j++)
{
result[i][j]=count++;
}
}
return result;
}
void printArray2D(size_t rows, size_t cols,int** input)
{
int i,j;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf(" %4d",input[i][j]);
}
printf("\n");
}
}
void removeColumn(int** matrix, int col2del , int rows, int cols){
int MATRIX_WIDTH = cols;
int MATRIX_HEIGHT = rows;
MATRIX_WIDTH--;
for(int i=0;i<MATRIX_HEIGHT; i++) {
int curr_col = col2del;
while(curr_col<MATRIX_WIDTH)
{
//move data to the left
matrix[i][curr_col]=matrix[i][curr_col+1];
curr_col++;
}
//matrix[i] = realloc(matrix[i], sizeof(int)*MATRIX_WIDTH); // <- int, not double
matrix[i] = realloc(matrix[i], sizeof (matrix[i][0])*MATRIX_WIDTH);
}
}
int main()
{
int arRow,arCol;
arRow =8;
arCol = 9;
int ar[arRow][arCol];
int **filled;
filled = fill(arRow, arCol, ar);
printArray2D(arRow,arCol,filled);
removeColumn(filled, 3,arRow,arCol);
printf("After 3rd Column Delete.......\n");
printArray2D(arRow,arCol,filled);
return(0);
}
Output: last column duplicates
1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18
19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63
64 65 66 67 68 69 70 71 72
After 3rd Column Delete.......
1 2 3 5 6 7 8 9 9
10 11 12 14 15 16 17 18 18
19 20 21 23 24 25 26 27 27
28 29 30 32 33 34 35 36 36
37 38 39 41 42 43 44 45 45
46 47 48 50 51 52 53 54 54
55 56 57 59 60 61 62 63 63
64 65 66 68 69 70 71 72 72
You increment col until it reaches the end of the first row, but you never reset it for subsequent rows, which is why you end up removing only the first row's column.
Make sure you reset col at the start of each iteration:
void removeColumn(int** matrix, int col){
MATRIX_WIDTH--;
for(int i=0;i<MATRIX_HEIGHT; i++) {
int curr_col = col; // <- use a temporary `col` variable for each row
while(curr_col<MATRIX_WIDTH)
{
//move data to the left
matrix[i][curr_col]=matrix[i][curr_col+1];
curr_col++;
}
matrix[i] = realloc(matrix[i], sizeof(int)*MATRIX_WIDTH); // <- int, not double
}
}
Edit (in response to OP's edit):
Ensure that removeColumn() updates the number of columns (cols) after resizing the matrix; one way to do that is by using a pointer: int *cols as a parameter instead of int cols (don't forget to pass in an address, &arCol, when calling this function). Also, I suggest getting rid of the unnecessary MATRIX_HEIGHT variable:
void removeColumn(int** matrix, int col2del, int rows, int *cols){
int MATRIX_WIDTH = --(*cols);
for(int i=0;i<rows; i++) {
int curr_col = col2del;
while(curr_col<MATRIX_WIDTH)
{
//move data to the left
matrix[i][curr_col]=matrix[i][curr_col+1];
curr_col++;
}
matrix[i] = realloc(matrix[i], sizeof(matrix[i][0])*MATRIX_WIDTH);
}
}
It's easier if you pass the width and height, and update the width:
void removeColumn(int** matrix, int col, int* width, int height)
{
int j, i;
for (j = 0; j < height; ++j) {
if (col == *width-1) {
continue;
}
for (i = col; i < *width; ++i) {
matrix[j][i] = matrix[j][i+1];
}
// this is not necessary, but I'm adding as requested
matrix[j] = realloc(
matrix[j],
sizeof(int) * (*width - 1)
);
}
--(*width);
}
You could also avoid dynamic memory allocations, avoiding memory defragmentation:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int max_width, max_height;
int width, height;
int* values;
} matrix;
void removeColumn(matrix* matrix, int col)
{
int y, i;
for (y = 0; y < matrix->height; ++y) {
if (col == matrix->width-1) {
continue;
}
i = col + matrix->height * y;
while (i < matrix->width) {
matrix->values[i] = matrix->values[++i];
}
}
--matrix->width;
}
void printMatrix(matrix* matrix)
{
int y, x;
for (y = 0; y < matrix->height; ++y) {
for (x = 0; x < matrix->width; ++x) {
printf("%d ", matrix->values[x + matrix->width * y]);
}
printf("\n");
}
}
int main ()
{
int y, x = 0;
matrix matrix;
matrix.max_width = 4;
matrix.max_height = 4;
matrix.width = 4;
matrix.height = 4;
int values[4][4];
matrix.values = &values;
for (y = 0; y < matrix.height; ++y) {
for (x = 0; x < matrix.width; ++x) {
int i = x + matrix.width * y;
matrix.values[i] = i % 10;
}
}
printMatrix(&matrix);
removeColumn(&matrix, 1);
printf("===\n");
printMatrix(&matrix);
}
Tested using: https://www.tutorialspoint.com/compile_c_online.php
ADDED
But when the array size is too big then do we have any other option
but using dynamic array
If you want to make a resizable array, you could use a single malloc when allocating the array and use a realloc when the width will be greater than max_width or the height will be greater than max_height.
Nevertheless, I believe we should try to avoid lots of dynamic allocations using malloc or realloc, because they're slow (though most of the time you won't notice), they can severely defragment memory and the way you did it generates lots of unnecessary cache misses.
You should also grow them more than required, for instance, exponentially, if you don't know that you will need to resize the array several times. That's how hashes and dynamic arrays are usually implemented (properly).
You may find, for instance, several JSON, XML and HTML C libraries without dynamic memory to avoid its pitfalls, and in many professional video games, a huge malloc might be used to avoid lots of them and simple arrays are used liberally.
Why is realloc eating tons of memory?
https://blog.mozilla.org/nnethercote/2014/11/04/please-grow-your-buffers-exponentially/
http://gameprogrammingpatterns.com/data-locality.html
https://codefreakr.com/how-is-c-stl-implemented-internally/
http://gamesfromwithin.com/start-pre-allocating-and-stop-worrying
CppCon 2014: Mike Acton "Data-Oriented Design and C++"
Of course, you can use dynamic memory, but it's better to understand its pitfalls for better decisions.
I tried to use realloc in a code I am working on and once I do the realloc not all the values that were in the original array are present in the newly allocated array. The code is as follows.
#include <stdio.h>
#include <stdlib.h>
#define CONST1 20
#define CONST2 2
int main() {
double *a = (double *) malloc(sizeof(double) * CONST1);
int i;
for (i = 0; i < CONST1; i++) {
a[i] = i * i;
}
for (i = 0; i < CONST1; i++) {
printf("%.0lf ", a[i]);
}
printf("\n");
double *b = (double *) realloc(a, CONST1 + CONST2);
a[CONST1] = 11;
a[CONST1+1] = 12;
for (i = 0; i < CONST1+CONST2; i++) {
printf("%.0lf ", b[i]);
}
printf("\n");
return 0;
}
The output I got for running this code is;
0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361
0 1 4 0 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 11 12
Can anyone point out to me the reason for the second 0 in the second row?
It works fine when the CONST1 value is set to 4. After 4 it shows this behaviour where either one or two values are set to 0.
Assuming double is 8-byte long, I guess b happened to be the same as a and some 0x00 bytes are written to the buffer after the newly allocated buffer to manage something.
You made two mistakes:
The a passed to realloc() is deallocated, according to N1256 7.20.3.4 The realloc function, so you must not use it. You assigned the new pointer to b, so use b.
The size to be passed to realloc() should be sizeof(double) * (CONST1 + CONST2), not CONST1 + CONST2.
Also whatever is allocated should be freed, so you should add free(b); before return 0;.