1

Why am I getting the same output in the following for loop in c++.

node* nn =  (struct node*)malloc(sizeof(struct node));      
for(int i=0;i<10;i++)
{

    node* n =  (struct node*)malloc(sizeof(struct node)); 
    cout<<&n<<endl;
    nn->next = n;
    nn =n;
}
Persixty
  • 8,165
  • 2
  • 13
  • 35
tarunkota
  • 43
  • 5
  • what is the output you're getting? – Ian Rehwinkel Apr 28 '18 at 08:14
  • 2
    Show the declarations for `node` (presumes struct, or typedeffed struct) Please provide [**A Minimal, Complete, and Verifiable Example (MCVE)**](http://stackoverflow.com/help/mcve). – David C. Rankin Apr 28 '18 at 08:25
  • `n` is a variable that is local to the loop, and you are printing its address. It would be a pretty trivial optimisation for the compiler to create the variable (on the stack) before the loop, and do a reassignment in each iteration (in this case, to the result of the `malloc()` call). If the compiler does such a thing, `&n` would be the same in every iteration. Note that `&n` is not affected by `malloc()`. – Peter Apr 28 '18 at 10:20
  • Friendly advice... Don't use `malloc`, or `new`. Avoid pointers. Use standard containers. – Jive Dadson Apr 28 '18 at 10:34

3 Answers3

4

Because your n variable is local to the loop body, it is created at the beginning of each iteration, and destroyed at the end of each iteration.

Evidently the compiler decided to reuse the same storage for every incarnation of n, which is why all of them have the same memory address.

Note that &n is the address of n, not its contents. You don't even have to initialize it. Your call to malloc is irrelevant.

If you want to see the value of n, you need to remove the &.

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • 1
    The address of `n` isn't changing because of the redeclaration issue, but he is also leaking memory on each iteration. – David C. Rankin Apr 28 '18 at 08:19
  • How do I create n nodes? Use of vectors is prohibited, so I am creating a linked linked list of n nodes, but the problem is I am unable to create n nodes in a loop. – tarunkota Apr 28 '18 at 08:20
  • Get rid of the loop and simply use `struct *n = malloc (sizeof *n * 10);` – David C. Rankin Apr 28 '18 at 08:21
  • @user3104926 Your code already creates 10 nodes in a loop. I don't see the problem. – melpomene Apr 28 '18 at 08:22
  • @user3104926 - if you are creating a *linked-list*, you simply allocate when you `add` a node to the list and make the previous `next` pointer point to the new node. (that's where an MCVE helps us help you) – David C. Rankin Apr 28 '18 at 08:24
1

You're outputting &n which is the address of n not the content of n which is probably what you wanted.

NB: The question was edited following my answer, but the same problem remains.

Try this:

#include <iostream>
#include <cstdlib>

struct node {
    node* next;
};

int main() {
    node* nn =  (struct node*)malloc(sizeof(struct node));      
    nn->next=nullptr;//Initialise so we can clean up nicely...
    for(int i=0;i<10;i++)
    {

        node* n =  (struct node*)malloc(sizeof(struct node)); 
        n->next=nullptr;//Initialise so we can clean up nicely...
        std::cout<<&n<<"=="<<n<<std::endl;
        nn->next = n;
        nn =n;
    }
    //Clean up after ourselves. Not relevant to the question but good practice.
    while(nn!=nullptr){
        node*n=nn;
        free(nn);
        nn=n;
    }
    return 0;
}

Typical output:

0x7ffda1be2058==0x55ffb0b9fc20
0x7ffda1be2058==0x55ffb0ba0c50
0x7ffda1be2058==0x55ffb0ba0c70
0x7ffda1be2058==0x55ffb0ba0c90
0x7ffda1be2058==0x55ffb0ba0cb0
0x7ffda1be2058==0x55ffb0ba0cd0
0x7ffda1be2058==0x55ffb0ba0cf0
0x7ffda1be2058==0x55ffb0ba0d10
0x7ffda1be2058==0x55ffb0ba0d30
0x7ffda1be2058==0x55ffb0ba0d50

The actual output may vary and in principle a compiler isn't required to store n at the same address each iteration. I know of no compiler that doesn't. Anyone?

NB: Using malloc() in C++ is very rarely recommended. The direct substitute for malloc() and free() is new and delete. In practice use std::unique_ptr<> or other self managing construct.

Persixty
  • 8,165
  • 2
  • 13
  • 35
0

This is only an addition to melpomene's answer, responding to the comments:

How do I create n nodes? Use of vectors is prohibited, so I am creating a linked linked list of n nodes, but the problem is I am unable to create n nodes in a loop.

Actually, your code was less incorrect than you thought, solely you missed one important point:

nn->next = n;

With this instruction, you lost the last reference to what nn pointed to originally and you won't ever be able to re-gain it again...

What you yet need is a second pointer to the element created initially, so you don't lose your list head and thus the rest of the list any more:

node* nn = new node(); // this is the C++ way...
node* head = nn; // now you have a second pointer to the head... 

for(int i=0;i<10;i++)
/* [...] */

Now you can access all the nodes you created via the head pointer (as long as you do not move it away from...).

Get rid of the loop and simply use struct *n = malloc (sizeof *n * 10); – David C. Rankin

Another variant: creating 10 elements directly... Assuming node looks like this:

struct node
{
    Data data;
    node* next;
};

Then you get 10 elements of Data simply by

Data* allData = new Data[10]; // again using the C++ way...

The C++ aproach has another advantage: the elements in the array are already initialised as the default constructor gets called (for primitive data types, see here).

Aconcagua
  • 24,880
  • 4
  • 34
  • 59