How to Read a File and Store in a 2d Array
We tin create both static and dynamic array in C. These arrays can be one dimensional or multiple dimensional. In statically allocated assortment problem is that nosotros have to specify the size of the array earlier the compilation. And then the trouble is generated when nosotros don't know how much size of the array required ahead of time.
Go here for a quick introduction of the Array in C: Brief introduction of Array
We can resolve these issues using dynamic retentiveness allotment. The reward of a dynamically allocated array is that information technology is allocated on the heap at runtime. The C language provides a library function to request for the heap retentiveness at runtime.
In the below program, I am using malloc to allocate the dynamic retention for the 1D and second array.
Syntax of malloc in C
void * malloc (size_t size);
Parameters
size ==> This is the size of the retentiveness block, in bytes.
Render Value:
Returns a pointer to the allocated retention, if enough memory is not available so it returns Aught.
1D array using the dynamic retention allocation in C
In the below example, I am creating a pointer to an integer and assign it heap memory. When retention is successfully assigned to the arrow so we can apply this pointer as a 1D array and using the square braces "[]" we can admission the pointer as similar the statically allocated array. Permit us see the below Image for better agreement.
Let's see a program example,
#include <stdio.h> #include <stdlib.h> #define Neglect i #define TRUE 0 int main(int argc, char *argv[]) { int *piBuffer = NULL; //pointer to integer int nBlock = 0; //Variable shop number of block int iLoop = 0; //Variable for looping printf("\nEnter the number of block = "); scanf("%d",&nBlock); //Go input for number of cake piBuffer = (int *)malloc(nBlock * sizeof(int)); //Bank check memory validity if(piBuffer == NULL) { return Fail; } //re-create iLoop to each block of 1D Array for (iLoop =0; iLoop < nBlock; iLoop++) { piBuffer[iLoop] = iLoop; } //Print the copy data for (iLoop =0; iLoop < nBlock; iLoop++) { printf("\npcBuffer[%d] = %d\due north", iLoop,piBuffer[iLoop]); } // gratis allocated memory free(piBuffer); render TRUE; }
Output:
If yous love online courses and want to learn C programming, you can check the beneath courses it will help.
- The C Programming Linguistic communication in Action (Complimentary Trial Bachelor).
- C Programming For Beginners – Main the C Language.
- Pointers in C Programming – Master the C Language.
- Learning C with Dan Gookin (FREE Trial Available).
2nd array using the dynamic retentivity resource allotment
In C language like the 1D array, nosotros can as well create the 2D assortment using the dynamic memory allocation at runtime. In below, I am list some generic steps to create the 2D assortment using the pointers.
Steps to creating a 2D dynamic array in C using arrow to pointer
- Create a pointer to pointer and allocate the memory for the row using malloc().
int ** piBuffer = Nil; piBuffer = malloc( nrows * sizeof(int *));
- Allocate retention for each row-column using the malloc().
for(i = 0; i < nrows; i++) { piBuffer[i] = malloc( ncolumns * sizeof(int)); }
- If each row does non have the same number of columns and so allocate memory for each row individually.
piBuffer[0] = malloc( ncolumns * sizeof(int)); piBuffer[i] = malloc( ncolumns * sizeof(int)); piBuffer[n] = malloc( ncolumns * sizeof(int));
Allow's encounter the below picture where I am creating a 5×5 2d array using the dynamic memory allocation.
When each row incorporate the aforementioned number of column
Hither we have to call malloc function ii times, one for the row and second for the column. You can come across the example code, where we are calling malloc function two times.
Note: Every location in each row is a face-to-face retention but it is non necessary every row at contiguous retention in heap.
#include <stdio.h> #include <stdlib.h> #ascertain Fail 1 //Free Allocated memory void freeAllocatedMemory(int **piBuffer, int nRow) { int iRow = 0; for (iRow =0; iRow < nRow; iRow++) { complimentary(piBuffer[iRow]); // free allocated memory } free(piBuffer); } int primary(int argc, char *argv[]) { int **piBuffer = Zip; //pointer to pointer int nRow = 0; //variable store number of Row int nColumn = 0; //variable store number of Row int iRow = 0; //Variable for looping Row int iCol = 0; //Variable for looping column printf("\nEnter the number of Row = "); scanf("%d",&nRow); //Get input for number of Row printf("\nEnter the number of Cavalcade = "); scanf("%d",&nColumn); //Get input for number of Column //Allocate memory for row piBuffer = (int **)malloc(nRow * sizeof(int*)); //Check memory validity if(piBuffer == NULL) { return FAIL; } //Classify retentivity for column for (iRow =0 ; iRow < nRow ; iRow++) { piBuffer[iRow] = (int *)malloc(nColumn * sizeof(int)); //Check retention validity if(piBuffer[iRow] == Naught) { freeAllocatedMemory(piBuffer,iRow); return FAIL; } } //Copy the data in second Array for (iRow =0 ; iRow < nRow ; iRow++) { for (iCol =0 ; iCol < nColumn ; iCol++) { piBuffer[iRow][iCol] = 3; } } //Print the content of 2d array for (iRow =0 ; iRow < nRow ; iRow++) { for (iCol =0 ; iCol < nColumn ; iCol++) { printf("\npiBuffer[%d][%d] = %d\n",iRow, iCol,piBuffer[iRow][iCol]); } } freeAllocatedMemory(piBuffer,nRow); return 0; }
Output:
Annotation: You can see, how we tin can create a vector in C.
When each row contain a different number of column
Nosotros can also create a not-square ii-dimensional array in c using the dynamic retention allotment. Here we have to explicitly telephone call malloc for each row. Hither we are lucky considering the number of columns of each row is equal to their row_index+1. For example, the 0th row has 1 column, 1st row has 2 columns ..etc. So nosotros are able to use for loop to call the malloc office. It reduces the code length.
Consider the below prototype and case for better understanding.
#include <stdio.h> #include <stdlib.h> #define FAIL 1 //Free Allocated memory void freeAllocatedMemory(int **piBuffer, int nRow) { int iRow = 0; for (iRow =0; iRow < nRow; iRow++) { gratuitous(piBuffer[iRow]); // free allocated memory } free(piBuffer); } int main(int argc, char *argv[]) { int **piBuffer = Zero; //pointer to pointer int nRow = 0; //variable store number of Row int iRow = 0; //Variable for looping Row int iCol = 0; //Variable for looping column printf("\nEnter the number of Row = "); scanf("%d",&nRow); //Get input for number of Row //Classify memory for row piBuffer = (int **)malloc(nRow * sizeof(int*)); //Cheque retentivity validity if(piBuffer == NULL) { render Fail; } //Allocate retentiveness for column for (iRow =0 ; iRow < nRow ; iRow++) { piBuffer[iRow] = (int *)malloc((iRow+1) * sizeof(int)); //Check memory validity if(piBuffer[iRow] == Nothing) { freeAllocatedMemory(piBuffer,iRow); render FAIL; } } //Copy the information in 2nd Array for (iRow =0 ; iRow < nRow ; iRow++) { for (iCol =0 ; iCol <= iRow ; iCol++) { piBuffer[iRow][iCol] = 27; } } //Display the stored data for (iRow =0 ; iRow < nRow ; iRow++) { for (iCol =0 ; iCol <= iRow ; iCol++) { printf("\npiBuffer[%d][%d] = %d\n",iRow, iCol,piBuffer[iRow][iCol]); } } //Free Allocated memory freeAllocatedMemory(piBuffer,iRow); return 0; }
Output:
Dynamically 2nd array in C using the single pointer:
Using this method we can save memory. In which we can only do a single malloc and create a large 1D array. Hither nosotros will map 2D array on this created 1D array.
#include <stdio.h> #include <stdlib.h> #define Fail one int primary(int argc, char *argv[]) { int *piBuffer = NULL; //arrow to integer int nRow = 0; //variable store number of Row int nColumn = 0; //variable store number of Row int iRow = 0; //Variable for looping Row int iCol = 0; //Variable for looping column printf("\nEnter the number of Row = "); scanf("%d",&nRow); //Go input for number of Row printf("\nEnter the number of Column = "); scanf("%d",&nColumn); //Become input for number of Column //Allocate retentivity for row piBuffer = (int *)malloc(nRow * nColumn * sizeof(int)); //Bank check memory validity if(piBuffer == Nil) { return FAIL; } //Copy 5 in 2nd Array for (iRow =0 ; iRow < nRow ; iRow++) { for (iCol =0 ; iCol < nColumn ; iCol++) { piBuffer[iRow * nColumn + iCol] = v; } } //Print the content of 2D assortment for (iRow =0 ; iRow < nRow ; iRow++) { for (iCol =0 ; iCol < nColumn ; iCol++) { printf("\npiBuffer[%d][%d] = %d\n",iRow, iCol,piBuffer[iRow * nColumn + iCol]); } } //gratis the allocated memory free(piBuffer); return 0; }
Output:
Yous want to learn more about C Pointers, you tin can check the beneath articles.
- A brief description of the pointer in C.
- Dangling, Void, Zero and Wild Pointers
- Function arrow in c, a detailed guide
- How to apply the structure of function pointer in c linguistic communication?
- Function pointer in structure.
- Pointer Arithmetic in C.
- void pointer in C.
- 10 questions about dynamic memory allocation.
- Memory Layout in C.
- 100 C interview Questions
- File handling in C.
- C format specifiers.
Source: https://aticleworld.com/dynamically-allocate-2d-array-c/
Postar um comentário for "How to Read a File and Store in a 2d Array"