So i try to make binary tree using array implementation. I just start it but I got a problem. First, this is my struct that I use to build my node for the tree
typedef char infotype;
typedef int letak; //it's the variable to tell the array position number
typedef struct simpul
{
infotype info;
letak parent;
letak rightSon, leftSon;
}elemenSimpul;
typedef struct
{
elemenSimpul treeMember[30]; //my tree have very maximum 30 nodes in it.
int maksimum; //it's the variable to put how many node the user wants and should be under 30
}tree;
here is my btreestatic.h
#ifndef btreestatic_H
#define btreestatic_H
void createTree(tree T);
void createNode(tree T, int i, char value);
void initNode(tree T, int i);
#endif
and for construct the tree I use these at my btreestatic.c
#ifndef btreestatic_C
#define btreestatic_C
#include <stdio.h>
#include <math.h>
#include "btreestatic.h"
void createTree(tree T)
{
T.treeMember[0].parent = -1;
}
void createNode(tree T,int i, char value)
{
int leftchild;
int rightchild;
T.treeMember[i].info = value;
leftchild = 2 * i + 1;
rightchild = 2 * i + 2;
if(leftchild < T.maksimum)
{
T.treeMember[i].leftSon = leftchild;
}
else
{
T.treeMember[i].leftSon = -1;
}
if (rightchild < T.maksimum)
{
T.treeMember[i].rightSon = rightchild;
}
else
{
T.treeMember[i].rightSon = -1;
}
if(i == 0)
{
T.treeMember[i].parent = -1;
}
else
{
T.treeMember[i].parent = (i - 1) / 2;
}
}
void initNode(tree T, int i)
{
char info;
printf("Input node info : ");
scanf(" %c", &info);
createNode(T, i, info);
}
#endif
and on my driver is
#include <stdio.h>
#include <stdlib.h>
#include "btreestatic.h"
int main()
{
tree A;
int maksimum;
int j;
createTree(A);
scanf("%d", &maksimum);
A.maksimum = maksimum;
for(j = 0; j < A.maksimum; j ++)
{
initNode(A, j);
}
printf("%c", A.treeMember[0].info);
return 0;
}
then I try my input as 3 (the maximum of the tree nodes are 3). First node(root) is 'a', second node is 'b', and third node is 'c'. But what i got on my screen is 'd' instead of 'a'. Can anyone tell me where did I go wrong? Thank you.
Related
This code is written in C. The first line of Node_reset() function occurs an error. (Structure array is allocated dynamically in main function.) I think there's something wrong in member-access of Node_reset(), also Create() might occur same kind of error. Input.txt, the following format is provided:
2
3 dfs(3)
786 368 603
5 bfs(4)
825 162 768 724 635
The number in the first line (i.e., 2) shows the number of test cases to be processed. From the second line, test cases are given, and the information for each case is provided over two lines.
In the first line (line number 2 in the example above), the first number (i.e., 3) indicates the number of integers in that case, and the next string (i.e., dfs(3)) shows the location of the target number that you need to look for. In this example, the target number is on the third node of DFS.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_QUEUE_SIZE 100
#define FALSE 1;
#define TRUE 0;
typedef struct BST_node{
int data;
int visited;
struct BST_node * leftChild;
struct BST_node * rightChild;
}node;
typedef node* TreeNode;
typedef struct {
TreeNode data[MAX_QUEUE_SIZE];
int front;
int rear;
}Queue;
void Node_reset(TreeNode* input_tree, int BST_size)
{
for(int i=0;i<BST_size;i++)
{
input_tree[i]->data = 0; //"Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)"occurs
input_tree[i]->leftChild=NULL;
input_tree[i]->rightChild=NULL;
input_tree[i]->visited=FALSE;
}
}
void Create(TreeNode* input_tree, int data[], int BST_size)
{
for(int i=0;i<BST_size;i++)
{
input_tree[i]->data=data[i];
}
for(int i=0;i<BST_size-1;i++)
{
if(input_tree[i]->data > input_tree[i+1]->data) input_tree[i]->leftChild=input_tree[i+1];
else input_tree[i]->rightChild=input_tree[i+1];
}
}
void init_Q(Queue* q)
{
q->front = q->rear =0;
}
int IsEmpty(Queue* q)
{
return (q->front == q->rear);
}
int IsFull(Queue* q)
{
return ((q->rear+1)%MAX_QUEUE_SIZE==q->front);
}
void enqueue(Queue* q,TreeNode data)
{
if(IsFull(q))
{
printf("Queue is Full");
}
q->rear = (q->rear+1)%MAX_QUEUE_SIZE;
q->data[q->rear]=data;
}
TreeNode dequeue(Queue* q)
{
if(IsEmpty(q))
{
printf("Queue is empty");
return NULL;
}
q->front = (q->front+1)%MAX_QUEUE_SIZE;
return q->data[q->front];
}
int DFS_search(TreeNode Node, int *searching_times)
{
while(*searching_times==0){
*searching_times--;
if(Node->leftChild!=NULL) DFS_search(Node->leftChild, searching_times);
if(Node->rightChild!=NULL) DFS_search(Node->rightChild, searching_times);
}
return Node->data;
}
int BFS_search(TreeNode* Node, int searching_times)
{
Queue q;
init_Q(&q);
for(int i=0;i<searching_times;i++)
{
enqueue(&q, Node[i]);
if(Node[i]->leftChild)
enqueue(&q, Node[i]->leftChild);
if(Node[i]->rightChild)
enqueue(&q, Node[i]->rightChild);
}
for(int i=0;i<searching_times;i++)
{
if(i==searching_times-1) return dequeue(&q)->data;
else dequeue(&q);
}
return 0;
}
void pass_result(int result_num,int *result,int result_arr[])
{
result_arr[result_num]=(*result);
}
void return_result(int result_arr[],int how_many)
{
FILE *of = fopen("output.txt","w");
for(int i=0;i<how_many;i++)
{
fprintf(of, "%d\n",result_arr[i]);
}
fclose(of);
}
int main()
{
int how_many_times; //the number of input expression
int BST_size; //input the number of element here
char string[7]={0}; //input string data here
char temp[2]={0}; //input searching num
int searching_times; //the number of input expression
int result; //result of expression
FILE *fp = fopen("input.txt","r");
fscanf(fp, "%d", &how_many_times);
int *result_arr=(int*)malloc(sizeof(int)*how_many_times);
for(int i=0;i<how_many_times;i++)
{
memset(string, 0, sizeof(char)*7); //reset string[]
memset(temp, 0, sizeof(char)*2); //reset temp[]
fscanf(fp, "%d", &BST_size); //pass BST size
int* input=(int*)malloc(sizeof(int)*BST_size); //allocate heep memory as long as input BST size
fscanf(fp, "%s", string); //pass string input data to string[]
TreeNode* tree=(TreeNode*)malloc(sizeof(TreeNode)*BST_size);
Node_reset(tree, BST_size);
for(int i=0;i<BST_size;i++) //input elements in array
{
fscanf(fp, "%d",&input[i]);
}
Create(tree, input, BST_size);
for(int i=0;i<2;i++)
{
temp[i]=string[i+4];
}
searching_times=atoi(temp); //input data about searching times becomes integer type
if(strcmp(&string[0],"d")) result=DFS_search(tree[0], &searching_times);
if(strcmp(&string[0],"b")) result=BFS_search(tree, searching_times);
pass_result(i, &result, result_arr); //pass the result
free(input);
}
return_result(result_arr, how_many_times); //return result in txt file
free(result_arr); //free result heep data
}
This is the part that occurs error. If needed please refer full code or tell me what I could do more. 😂
#define MAX_QUEUE_SIZE 100
#define FALSE 1;
#define TRUE 0;
typedef struct BST_node{
int data;
int visited;
struct BST_node * leftChild;
struct BST_node * rightChild;
}node;
typedef node* TreeNode;
typedef struct {
TreeNode data[MAX_QUEUE_SIZE];
int front;
int rear;
}Queue;
void Node_reset(TreeNode* input_tree, int BST_size)
{
for(int i=0;i<BST_size;i++)
{
input_tree[i]->data = 0;
input_tree[i]->leftChild=NULL;
input_tree[i]->rightChild=NULL;
input_tree[i]->visited=FALSE;
}
}
void Create(TreeNode* input_tree, int data[], int BST_size)
{
for(int i=0;i<BST_size;i++)
{
input_tree[i]->data=data[i];
}
for(int i=0;i<BST_size-1;i++)
{
if(input_tree[i]->data > input_tree[i+1]->data) input_tree[i]->leftChild=input_tree[i+1];
else input_tree[i]->rightChild=input_tree[i+1];
}
}
int main()
{
int how_many_times; //the number of input expression
int BST_size; //input the number of element here
char string[7]={0}; //input string data here
char temp[2]={0}; //input searching num
int searching_times; //the number of input expression
int result; //result of expression
FILE *fp = fopen("input.txt","r");
fscanf(fp, "%d", &how_many_times);
int *result_arr=(int*)malloc(sizeof(int)*how_many_times);
for(int i=0;i<how_many_times;i++)
{
fscanf(fp, "%d", &BST_size); //pass BST size
int* input=(int*)malloc(sizeof(int)*BST_size); //allocate heep memory as long as input BST size
fscanf(fp, "%s", string); //pass string input data to string[]
TreeNode* tree=(TreeNode*)malloc(sizeof(TreeNode)*BST_size);
Node_reset(tree, BST_size);
for(int i=0;i<BST_size;i++) //input elements in array
{
fscanf(fp, "%d",&input[i]);
}
Create(tree, input, BST_size);
}
}
someone help me please i am stucked at this pointed at line 75,96,133 i am getting error warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
when at line 96 i replaced int with long then it resolved the issue but for other two it is still same someone please explain me what i am doing wrong here?
#include <linux/module.h>
#include <linux/list.h>
#include <linux/slab.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("WaSi");
int init(void);//initialization
int hashFunc(int);//Hash function
void addAllNodes(int[]);//Add all keyword nodes
void showAllNodes(void);//Print all keyword nodes
int search(int);//Query node address based on keywords
//Hash table length and hash remainder
#define N 8
//Keyword array length
#define LENGTH 20
//Node structure
struct hlist_data {
int key;
struct hlist_node hNode;
};
struct hlist_head* head;
//Initialize, apply for memory
int init(void) {
int index;
head = (struct hlist_head*)kmalloc(sizeof(struct hlist_head) * N, GFP_KERNEL);
if (!head) return 0;
printk("\nStart initializing the hash table!\n");
for (index = 0; index < N; index++) {
INIT_HLIST_HEAD(&head[index]);
}
return 1;
}
//The simplest hash function-remainder
int hashFunc(int key) {
return key % N;
}
//Insert all keyword nodes
void addAllNodes(int array[]) {
int index;
int i;
int hashAddr;//Address;
struct hlist_data* hd;
for (index = 0, i = 1; index < LENGTH; index++) {
//Apply for memory for keyword nodes
hd = (struct hlist_data*)kmalloc(sizeof(struct hlist_data), GFP_KERNEL);
INIT_HLIST_NODE(&(hd->hNode));
hd->key = array[index];
printk("Add node%d-----%d!\n", i++, array[index]);
//Keyword gets the hash address according the hash function
hashAddr = hashFunc(array[index]);
hlist_add_head(&(hd->hNode), &(head[hashAddr]));//Head insertion method
}
}
// Traverse and print all nodes
void showAllNodes(void) {
int index;
struct hlist_data* hd;
struct hlist_node* pos;
printk("\ntraversal print!\n");
//Loop array
for (index = 0; index < N; index++) {
printk("%d\n", index);
//Circular singly linked list
hlist_for_each(pos, &(head[index])) {
//Find out the first address of the linked list node pointed by pos
hd = hlist_entry(pos, struct hlist_data, hNode);
**printk("%d(%d)->", hd->key, int pos);**
}
printk("NULL");
printk("\n");
}
}
//Find the node address based on keywords
int search(int searchKey) {
int hashAddr;
struct hlist_data* hd;
struct hlist_node* pos;
printk("finding %d!\n", searchKey);
//Find the address
hashAddr = hashFunc(searchKey);
printk("According the hash function obtain the address=%d!\n", hashAddr);
hlist_for_each(pos, &(head[hashAddr])) {
hd = hlist_entry(pos, struct hlist_data, hNode);
**if (hd->key == searchKey) return (long)pos;**
}
return -1;
}
static int __init hlist_init(void) {
int keys[LENGTH] = { 1,2,3,4,5,6,7,16,18,20,31,44,47,51,55,60,66,69,72,73 };// A set of keywords
int addr;//Used when searching
int searchKey;
//Initialization
if (!init()) return -1;
//Insert the node as a hash function according the simple remainder
addAllNodes(keys);
//Print all nodes
showAllNodes();
//Give keywords
searchKey = 19;
addr = search(searchKey);
if (addr == -1) printk("Search failed\n\n");
else printk("Find the node address with key %d is %d\n\n", searchKey, addr);
return 0;
}
static void __exit hlist_exit(void) {
int index;
int i;
struct hlist_data* hd;
struct hlist_node* pos, * n;
for (index = 0, i = 1; index < N; index++) {
//The traversal here needs be safe
hlist_for_each_safe(pos, n, &(head[index])) {
hd = hlist_entry(pos, struct hlist_data, hNode);
**printk("Delete node%d-----%d, the address is%d\n", i++, hd->key, int pos);**
hlist_del(pos);
kfree(hd);
}
}
kfree(head);
printk("Deletion is complete!\n");
}
module_init(hlist_init);
module_exit(hlist_exit);
My teacher gave me a library that describes a single linked list. I am writing a main file to test it, and i ran into a very weird problem.
This is the header for the linked list library (There are more function, but i only putin the one i used):
#ifndef DSSINGLYLINKEDLIST_H
#define DSSINGLYLINKEDLIST_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _SListEntry SListEntry;
typedef struct _SListIterator SListIterator;
typedef void *SListValue;
/**
* Definition of a #ref SListIterator.
*/
struct _SListIterator {
SListEntry **prevNext;
SListEntry *current;
};
#define SLIST_NULL ((void *) 0)
typedef int (*SListCompareFunc)(SListValue value1, SListValue value2);
typedef int (*SListEqualFunc)(SListValue value1, SListValue value2);
SListEntry *slist_append(SListEntry **list, SListValue data);
SListValue slist_nthData(SListEntry *list, unsigned int n);
unsigned int slist_length(SListEntry *list);
#ifdef __cplusplus
}
#endif
#endif /* #ifndef DSSINGLYLINKEDLIST_H */
This is my .c file:
#include <stdlib.h>
#include <stdio.h>
#include "dssinglylinkedlist.h"
struct _SListEntry {
SListValue data;
SListEntry *next;
};
SListEntry *slist_append(SListEntry **list, SListValue data)
{
/* Create new list entry */
SListEntry *newEntry = malloc(sizeof(SListEntry));
if (newEntry == NULL) {
return NULL;
}
newEntry->data = data;
newEntry->next = NULL;
/* Hooking into the list is different if the list is empty */
SListEntry *rover;
if (*list == NULL) {
/* Create the start of the list */
*list = newEntry;
} else {
/* Find the end of list */
rover=*list;
while (rover->next != NULL) {
rover = rover->next;
}
/* Add to the end of list */
rover->next = newEntry;
}
return newEntry;
}
SListValue slist_nthData(SListEntry *list, unsigned int n)
{
/* Find the specified entry */
SListEntry *entry = slist_nthEntry(list, n);
/* If out of range, return NULL, otherwise return the data */
if (entry == NULL) {
return SLIST_NULL;
} else {
return entry->data;
}
}
unsigned int slist_length(SListEntry *list)
{
SListEntry *entry = list;
unsigned int length = 0;
while (entry != NULL) {
/* Count the number of entries */
++length;
entry = entry->next;
}
return length;
}
I think there's nothing wrong with these code.
I am writing a main using this library to store information of two polynomial:
#include <stdio.h>
#include <stdlib.h>
#include "dssinglylinkedlist.h"
void printPolynomial(SListEntry*);
int main()
{
SListEntry *poly1;
int n;
printf("Input n for poly1: ");
scanf("%d", &n);
printf("Input poly1: ");
for (int i=0; i<=n; i++) {
int *temp = (int *) malloc(sizeof (int));
scanf("%d", temp);
slist_append(&poly1, temp);
}
printPolynomial(poly1);
SListEntry *poly2;
printf("Input n for poly2: ");
scanf("%d", &n);
printf("Input poly2: ");
// for (int i=0; i<=n; i++) {
// int *temp = (int *) malloc(sizeof (int));
// scanf("%d", temp);
// slist_append(&poly2, temp);
// }
// printPolynomial(poly2);
return 0;
}
void printPolynomial(SListEntry *list)
{
int length = (int)slist_length(list);
for (int i = 0; i < length; i++) {
int temp = *((int *)slist_nthData(list,(unsigned int)i));
if (i >0 && temp >= 0) {
printf("+");
}
printf("%d*x^%d", temp, length-i-1);
}
printf("\n");
}
So if i comments the second loop (after i print 'Input poly2', like i wrote above), i can still input my poly1 and print it. But if i un-comments it, my program crashes immediately when i append the first element of poly1.
What is the problem of my code?
This question already has answers here:
Wrong output while running C code [duplicate]
(8 answers)
Closed 5 years ago.
I came across some problems while doing my assignment. Part of this assignment involves creating a linked-list with the data given and printing them out. The data stored in the list is of datatype 'Atom', which can be an integer, a string, a "pair"(self-defined datatype), or a list made of Nodes.
If the input is (the first integer indicates the number of data)
4
1 2 3 4
it prints
1 2 3 4
What makes me feel strange is that, if I change the function read_list_helper(int n) like this
Node* read_list_helper(int n)
{
Atom *atom;
if (n == 0) return NULL;
return combine_atom_and_list(get_atom(), read_list_helper(n - 1));
}
the output becomes
4 3 2 1
Why would this happen? I have tried several keywords to search for the answer, but none of them works.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define STRING 0
#define NUM 1
#define PAIR 2
#define LIST 3
struct Atom;
typedef struct Pair
{
struct Atom *left;
struct Atom *right;
} Pair;
typedef struct Node
{
struct Atom *data;
struct Node *next;
} Node;
typedef struct Atom
{
int dtype;
int val = 0;
char str[21] = {'\0'};
Pair *pair = NULL;
Node *Node = NULL;
} Atom;
Node* read_list();
Node* read_list_helper(int);
Atom* get_atom();
Node* combine_atom_and_list(Atom*, Node*);
void print_atom(Atom*);
void print_pair(Pair*);
void print_list(Node*);
int main()
{
Node *head1;
head1 = read_list();
print_list(head1);
system("pause");
return 0;
}
Node* read_list()
{
int n;
scanf("%d", &n);
return read_list_helper(n);
}
Node* read_list_helper(int n)
{
Atom *atom;
if (n == 0) return NULL;
atom = get_atom();
return combine_atom_and_list(atom, read_list_helper(n - 1));
}
Atom* get_atom()
{
int num;
char str[21];
int i;
Atom* res = (Atom*)malloc(sizeof(Atom));
if (scanf("%d", &num) == 1)
{
res->dtype = NUM;
res->val = num;
}
else
{
scanf(" %20s", str);
res->dtype = STRING;
strncpy(res->str, str, 20);
}
return res;
}
Node* combine_atom_and_list(Atom* atom, Node* node)
{
Node *res = (Node*)malloc(sizeof(Node));
res->data = atom;
res->next = node;
return res;
}
void print_atom(Atom* atom)
{
if (atom == NULL) return;
switch (atom->dtype)
{
case NUM:
printf("%d", atom->val);
break;
case STRING:
printf("%s", atom->str);
break;
case PAIR:
print_pair(atom->pair);
break;
case LIST:
print_list(atom->Node);
break;
default:
break;
}
}
void print_pair(Pair* pair)
{
print_atom(pair->left);
print_atom(pair->right);
}
void print_list(Node* node)
{
print_atom(node->data);
if (node->next != NULL)
{
printf(" ");
print_list(node->next);
}
}
Function arguments are not evaluated in any particular order. Since one of your arguments does I/O, the order of evaluation affects the order of the inputs.
I have the following C program:
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
typedef struct node_t node_t;
struct node_t
{
char *name;
node_t **nodes;
};
node_t* init(int p_n)
{
node_t *node = malloc(sizeof(node_t));
node->name = "_ROOT_";
if(p_n > 0 && p_n < 10)
{
node->nodes = malloc(p_n*sizeof(node_t**));
char nbuffer[9];
int i;
for(i = 0; i < p_n; i++)
{
node_t *child = malloc(sizeof(node_t));
sprintf(nbuffer, "NAME %d", i);
child->name = nbuffer;
node->nodes[i] = child;
}
}
return node;
}
int main(int argc, char *argv[])
{
int n = 3;
node_t *ROOT = init(n);
printf("%sNODE {name:%s [%lu]}\n",
"", ROOT->name, sizeof(ROOT->nodes)/sizeof(ROOT->nodes[0])
);
assert(n == sizeof(ROOT->nodes)/sizeof(ROOT->nodes[0]));
free(ROOT);
return 0;
}
The assertion from the beginning of the main method fails and this is my problem. What I am doing wrong in the evaluation of the length of member nodes?
This post is know by me but from some reason it doesn't work for me. Why?
SK
Assuming a 32 bit pointer.
The sizeof(ROOT->nodes) is going to be 4 bytes. A pointer to a pointer it still a pointer.
The sizeof(ROOT->nodes[0]) is also going to be 4 bytes. It too is a pointer.
Hence 4/4 != 3 and your assert fails.
I'm not sure what your objective is, but if you're wanting to do something like this with dynamically allocated storage you might do something like the following. It can be extended with additional APIs to add, remove, etc. This solution maintains a count of the number of elements in the list.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#define NAME_SIZE 32
typedef struct node_s {
char *name;
} node_t;
typedef struct node_list_s {
int count;
node_t *nodes;
} node_list_t;
void init(node_list_t *l, int p_n) {
int i = 0;
char name[NAME_SIZE];
if(!l) return;
memset(l, 0, sizeof(node_list_t));
l->nodes = malloc(p_n*sizeof(node_t));
l->count = p_n;
for(i=0;i<l->count;i++) {
snprintf(name,sizeof(name),"NAME %d",i);
l->nodes[i].name = strdup(name);
}
}
void term(node_list_t *l) {
int i = 0;
if(!l) return;
for(i=0;i<l->count;i++) {
if(l->nodes[i].name) free(l->nodes[i].name);
}
if(l->nodes) free(l->nodes);
}
void print(node_list_t *l) {
int i = 0;
if(!l) return;
for(i=0;i<l->count;i++) {
printf("%d %s\n", i, l->nodes[i].name ? l->nodes[i].name : "empty" );
}
}
int main(int argc, char *argv[]) {
node_list_t list;
init(&list, 3);
print(&list);
term(&list);
return 0;
}