0
struct process {
  int id;
  struct process * prev;
  struct process * next;
}

struct process * ready = NULL;
struct process * running;

int main() {
  struct process * curr = NULL;
  curr = ready;
  while (curr != NULL) {
    curr = curr - > next;
  }
  struct process * tmp = (struct process * ) malloc(sizeof(struct process));
  //running->id=1  !!!
  tmp = running;
  printf("%d", tmp - > id); //it prints 1
  tmp - > next = NULL;
  curr = tmp;
  printf("%d", curr - > id); //it prints 1
}

I made linked-list like this. Before while loop, *ready is empty. I think curr is pointing to ready and I copy running's id to curr's first node's id. So I think ready's id will be 1. But, it didn't. I don't know which part has error...

Derek Wang
  • 9,720
  • 4
  • 15
  • 38
장동균
  • 45
  • 5
  • 2
    There is only one place where `ready` gets a value, and it is `null`, so why do you expect it to be something different? – trincot Oct 12 '20 at 19:58
  • 1
    "I think curr is pointing to ready" -- No, `curr` is the value of `ready` (which is `NULL`), until you assign it to the value of `tmp` at the end of your program. – Andreas Wenzel Oct 12 '20 at 20:55
  • 1
    If you want to see the values of all variables at different stages of your program, then I suggest you run your program line by line in a [debugger](https://stackoverflow.com/q/25385173/12149471). – Andreas Wenzel Oct 12 '20 at 20:57
  • why `curr` is the value of `ready`?? two of them is pointer and I put ready to curr... – 장동균 Oct 13 '20 at 02:02
  • @장동균: A pointer is nothing more than a memory address. If you write `curr = ready`, then you are copying the memory address contained in the value of `ready` into the variable `curr`, so that `ready` and `curr` both have the same value (i.e. memory address). If you want `curr` to point to the variable `ready`, then you must write the following instead: `curr = &ready`. However, for this to work, the data type of `curr` would have to be changed to `struct process **`. – Andreas Wenzel Oct 13 '20 at 02:08
  • @AndreasWenzel I think change `*ready` to `ready` and make curr = &ready can be another solution. Isn't it?? – 장동균 Oct 13 '20 at 02:44
  • @장동균: If you change `struct process * ready` to `struct process ready`, then `ready` willl no longer be a pointer, but rather an instance of the actual struct. In that case, you will no longer be able to initialize `ready` with the value `NULL`. However, you are right that the line `curr = &ready` will work, then. That will cause `curr` to point to `ready`. – Andreas Wenzel Oct 13 '20 at 02:50
  • @AndreasWenzel I'm really thanks to your help... I have confidence to solve my problem with your advice. Thank you. – 장동균 Oct 13 '20 at 03:17

0 Answers0