Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create 2d_address.c #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions 2d_address.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#include <stdio.h>
#include <stdlib.h>

int main()
{
int **arr; // Declare a pointer to a pointer to int
int rows, cols,i,j,size,address;
char ch;
size=sizeof(int);
int base=(int)&arr[0][0];
//taking the number of rows and columns from the user
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);

// Dynamically allocating memory for the 2D array
arr = (int **)malloc(rows * sizeof(int *));
for (i = 0; i < rows; i++)
{
arr[i] = (int *)malloc(cols * sizeof(int));
}

// Checking if memory allocation was successful
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
//ask user the index of the array to find the address of that index
do
{
printf("\nEnter row no.: ");
scanf("%d",&i);
printf ("\nEnter col no.: ");
scanf("%d",&j);
if(i>rows||j>cols||i<0||j<0)
{
printf("you are trying to find the address of a non allocated memory\n");
}
else
{
address = base+(i*cols+j)*size;
printf("Memory address of arr[%d][%d]: %p\n", i, j, (void *)address);
}
printf("Do you want to try again with the other index:- Y/y for Yes\n");
scanf(" %c",&ch);
}while(ch=='Y'||ch=='y');
// Freeing the dynamically allocated memory
for (int i = 0; i < rows; i++) {
free(arr[i]);
}
free(arr);
return 0;
}