Why are 2D array elements not printed using *(a+1)? - c

I am trying to accept and print 2D array using same integer lets take i and j but I'm not getting expected output. I'm using *(a+i) to print but it seem to print address!
Could some one please explain why it is happening like this ?
#include<stdio.h>
int main()
{
int a[3][4];
int i,j,k,l;
printf("enter element\n");
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
scanf("%d",&a[i][j]);
}
printf("#####################\n");
for(i=0;i<12;i++)
{
printf("%d\n",*(a+i)); // what is *(a+i)? is it a[i]?
} // how will it print all address??
}

Your answer is very simple you do this for arrays (*(arr+n)) arr is an address and n is the no
of element address you search . If you want to search for addresses into a matrix you must first convert matrix address into a array address something like :
*(*mat+n);
And your code will be:
# include<stdio.h>
int main()
{
int a[3][4];
int i,j,k,l;
printf("enter element\n");
for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
scanf("%d",&a[i][j]);
}
printf("#####################\n");
for(i=0; i<8; i++)
{
printf("%d\n",*(*a+i)); // what is *(a+i)? is it a[i]?
}
}

what is *(a+i)? is it a[i]? - ya it is. you can represent a[i] in many forms. those are *(a+i) or *(i+a) or i[a]. All are representing same memory location only.
In your program *(a+i) wont work with in the same function. Try to pass the array to another function and print there that time it will work. Try the following code-
#include<stdio.h>
void print(int *a,int r ,int c)
{
int i ,j;
for(i=0;i<r*c;i++)
printf("%d\n",*(a+i));
}
int main()
{
int a[2][2];
int i,j,k,l;
printf("enter element\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
}
printf("#####################\n");
print(a,2,2); // calling my function here
}
But don't prefer this type of methods( *(a+i) for printing 2D array) in real time programming!

*(a+i) is definitely a[i].
Many bugs in your code need to fix first.
Your array reading value goes to out of bound. You defined array by int a[1][4] (room for 1*4 = 4 elements ) and you read 3*4=12 elements.
Also a points to entire 2D array and a+1 point to next 2D array. So you need to access by pointing to first element of the array.
So basically valid access is
a[0][1] = *( a[0] + 1 )
And
for(i=0;i<12;i++)
printf("%d\n",*(a[0]+i));

The best way you can do what you are trying to achieve is to take a pointer to the base address of the 2D array, and then traverse the array linearly as you wanted to do.
Also, as already answered by Sathish, *(a+i) = *(i+a) = a[i] = i[a]
Here, in my solution, I have just added a pointer p which points to the base address of a, and because the 2D array is stored linearly in the memory, you can access it by incrementing the pointer p to the next array element.
#include<stdio.h>
int main()
{
int a[3][4];
int i,j,k,li, *p;
printf("enter element\n");
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
scanf("%d",&a[i][j]);
}
printf("#####################\n");
p = &a[0][0];
for(i=0;i<12;i++)
{
printf("%d\n",*(p+i));
}
}

Related

Array of pointers whose elements point to another array of pointers

What I need very precisely is an array A[10] and each of its element pointing to the respective element of array B[10] whose each element store its index.
Hence, A[1] points to B[1] and B[1] has value of 1.
So, when I call *A[1] or *B[1], I get 1.
I know it can be super easy if the array B[10] is not an array of pointers but of integers but I need this for another purpose.
This is what I did but segmentation fault was offered.
#include <stdio.h>
int main() {
int *A[10];
int *B[10];
for(int i=0; i<10; i++) {
A[i] = B[i];
*B[i] = i;
printf("\n%d %d",*A[i],*B[i]);
}
}
By the way, I am not very proficient in pointers.
Your commented code :
int main() {
int *A[10]; // an array of 10 pointers, each of them pointing nowhere
int *B[10]; // an array of 10 pointers, each of them pointing nowhere
// now each array a and b contain 10 uninitialized pointers,
// they contain ideterminate values and they point nowhere
for(int i=0; i<10; i++) {
A[i] = B[i]; // copy an uninitialized pointer
// this usually works but it's pointless
*B[i] = i; // you assign i to the int pointed by *B[i]
// but as *B[i] points nowhere you end up with a segfault
printf("\n%d %d",*A[i],*B[i]); // you never get here because the previous
// line terminates the program with a segfault,
// but you'd get a segfault here too for
// the same reason
}
}
Your program is basically equivalent to this:
int main() {
int *a; // a is not initialized, it points nowhere
*a = 1; // probably you'll get a segfault here
}
Accessing the thing pointed by a pointer is called dereferencing the pointer. Dereferencing an uninitialized pointer results in undefined behaviour (google that term), most likely you'll get a seg fault.
I'm not sure what you're trying to achieve, but you probably want something like this:
#include <stdio.h>
int main() {
int* A[10];
int B[10];
for (int i = 0; i < 10; i++) {
A[i] = &B[i];
B[i] = i;
printf("%d %d\n", *A[i], B[i]);
}
}

What is the purpose of using (*ptr)[5] instead of *ptr? [duplicate]

This question already has answers here:
Difference between "pointer to int" and "pointer to array of ints"
(8 answers)
Closed 4 years ago.
I read about (*ptr)[5] that it can point to a 5-element integer array. What this means?
It can be used when you want to go through a 2-d or a higher dimensional array.
For example you have this 2-d array:
int a[3][4] = {
1,2,3,4,
5,6,7,8,
9,0,1,6
};
A normal *ptr will go through each of the elements in the array.
If this array's base address is : 1000. Then the next address it will go to on increment would be 1002, 1004, 1006. Taking sizeof(int) => 2.
What (*ptr)[5] would do is to jump to the next 5th element and then point to it.
In the example taken above, if I want to jump on the very starting of each 1-d array in it, I would simply use (*q)[4] and jump to the next 4th element and just not the very next one.
So if you want to display the elements of this array you can do this in two ways:
Using normal *ptr
void display(int *q, int row, int col){
int i, j;
for(i=0; i<row; i++){
for(j=0; j<col; j++){
printf("%d ", *(q + i*col + j));
}
printf("\n");
}
}
Using (*ptr)[4]
void show(int (*q)[4], int r, int col){
int i, j, *p;
for(i=0; i<r; i++){
p = q+i;
for(j=0; j<col; j++){
printf("%d ", *(p+j));
}
printf("\n");
}
}
int (*q)[5] means that q is a pointer to an array of 5 integers. To understand better let us use this pointer to an array of 5 integers.
void main()
{
int a[][5] = {
1,2,3,4,5,
6,7,8,9,10,
11,12,13,14,15
};
int *p;
int (*q)[5];
p = *a;
printf("%d %d\n",p,q);
p++;
q++;
printf("%d %d\n",p,q);
}
Output:
65500 65500
65502 65510
To begin with, both p and q contain the same address 65500. However, on incrementing p it points to an array of 5 integers.Hence on incrementing p it points to the next integer,
whereas q starts pointing to the next 1-D array of 5 integers. Pointer to the array is very useful while passing a 2D array to functions.

How to access a two dimensional array value and assing value to a int in C

I have a problem with my two dimensional array in C. Say 2D array is board[d][d] (d=7) and i want to assign value of board[d-1][d-2] to an int. When i do this i get error, if i printf board[d-1][d-2] i get 32766. The highest value in the array is d*d-1=48.
What am i doing wrong?
int main(void)
{
int d=7;
int nr=(d*d)-1;
int board[d][d];
int u=board[d-1][d-2];
bool even=false;
if ((d/2)*2!=d)
{
even=true;
}
printf("%d\n", even);
printf("%i\n", board[d-1][d-2]); //result here is 32764?
for(int i=0;i<d;i++)
{
for(int j=0;j<d;j++)
{
board[i][j]=nr;
nr--;
printf(" %2d", board[i][j]);
}
printf("\n");
}
return 0;
}
It's because you didn't initialize it with any value, so it simply stores whatever garbage happened to be there in memory atm.
You need to run on board and set initial values to it.
When you create the board array it's not initalised - you get garbage values inside. A good practice is to initialise the array before using it
int board[d][d] = {0};
If you move printf after the loop where you fill the array with values, you'll get the expected result

Array pointer in C program

Here is a C program in textbook, it asks a 3*5 2D array from users and prints the third line.
I am confused with int* p[5]. Why here needs to have [5], I think just int* p is OK. It can repeatedly add and point to the next memory space in the int array. And can anyone explain how pointer works in this program?
#include <stdio.h>
int main(void){
int a[3][5];
int i,j;
int *p[5];
p = &a[0];
printf("Please input:\n");
for(i = 0; i < 3; i++){
for(j = 0; j<5;j++){
scanf("%d\n",(*(p+i))+j);
}
}
p = &a[2];
printf("the third line is:\n");
for(j = 0; j<5; j++){
printf("%5d", *((*p)+j));
}
printf("\n");
}
int *p[5];
is an array of five pointers to int.
What you want is a pointer to an array of five ints
int (*p)[5];
because &a[0] is the address of the 1st element of a which is an int[5].
The compiler should have clearly issued at least a warning on this, if not an error, which would be expected.
More on this here: C pointer to array/array of pointers disambiguation

Passing an array to a sort function in C language

#include<stdio.h>
#include<conio.h>
float smallest(int arr[],int k,int n);
void sort(int arr[],int n);
void main()
{
int arr[20],i,n,j,k;
clrscr();
printf("\nEnter the number of elements in the array: ");
scanf("%d",&n);
printf("\nEnter the elements of the array");
for(i=0 ; i < n ; i++)
{
printf("\n arr[%d] = ",i);
scanf("%d",&arr[i]);
}
sort(arr,n);
printf("\nThe sorted array is: \n");
for(i=0 ; i < n ; i++)
printf("%d\t",arr[i]);
getch();
}
int smallest(int arr[],int k,int n)//smallest function
{
int pos=k,small=arr[k],i;
for(i=k+1;i<n;i++)
{
if(arr[i]<small)
{
small=arr[i];
pos=i;
}
}
return pos;
}
void sort(int arr[],int n)//sorting function
{
int k,pos,temp;
for(k=0 ; k < n ; k++)
{
pos=smallest(arr,k,n);
temp=arr[k];
arr[k]=arr[pos];
arr[pos]=temp;
}
}
In the above program the sort function is being called from main but the return type of sort is void and it still returns the sorted array. As after sorting the array the function should return the sorted array back to the calling function to print the sorted array but the program runs perfectly. How is that happening?
When you declare
int arr[20];
you can say "arr is an array of 20 integers". But arr is a pointer to an integer as well, pointing to the first integer in a row of 20. So de-referencing *arr is an integer, the same as arr[0] in fact.
This means when you pass arr to a function you only pass a pointer to that function. The function in this case works on the (copied) pointer. But this very pointer points exactly to the same memory as your original arr declared in main(). And that's the reason why manipulating arr in sort() is in fact manipulating arr in main().
When passing an array as a parameter, this
int smallest(int arr[],int k,int n)
means exactly the same as
int smallest(int *arr,int k,int n)
For example
#include<iostream>
void printArray(int data[])
{
for(int i = 0, length = sizeof(data); i < length; ++i)
{
std::cout << data[i] << ' ';
}
std::cout << std::endl;
}
int main()
{
int data[] = { 5, 7, 8, 9, 1, 2 };
printArray(data);
return 0;
}
You will see that only the first 4 elements of the array are printed. The sizeof(data) returns a value of 4! That happens to be the size of the pointer used to pass the array to printArray().
First the array does not get copied. The pointer to the first element of the array is copied
First, there is no connection between any function argument what is, or is not passed using a return statement with an expression according to the function's return type.
While it is true that all parameter passing in C is by value - copy the value to a "local parameter variable" - nothing is assumed about what is to happen at the memory location a pointer is referencing. So, a function can make any changes in the calling environment, even without returning a value.
As to parameters declared as being aType name[]. this is merely syntactic sugar for const aType* name.

Resources