top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Check the following two functions and explain if method1 and method2 are same?

0 votes
421 views
#include<stdio.h>
#include<stdlib.h>

int main(void)
{
  int *p
  int size = 10;

  p=(int*)calloc(size,sizeof(int));

  while(i != size)
  {
    *p++=1;       /*    METHOD 1       */
    i++;
  }

  i=0;

  while(i != size)
  {
    i[p] = 1;         /*    METHOD 2    */
    i++;
  }

}    
posted Apr 23, 2017 by Leon Martinović

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Both the methods will result different. In first method pointer "p" is being incremented in every iteration. So once loop exists pointer "p" will be pointing to location which is different from the initial address given by malloc function.
In second method pointer "p" is not being incremented while it is holding the same address allocated at the time of malloc function but in every iteration value "1" is being assigned.

answer Apr 23, 2017 by Harshita
thx__
Similar Questions
+1 vote

Check the following C example, why is one loop so much slower than two loops?

Suppose we have to add some values to array a1 and c1 of b1 and d1 respectively then there is big time difference in execution of both code..

const int n=100000;
for(int j=0;j<n;j++){
    a1[j] += b1[j];
    c1[j] += d1[j];
}

This loop is executed 10,000 times via another outer for loop. to speed it up, I changed the code to:

for(int j=0;j<n;j++){
    a1[j] += b1[j];
}
for(int j=0;j<n;j++){
    c1[j] += d1[j];
}

I don't think there should be any execution time difference but it is showing.

+6 votes

What is the simples way to check if the sum of two unsigned integers has resulted in an overflow.

+6 votes
                    50                      50
                   /  \                    /  \
                  20     30              30   20
Sample Tree<---   /  \                       /  \   ----> Mirror image
               70      80                   80   70
              /  \    \                    /    /  \  
             10  40     60                60   40   10
...