Home > OS >  How to give condition to my for loop to stop my integer pointer after reading all elements of my int
How to give condition to my for loop to stop my integer pointer after reading all elements of my int

Time:09-22

#include<stdio.h>

#include<stdlib.h>

int main()

{ int a[3];

int *x=(int *) malloc (7*sizeof(int));

int *p=x;

scanf("%d %d %d",&a [0],&a[1],&a [2]); 
for(int i=0;i<3; i  )
{
if(i==0)
for(int j=0; j<3;j  )
    *p  =a[j];
else if (i==1)
    for (int j=0; j<3; j  ) 
    *p  =a[j] a[(j 1)%3];
else
    for(int j=0; j<3;j  )
    *p =a[j];

}
*(  p)= '\0';//id-001

int last=sizeof(x)/sizeof(x[0]); 
printf("%d\n", last); //My expected output is 7 but why I'm getting 2?
p=x;

for(int i=0;p!='\0';i  ){   //id-002
printf("%d ",x[i]);
p  ;
}
}

How should I need to change id-001 to stop my integer pointer?

How should I need to change id-002 my for loop condition to stop after reading stored value in heap array?

CodePudding user response:

int last=sizeof(x)/sizeof(x[0]);

This is incorrect since sizeof() only works for arrays who's size is known at compile time. In your case x is an allocated pointer so this is just dividing the size of a pointer (8 on x86_64) by the size of int (usually 4), hence you get 2.

I'm not sure what you exactly want to do with this program, but the termination condition here can be fixed:

for(int i=0;p!='\0';i ){

Here you're comparing the pointer with a NUL terminatior, not the value that the pointer points to. It should be changed to *p to check the value:

for(int i=0;*p!='\0';i ){

You don't need to advance the pointer again since it would've been advanced by the previous call to *p = something:

*( p) = '\0'; // id-001

So change this to *p = '\0'.

There seems to be a typo in this loop, it should be changed to *p = a[j];:

for (int j = 0; j < 3; j  )
  *p  = a[j];

There is a buffer overflow in the loop itself since p is advanced without any bounds checks. It's advanced a total of 9 times which is out of bounds for size 7.

  • Related