How to print structures in C programming, anything similar to the toString() method of Java in c?

StackOverflow https://stackoverflow.com/questions/23508028

  •  16-07-2023
  •  | 
  •  

Question

I'm working on a C project. My project is to create a binary tree, this is my struct:

struct Node
{
  char * word;
  int count;
  struct Node* left;
  struct Node* right;
};

My question is how to print the struct, do I use printf() for each one of the field or there is a way to create a toString() method like in Java. What do you guys recommend? What's the easiest way?

I just realized I can create a method call print() and use printf and cast all the fields. Sorry but if you know a better way please let me know.

Was it helpful?

Solution

No real magic:

struct Node node = {"Adam", 1, NULL, NULL};
struct Node *nodePtr = &node;

printf("word[%s] count[%d] left[%p] right[%p]\n",
  node.word, node.count, node.left, node.right);

printf("word[%s] count[%d] left[%p] right[%p]\n",
  nodePtr->word, nodePtr->count, nodePtr->left, nodePtr->right);

OTHER TIPS

In C++ I would write a tostring() method for each node and call them recursively. But in c, try this.

struct Node node1 = {"Adam", 1, NULL, NULL};
struct Node node2 = {"Bert", 2, &node1, NULL};

void printit(Node* node) {
  printf("word[%s] count[%d] left[%p] right[%p]\n",
    node->word, node->count, node->left, nodePtr->right);
  if (node->left) printit(node->left);
  if (node->right) printit(node->right);
}

printit(&node2);

No. C is not object-oriented, and there's no general-purpose facility for turning C data into strings. You'll have to write your own function to either turn your struct into a string or print it out directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top