You are not logged in. Please login at www.codechef.com to post your questions!

×

Help needed for pointer variable

I was solving the question that prints primes up to a limit. I solved after looking at solution. I couldn't understand the use of pointers here.

 int prime[100000000];
 int* sieve(int A, int *n) {


      *n = A; // length of result array
      int *result = (int *) malloc(*n * sizeof(int));
      int i,j;
      prime[0] = 1;
      prime[1] = 1;
      int k=0;
      for(i = 2;i <=A; i++)
      {
          if(prime[i] == 0)
          {

              for(j=i*2;j<=A;j+=i)

                prime[j] = 1;

          }
      }
      for(i = 2;i <= A; i++)
        {
            if(prime[i]==0)
            result[k++] = i;
            *n = k;     //  PLEASE HELP ME UNDERSTAND THE USE OF THIS LINE 
        }
      return result;
 }

I have commented the line I don't understand. Also, If I remove that line, I get array filled with 0s Please help me here

asked 02 Jan '17, 21:11

aniketsanadhya's gravatar image

1★aniketsanadhya
115210
accept rate: 0%


For a C++ program, the memory of a computer is like a succession of memory cells, each one byte in size, and each with a unique address. These single-byte memory cells are ordered in a way that allows data representations larger than one byte to occupy memory cells that have consecutive addresses.

This way, each cell can be easily located in the memory by means of its unique address. For example, the memory cell with the address 1776 always follows immediately after the cell with address 1775 and precedes the one with 1777, and is exactly one thousand cells after 776 and exactly one thousand cells before 2776.

When a variable is declared, the memory needed to store its value is assigned a specific location in memory (its memory address). Generally, C++ programs do not actively decide the exact memory addresses where its variables are stored. Fortunately, that task is left to the environment where the program is run - generally, an operating system that decides the particular memory locations on runtime. However, it may be useful for a program to be able to obtain the address of a variable during runtime in order to access data cells that are at a certain position relative to it.

*n is a pointer in this code which locates value stored at "A".

Initially the value of all elements in "result" is zero. So if you remove that line your code always change the value of "result[k++]" and the value of "A" is always constant.

link

answered 02 Jan '17, 21:50

only4's gravatar image

4★only4
1.5k212
accept rate: 17%

edited 02 Jan '17, 21:51

But there is one thing I don't get, in my for loop, n is getting changed alright but that n is not getting used anywhere inside my loop still if I remove the value changes

(03 Jan '17, 20:33) aniketsanadhya1★

I am assuming you know what pointers are and how they work. If not, please take a look here. In summary, a pointer stores the memory address of another variable. Which can be used to change the value of a variable from a different function, for instance.

The sieve function you have here is defined as int* sieve(int A, int *n). It takes 2 arguments. int A is the limit upto which it finds all primes. int *n is the address of a variable sent to this functions, whose purpose is to store the count of all primes found (not mentioned in the code). The function returns an int* value, which is a pointer to the result array containing the primes found. The method is used as

int main(void) {
    int cnt, i;  // cnt will store the number of primes found
    int *res = sieve(100, &cnt);
    //                     ^ here the address of cnt variable is passed to sieve function
    for(i=0; i< cnt; i++)
        printf("%d ", res[i]);
    return 0;
}

After the sieve function receives the value of the cnt variable as int *n, whenever *n is used it refers to the value of the cnt variable. In the first line of the code, *n is set to A. So the variable cnt in main gets set to A. Later while gathering the primes into result, k refers to the number of primes found. Each time a new prime is collected the count needs to be updated, so *n is updated to k.
If you delete this line, the *n = A line remains. So the value of cnt will be set to A and when sieve finishes execution it will remain A. As a result you will see A values while printing, where only k are primes and rest are 0 as provided by malloc.

I have tried to document the code it properly so that it's easier to understand, here. Hope this helps, and do ask if something is not clear.

link

answered 02 Jan '17, 23:44

meooow's gravatar image

6★meooow ♦
7.1k718
accept rate: 48%

edited 03 Jan '17, 01:17

First of all, thanks for your efforts mate. It's my mistake that I didn't tell the use of n, it is used to define the length of array. The line I have problem is n = k. This is the part I didn't understand.

(03 Jan '17, 15:30) aniketsanadhya1★
2

It's not "n=k", it's "*n=k". "*n = k" changes the value at the address stored in n to k. The address stored in n comes from the caller function, so that the sieve function can save the number of primes found in *n. I would suggest you read up on pointers further.

(04 Jan '17, 00:08) meooow ♦6★

please provide full solution so I can understand your doubt.

link

answered 02 Jan '17, 21:25

olympiadcrack's gravatar image

2★olympiadcrack
5816
accept rate: 7%

*n = k;
updating a size of the usable data in result.
prime numbers are in between result[0] and result[*n - 1].

link

answered 03 Jan '17, 06:44

ishibashijun's gravatar image

3★ishibashijun
1
accept rate: 0%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×62

question asked: 02 Jan '17, 21:11

question was seen: 544 times

last updated: 04 Jan '17, 00:08