PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 5, 2022

[FIXED] How to access user-chosen struct variable C++

 July 05, 2022     c++, pass-by-reference, struct     No comments   

Issue

I am using a function to print out data from a linked list, the list Nodes have 2 variables which could be accessed, data or index. I want to add a parameter to the print() function that allows the user to call the variables name within the Node that they want to be outputted, I've heard of passing by reference and I'm pretty sure this is what I want to do but haven't found any resources that actually work for my code.

(simply I want to pass a variable name to a function).

here is my code:

struct Node {
    int data;
    int index;
    Node *next;
}

Node *_current;
Node *_next;
Node *_head;
Node *_temp;
Node *_tail;
Node *_last;
// all this is handled correctly

void print(*variable name*) {
   Node *n = _head;
   while (n->next != nullptr) {
       std::cout << n-> *variable name* << std::endl;
       n = n->next;
   }
}

p.s: variable name is not necessarily a pointer but just (literally) referring to the variable name parameter I want to add.

this code works if I swap out variable name to 'std::cout << n->data <<...' and runs without any other issues. (btw Whole code isn't provided just the parts needed to explain what I want to change)

any helpful information is greatly appreciated, Thank you in advance. :)


Solution

p.s: variable name is not necessarily a pointer

But it is a pointer. A member pointer, specifically:

void print(int Node::*member) {
   Node *n = _head;
   while (n->next != nullptr) {
       std::cout << n->*member << std::endl;
       n = n->next;
   }
}

It would get invoked as either

print(&Node::data);

or

print(&Node::index);


Answered By - Sam Varshavchik
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing