'Can I use #undef and #define mid code to change something in another function?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#define TYPE char
typedef struct node
{
TYPE data;
struct node *next;
} node;
typedef struct
{
node *top;
} stack;
node *newNode(TYPE x)
{
node *n = malloc(sizeof(node));
n->data = x;
n->next = NULL;
return n;
}
Can I later change the type to a float in another function and, if so, how do I do that? I am trying to use my stack as another thing or do I have to write another separate set of functions?
Solution 1:[1]
No you can't, this is because macro's are pre-processed what you can do is either use a union(not the best) or allocate dynamic memory (bytes) and then append them and cast them to form the variable you want, there's also void pointers etc...
For example with the void pointers you could do something like they allow your nodes to have different types of data although it can be hard to manage it as you start to have strings, etc...
{
void * datapnt;
struct node *next;
} node;
...
//on main or another place
type* t = malloc(...);
t[0]=some value;
node->datapnt=t;
//now data points to its value
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | marc_s |
