Accessing Struct From Other Source File - c

I have two files: getParams.c and tree.c.
What I'm trying to do is to declare tnode from tree.c into my getParams.c.
I don't remember how to properly include code from other source files.
getParams.c
#include <stdlib.h>
int main(int argc, char *argv[]) {
tnode *doublyLinked;
addtree(doublyLinked, argv[1]);
return 0;
}
tree.c
/*
* Tree routines from Kernighan and Ritchie
* Chapter 6.
*/
#include <stdio.h>
#include <string.h>
#define EOS '\0'
#define LETTER 'a'
#define DIGIT '0'
#define MAXWORD 20
struct tnode{ /* the basic node */
char *word; /* points to the text */
int count; /* number of occurrences */
struct tnode *left; /* left child */
struct tnode *right; /* right child */
};
main(){ /* word frequency count */
struct tnode *root, *addtree();
char word[MAXWORD];
int t;
root = NULL;
while((t=getword(word, MAXWORD)) != EOF)
if (t == LETTER)
root = addtree(root,word);
treeprint(root);
}
... more code
The error I'm getting
gcc getParams.c tree.c -o getParams
getParams.c: In function ‘main’:
getParams.c:5:2: error: unknown type name ‘tnode’
Could I receive your help?

I. You should define the tnode structure type in a separate header file and include that header file into both implementation files.
II. This is C, not C++. struct tnode { }; doesn't automatically define the type name tnode - you have to do that manually:
typedef struct tnode {
/* foo */
} tnode;

you need to declare tnode in a shared header and then include it using the following:
#include "myheader.h"

Related

I need someone to explain binary trees for me

edit: found the edit button, fundamental code is at https://github.com/unidef/quantum. it'd be awesome if you clone'd and fixed it, or forked it
here's a quick paste
jons-MacBook-Pro:quantum jon$ cat */*
todo: makefile, srsly
cat: bin/tests: Is a directory
#pragma once
#include "quantum.h"
// tests
TEST temp;
// id system
double long id;
#pragma once
#include "quantum.h"
extern FILE *filename;
extern FILE *extraFileName;
#pragma once
#include "sys.h"
#pragma once
// system macros
#define NEURAL_ARRAY 100
#define NEURAL_DIMENSION 20
#define NEURAL_DIRECTION "up"
#define NEURAL_MALLOC malloc(sizeof(NEURON))
#define NEURAL_MALLOC_BIG malloc(sizeof( NEURON * 20 )
// system libraries
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <math.h>
// built in libraries
#include "types.h"
#include "doc.h"
#include "io.h"
// extra variables
#pragma once
#include "types.h"
typedef struct neural_node NODE;
typedef struct neural OPERATIONS;
typedef struct neural SQL;
typedef struct neural TEST;
typedef struct neural DOC;
typedef struct neural ERROR;
typedef struct neural NEURON;
typedef double long ID;
#pragma once
#include "sys.h"
#include "typedefs.h"
// data structures
struct neural {
ID id;
char *description;
NODE *dimension[NEURAL_ARRAY][NEURAL_ARRAY][NEURAL_ARRAY];
} *N;
struct neural_node {
ID id;
DOC description;
ERROR (*exception)(NODE,DOC); // add SYS
NODE *up;
NODE *down;
NODE *left;
NODE *right;
} *NN;
#include "quantum.h"
// data operations
OPERATIONS arrange();
OPERATIONS delete();
OPERATIONS move();
OPERATIONS rearrange();
OPERATIONS query();
// internal sql database
SQL database();
// used for documentation purposes
DOC license();
DOC help();
void printq(char *msg, DOC *description){
printf(msg, "%s");
}
#include "sys.h"
OPERATIONS arrange();
OPERATIONS delete();
OPERATIONS move();
OPERATIONS rearrange();
OPERATIONS query();
SQL database();
DOC license();
DOC help();
// types
// doc
// system variables
#define NEURAL_ARRAY 1000000
#define NEURAL_DIMENSION 20
#define NEURAL_DIRECTION "up"
// general variables
typedef struct _neural_node NODE;
typedef struct _neural OPERATIONS;
typedef struct _neural SQL;
typedef struct _neural TEST;
typedef struct _neural DOC;
typedef double long ID;
struct _neural {
ID id;
DOC description;
NODE *dimension[NEURAL_ARRAY];
};
struct _neural_node {
ID id;
DOC description;
NODE *up;
NODE *down;
NODE *left;
NODE *right;
NODE dimension[NEURAL_DIMENSION];
};
init:
cc quantum.c -o quantum
tests:
trash:
mv *~ trash
mv lib/*~ trash
mv bin/*~ trash
General Purpose Quantum Paralellization Library
by Unidef
Licensed by the BSD License
#include "lib/quantum.h"
// additional code
int main(){
DOC INIT;
return 0;
};
#include "sys.h"
OPERATIONS arrange();
OPERATIONS delete();
OPERATIONS move();
OPERATIONS rearrange();
OPERATIONS query();
SQL database();
DOC license();
DOC help();
#pragma once
// system libraries
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <math.h>
// built in libraries
#include "types.h"
#include "doc.h"
#include "io.h"
// system variables
#define NEURAL_ARRAY 100
#define NEURAL_DIMENSION 20
#define NEURAL_DIRECTION "up"
#pragma once
#include "types.h"
typedef struct _neural_node NODE;
typedef struct _neural OPERATIONS;
typedef struct _neural SQL;
typedef struct _neural TEST;
typedef struct _neural DOC;
typedef struct _neural ERROR;
typedef struct _neural NEURON;
typedef double long ID;
#pragma once
#include "sys.h"
#include "types.h"
#include "typedefs.h"
// data structures
struct neural {
ID id;
char *description;
NODE *dimension[NEURAL_ARRAY][NEURAL_ARRAY][NEURAL_ARRAY];
};
struct neural_node {
ID id;
DOC description;
ERROR (*exception)(NODE);
NODE *up;
NODE *down;
NODE *left;
NODE *right;
};
jons-MacBook-Pro:quantum jon$
------
sorry for duplicate code, I have a lot of cached files
Basically I have a small database project I want to dub as a neural/ai technology that uses binary trees to high dimensions, I'm just confused on the whole node, pointer, how many pointers to use, etc thing
in my head this is a binary tree.
#define X 100
struct NODE
{
int id;
NODE *movement[X];
};
struct SQL
{
char *description;
NODE *next;
NODE *prev;
NODE *up;
NODE *down;
};
// usage
main()
{
SQL *DOC[X];
DOC[0] = (SQL*)(malloc(sizeof(SQL));
DOC[0]->next->id = 0;
DOC[0]->next->next->id=1;
}
// etc, didn't check it on a compiler
the problem is it segfaults
Is it a requirement to use C or a binary tree? When I was trying to do stuff with neural networks, my approach of multidimensional arrays was to use a flattened array and calculate the index with something like that
double & Tensor::operator[](std::initializer_list<int> list)
{
// TODO: insert return statement here
vector<int> tuple(list.begin(), list.end());
int dim = tuple[0];
int lastDimensions = dimensions[0];
for (int i = 1; i < tuple.size(); i++) {
if (i > dimensions.size() - 1)
{
break;
}
if (tuple[i] > dimensions[i]) throw exception("Dimension do not match");
dim += tuple[i] * lastDimensions;
lastDimensions *= dimensions[i];
}
return elements[dim];
}
(the whole class can be found at Tensor)
but maybe I didn't understand the question correctly...
You defined an array of pointers, not an array of structures. Before using it, you must initialize with pointers to structures of type SQL. Or create an array like SQL DOC [X] = {0};
int main(int argc, char **argv)
{
SQL *ptr = (SQL *) malloc(sizeof(SQL)*X);
SQL DOC[X];
if (!tmp)
return 1;
for (int i = 0; i < X; i++)
DOC[i] = ptr+i;
DOC[0]->next->id = 0;
DOC[0]->next->next->id=1;
}

Passing a typedef from header to source - C

I have the following main.c file:
#include <stdio.h>
#include <stdlib.h>
#include <wctype.h>
#include "lista.h"
int main(int argc, char *argv[])
{
struct nod *root = NULL;
root = init(root);
return 0;
}
And lista.h:
#ifndef LISTA_H_INCLUDED
#define LISTA_H_INCLUDED
#include "lista.c"
typedef struct nod
{
int Value;
struct nod *Next;
}nod;
nod* init(nod *);
void printList(nod *);
#endif // LISTA_H_INCLUDED
And finally lista.c which is:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include "lista.h"
nod* init(nod *root)
{
root = NULL;
return root;
}
void printList(nod *root)
{
//We don't want to change original root node!
nod *aux = root;
printf("\n=== Printed list =====\n");
while (aux != NULL)
{
printf(aux->Value);
aux = aux->Next;
}
puts("\n");
}
Even after included header file, I'm getting three errors which say:
Unknown type name 'nod'
How to make that typedef from lista.h to be seen on lista.c?
I just can't figure out what is happening here.
Have a look at your lista.h header file:
#ifndef LISTA_H_INCLUDED
#define LISTA_H_INCLUDED
#include "lista.c"
[..]
#endif // LISTA_H_INCLUDED
You're including lista.c, which you shouldn't do at all. And the error occures, because at that time nod isn't defined yet.

C - redefinition error in Xcode

My c header file has the following error message in Xcode
Redefinition of 'entry'
But it works perfectly when I compile it using gcc in command line. Could any of you give an explanation of why?
This is snapshot.h:
#ifndef SNAPSHOT_H
#define SNAPSHOT_H
#define MAX_KEY_LENGTH 16
#define MAX_LINE_LENGTH 1024
typedef struct value value;
typedef struct entry entry;
typedef struct snapshot snapshot;
struct value {
value* prev;
value* next;
int value;
};
// the line below is where the redefinition error appears
struct entry {
entry* prev;
entry* next;
value* values;
char key[MAX_KEY_LENGTH];
};
struct snapshot {
snapshot* prev;
snapshot* next;
entry* entries;
int id;
};
#endif
This is snapshot.c:
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include "snapshot.h"
int
main(int argc, char *argv[]){
int x = 7;
printf("x= %d\n" , x);
printf("value = %d\n", 1);
return 0;
}
entry was originally reserved as a keyword and then later declared obsolete. So older compilers don't allow it (see this question). Change the name of the struct and everything should be fine.

Conflicting types for 'Graph' error

I'm getting an error saying 'conflicting types for 'Graph' for the following code, but I'm not sure what the issue is, as Graph is declared before it is used anywhere. Anyone know what the issue is?
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#define __USE_BSD // make prototype for strdup visible
#include <string.h>
typedef struct linkedlist { // linked list of ints (for use in Node)
int index;
struct linkedlist *next;
} List;
typedef struct { // a Node of a Graph
char *name;
List *outlist; // adjacency list
int outdegree; // length of outlist
int indegree; // length of inlist
int dfsnum;
//double pagerank_score; //not needed for this exercise
} Node;
typedef struct {
int MaxSize;
Node *table;
} Graph;
// use to check result of strdup, malloc etc.
extern void check (void *memory, char *message);
extern int initialize_graph (Graph *mygraph, int MaxSize);
extern int insert_graph_node (Graph *mygraph, int n, char *name);
extern int insert_graph_link (Graph *mygraph, int source, int target);
extern int read_graph (Graph *mygraph, char *filename);
extern void print_graph (Graph *mygraph);
I am not sure but i think CDT MinGW has an extended C lib which already has a variable name reserved which is called "Graph", have you tried renaming your struct? This might be the case though i have never worked with CDT MinGW before

Pointers and structs

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dictionary.h"
#define HASH_SIZE 100
// prototype
int hash(char *word);
// counter
int counter;
// node
typedef struct
{
char *word;
node *next;
} node;
// hash table
node *hashtable[HASH_SIZE];
bool
load(const char *dictionary)
{
// open the dictionary
FILE *dict = fopen(dictionary, "r");
if(dict == NULL)
{
printf("Could not open %s.\n", dictionary);
return false;
}
// set all values in the hash table to null
for(int i = 0; i < HASH_SIZE; i++)
{
hashtable[i] = NULL;
}
// set the counter to 0
counter = 0;
// iterate through the words in the dictionary
while (!feof(dict))
{
// get word into a string
char gotcha[LENGTH];
fscanf(dict, "%s", gotcha);
// declare a node and allocate memory
node n;
n.word = malloc( strlen(gotcha)*sizeof(char) );
// save the word into the node
strcpy(n.word, gotcha);
// hash the word, baby!
int hash_value = hash(n.word);
// start saving addresses to the hashtable
n.next = hashtable[hash_value];
hashtable[hash_value] = &n;
//test
int len = strlen(n.word);
printf("%s\n", n.word);
printf("%i\n", len);
// that's one more!
counter++;
}
fclose(dict);
return true;
}
I am receiving the following two errors on these two lines of code:
n.next = hashtable[hash_value];
hashtable[hash_value] = &n;
dictionary.c:89:16: error: assignment from incompatible pointer type [-Werror]
dictionary.c:90:31: error: assignment from incompatible pointer type [-Werror]
How do I save pointer values in these two places? I am new to this, so please bear that in mind. :)
In your structure, the type node is not yet defined. Change it to use the structure tag:
typedef struct node
{
char *word;
struct node *next;
} node;
This:
typedef struct
{
char *word;
node *next;
} node;
is a syntax error. The node *next; occurs before the end of the typedef that creates node as a type. If your compiler for some reason accepted this, it probably thinks there are 2 different types called "node" now, which explains why one of them isn't compaible with the other. You should give up on that typedef silliness (structs generally shouldn't be typedef'ed) and just use
struct node
{
char *word;
struct node *next;
};
Define typedef names of structs before defining the structs. This allows mutually referring structs without concern for order and doesn't require inconsistent definitions, sometimes with the struct keyword and sometimes without it. Note that in C++ you can do away with the typedef line entirely:
typedef struct node node;
struct node
{
char* word;
node* next;
};

Resources