Pointers to a struct inside a struct - c

I have two structures (one_d and two_d).
I have a function that will take struct two_d *smg as input. In main(), I am trying to create such smg so it will return value c increased.
My problem is that, while creating an array of struct two_d smg[2], I am not sure how to put inside information about its values, as it is a pointer to a different struct.
So how do you use pointer to a struct inside a struct? I would like to create struct two_d smg[2] but i dont now how to deal with struct one_d *a field in it
#include <stdio.h>
enum sid
{
DRB,
DRA,
};
struct one_d
{
unsigned int r;
unsigned int *p;
};
struct two_d
{
struct one_d *a;
enum sid z;
};
unsigned int getSmg(struct two_d *smg)
{
unsigned int c = 0;
const struct two_d *sd = NULL;
const struct one_d *ed = NULL;
for (sd = smg; sd->a != NULL; ++sd)
{
for (ed = sd->a; ed->p != NULL; ++ed)
{
if (DRA == sd->z)
{
/*P Increment the clear-state buffer size */
c += 1 + ed->r;
}
}
}
return c;
}
int main(void)
{
unsigned int rVal = 0;
struct two_d smg[2]={
//
// [0].a ={1,0},
// [0].z =DRA,
// [1].a={1,0},
// [1].z =DRA,
};
rVal = getSmg(smg);
printf("Return value is a %d\n", rVal);
printf("Return value is a l");
return( 0 );
}

Well, at least this compiles... I'm not game to run it, though...
For what it's worth...
enum sid { DRB, DRA, DRAwhoCares };
typedef struct {
unsigned int r;
unsigned int *p;
} oneD_t;
typedef struct {
oneD_t *a;
enum sid z;
} twoD_t;
unsigned int getSmg( twoD_t *smg ) {
unsigned int c = 0;
for( twoD_t *sd = smg; sd->a != NULL; +sd++ ) {
for( oneD_t *ed = sd->a; ed->p != NULL; ed++ ) {
if( DRA == sd->z ) {
/*P Increment the clear-state buffer size */
c += 1 + ed->r;
}
}
}
return c;
}
int main( void ) {
oneD_t foo[] = { { 1, NULL }, /* ... */ };
oneD_t bar[] = { { 1, NULL }, /* ... */ };
twoD_t smg[]={
{ foo, DRA, },
{ bar, DRA, },
{ NULL, DRAwhoCares, },
};
unsigned int rVal = getSmg( smg );
printf( "Return value: %u\n", rVal );
return 0; // return is not a function call... No parenthesis...
}

Related

How can i find error in my code for the question for parenthesis matching? (C language)

Question is to to check in the character array if the parenthesis is matched or not using stack.
In my code i am not getting any output nor any error so i am unable to find my mistake.
At first i have made a structure for stack.
Then i have made functions to check whether the stack is empty or full to prevent conditions such as stack overflow or underflow.
Then i have made function for parenthesis checker
HERE IS MY CODE:
#include <stdio.h>
#include <stdlib.h>
//Initializing the stack with structures
struct stack
{
int size;
int top;
char *arr;
};
//function to check whether stack is empty
int isEmpty(struct stack *ptr)
{
if (ptr->top == -1)
{
return 1;
}
else
{
return 0;
}
}
//function to check whether stack is full
int isFull(struct stack *ptr)
{
if (ptr->top == (ptr->size - 1))
{
return 1;
}
else
{
return 0;
}
}
//Function for push
void push(struct stack *ptr, char val)
{
if (isFull(ptr))
{
printf("Stack Overflow, Cannot push more elements\n");
}
else
{
ptr->top++;
ptr->arr[ptr->top] = val;
}
}
//Function for pop
char pop(struct stack *ptr)
{
if (isEmpty(ptr))
{
printf("Stack Underflow, Unable to pop elements\n");
return -1;
}
else
{
char val;
val = ptr->arr[ptr->top];
ptr->top--;
return val;
}
}
//Function for parenthesis matching
int parenthesisChecker(char *exp)
{
struct stack *st;
st->size = 100;
//stack is empty for now
st->top = -1;
st->arr = (char *)malloc(st->size * sizeof(char));
int n_push = 0, n_pop = 0;
for (int i = 0; exp[i] != '\0'; i++)
{
//for open bracket push
if (exp[i] == '(')
{
push(st, '(');
n_push++;
}
//for closed bracket pop
else if (exp[i] == ')')
{
if (isEmpty(st))
{
return 0;
}
else
{
pop(st);
n_pop++;
}
}
}
printf("%d times push\n", n_push);
printf("%d times pop\n", n_pop);
if (isEmpty(st))
{
return 1;
}
else
{
return 0;
}
}
int main()
{
char *c = "akajvd)(()";
if (parenthesisChecker(c))
{
printf("Parenthesis is matched");
}
else
{
printf("Parenthesis is not matched");
}
return 0;
}
The pointer st within the function parenthesisChecker is not initialized and has an indeterminate value
struct stack *st;
So dereferencing the pointer like for example in this statement
st->size = 100;
invokes undefined behavior.
Also the function produces a memory leak because it does not free the memory allocated for the data member arr of the structure struct stack.
The function parameter should have the qualifier const because the passed string is not being changed within the function.
int parenthesisChecker( const char *exp );
And such functions as pop and push should not output any message. It is the caller of the functions that decides whether to output a message.
I would write the program the following way.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stack
{
size_t size;
size_t top;
char *arr;
};
struct stack make_stack( size_t size )
{
struct stack st = { .size = size, .top = 0, .arr = malloc( size ) };
if ( st.arr == NULL ) st.size = 0;
return st;
}
void free_stack( struct stack *st )
{
free( st->arr );
st->size = 0;
st->top = 0;
}
int isEmpty( const struct stack *st )
{
return st->top == 0;
}
int isFull( const struct stack *st )
{
return st->top == st->size;
}
int push( struct stack *st, char val )
{
int success = !isFull( st );
if ( success )
{
st->arr[st->top++] = val;
}
return success;
}
int pop( struct stack *st, char *val )
{
int success = !isEmpty( st );
if ( success )
{
*val = st->arr[--st->top];
}
return success;
}
int parenthesisChecker( const char *s )
{
int success = 1;
if ( *s != '\0' )
{
struct stack st = make_stack( strlen( s ) );
success = st.size != 0;
for ( ; success && *s; ++s )
{
if ( *s == '(' )
{
success = push( &st, *s );
}
else if ( *s == ')' )
{
char c;
success = pop( &st, &c );
}
}
success = success && isEmpty( &st );
free_stack( &st );
}
return success;
}
int main(void)
{
const char *s = "akajvd)(()";
if ( parenthesisChecker( s ) )
{
puts( "Parentheses are matched" );
}
else
{
puts( "Parentheses are not matched" );
}
return 0;
}
The program output is
Parentheses are not matched

Othello Minimax Algorithm not working

I am trying to make a minimax algorithm, but my function does not return the correct position. It returns the deepest node. I would like it to return the best possible move. Here is my code:
pos minimax(game* g, strategy_config sc)
{
int points = 0;
sc.minimax_config.heuristic(g, sc.minimax_config.hc);
pos p, p2;
int search_depth = sc.minimax_config.ply;
for (p.r = 0; p.r < g->b->nrows; p.r++)
{
for (p.c = 0; p.c < g->b->ncols; p.c++)
{
game* copy = g;
apply_move(copy, p);
if (sc.minimax_config.heuristic(copy, sc.minimax_config.hc)
> points && sc.minimax_config.ply > 0)
{
if (sc.minimax_config.ply == search_depth)
{
p2 = p;
}
sc.minimax_config.ply = sc.minimax_config.ply - 1;
minimax(copy, sc);
}
}
}
return p2;
}
And here are the relevant structs:
struct edge_corner_weight {
unsigned int edge_weight;
unsigned int corner_weight;
};
union heuristic_config {
unsigned int edge_weight;
struct edge_corner_weight edge_corner_weight;
};
typedef union heuristic_config heuristic_config;
struct minimax_config {
int (*heuristic)(game*, heuristic_config);
heuristic_config hc;
unsigned int ply;
};
typedef struct minimax_config minimax_config;
union strategy_config {
minimax_config minimax_config;
};

Member reference type issue

Hi everyone I'm having a problem with my code and I really don't know how to fix it.
It's telling me that member reference type 'Word'(aka 'struct dict_word *') is not a structure or a union.
I'm trying to change my struct dict_word to word as as you can see on my typedef but when I do it it's giving me that error.
Please have a look at my code I would really appreciate if you could explain that to me.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct dict_word *word;
typedef struct node *Node;
typedef struct double_linked_list *DLL;
struct dict_word
{
char words[100];
int year[10];
char eng_synonyms[100];
char heb_synonyms[100];
};
struct node
{
word data;
Node *next;
Node *previous;
};
struct double_linked_list
{
Node *head;
Node *last;
};
int SpliString(struct dict_word* entry, const char *str) // Here is where I'm trying to change struct dict_node to word
{
long sz,j,k;
int yearIndex;
char *buffer;
char *endOfYears;
char *endOfYear;
char *endOfDefinition;
char *endOfWord = strstr(str, "_#_");
//Sets the first num bytes of the block of memory pointed by ptr
//to the specified value (related as an unsigned char)
memset(entry, 0, sizeof(struct dict_word));
if (endOfWord)
{
sz = endOfWord - str;
strncpy(entry->words, str, sz);
endOfYears = strstr(endOfWord+3, "_#_");
if (endOfYears)
{
sz = endOfYears - (endOfWord+3);
buffer = endOfWord+3;
yearIndex = 0;
j = 0;
while(yearIndex<10 && buffer+j<endOfYears)
{
entry->year[yearIndex] = atoi(buffer+j);
// check year for negative...
if (entry->year[yearIndex]<=0)
return 0;
// Locating substring
endOfYear = strchr(buffer+j, '_');
if (endOfYear)
{
j = endOfYear - buffer;
j++;
yearIndex++;
}
else
{
break;
}
}
endOfDefinition = strstr(endOfYears+3, "_#_");
if (endOfDefinition)
{
sz = endOfDefinition - (endOfYears+3);
k = 0;
for(j=0; j<sz; j++)
{
if (endOfYears[j+3]==',') //Q11: what's j+3?
//A11: skips _#_
{
entry->eng_synonyms[k] = ' ';
k++;
}
else if (endOfYears[j+3]>='a' && endOfYears[j+3]<='z')
{
entry->eng_synonyms[k] = endOfYears[j+3];
k++;
}
else if (endOfYears[j+3]!='_')
{
return 0;
}
}
k = 0;
sz = (str+strlen(str)) - (endOfDefinition+3);
for(j=0; j<sz; j++)
{
if (endOfDefinition[j+3]==',')
{
entry->heb_synonyms[k] = ' ';
k++;
}
else if (endOfDefinition[j+3]>='A' && endOfDefinition[j+3]<='Z')
{
entry->heb_synonyms[k] = endOfDefinition[j+3];
k++;
}
else if (endOfDefinition[j+3]!='_')
{
return 0;
}
}
}
// check for legality
for(j=0;j<(int)strlen(entry->words);j++)
{
if (entry->words[j]<'a' || entry->words[j]>'z')
return 0;
}
return 1;
}
}
return 0;
}

how to access first element of a struct array

So I implemented the following method. The problem is that when I begin
searching the variableVector pointer I noticed that variableVector->variables
might not be pointing to the beginning variable element.
Variable* findVariable(VariableVector *variableVector,
char *variableNameOfVariableToReturn) {
if (variableVector->size < 1) {
return NULL ; // since variableVector is empty
}
Variable *currentVariable = variableVector->variables;//<== HOW TO RESET TO BEGINNING???
int numberOfVariablesInVariableVector = variableVector->size;
for (int i = 0; i < numberOfVariablesInVariableVector; i++) {
if (strcmp(currentVariable->variableName,
variableNameOfVariableToReturn) == 0) {
return currentVariable;
} else {
currentVariable++;
}
}
return NULL ; // variable not found in variableVector
}
These are what my structs look like:
struct _Variable {
char *variableName;
char *arrayOfElements;
int32_t address;
};
typedef struct _Variable Variable;
struct _VariableVector {
int size; // elements full in array
int capacity; // total available elements
Variable *variables;
};
typedef struct _VariableVector VariableVector;
Also this is how I add a new variable:
bool appendVariable(VariableVector *variableVector, Variable *variable) {
if (variableVector->size == variableVector->capacity) {
return false;
} else { // append since vector is not full
int indexOfFirstEmptyElement = variableVector->size;
memcpy(&variableVector->variables[indexOfFirstEmptyElement], variable, sizeof(Variable));
//variableVector->variables[indexOfFirstEmptyElement] = *variable;
variableVector->size++;
return true;
}
}

Setting struct value = segfault

#include <stdio.h>
#include <stdlib.h>
#define true 1
struct hashRow {
char *key;
char *value;
};
struct hash_table {
int max;
int number_of_elements;
struct hashRow **elements;
};
int hashstring(const char *s)
{
int key = 0;
while (*s)
key = key * 37 + *s++;
return key;
}
int hash_fun(int key, int try, int max) {
return (key + try) % max;
}
struct hash_table *table;
int hash_insert(struct hashRow *data, struct hash_table *hash_table) {
int try, hash;
if(hash_table->number_of_elements < hash_table->max) {
return 0; // FULL
}
for(try = 0; true; try++) {
int hkey = hashstring(data->key);
hash = hash_fun(hkey, try, hash_table->max);
if(hash_table->elements[hash] == 0) { // empty cell
hash_table->elements[hash] = data;
hash_table->number_of_elements++;
return 1;
}
}
return 0;
}
struct hashRow *hash_retrieve(char *key, struct hash_table *hash_table) {
int try, hash;
for(try = 0; true; try++) {
int hkey = hashstring(key);
hash = hash_fun(hkey, try, hash_table->max);
if(hash_table->elements[hash] == 0) {
return 0; // Nothing found
}
if(hash_table->elements[hash]->key == key) {
return hash_table->elements[hash];
}
}
return 0;
}
int hash_delete(char *key, struct hash_table *hash_table) {
int try, hash;
for(try = 0; true; try++) {
int hkey = hashstring(key);
hash = hash_fun(hkey, try, hash_table->max);
if(hash_table->elements[hash] == 0) {
return 0; // Nothing found
}
if(hash_table->elements[hash]->key == key) {
hash_table->number_of_elements--;
hash_table->elements[hash] = 0;
return 1; // Success
}
}
return 0;
}
void insertsomething()
{
struct hashRow *toInsert;
toInsert = (struct hashRow *)malloc(sizeof(*toInsert));
printf("toInsert declared\n");
char *k = (char*)malloc(sizeof(char*));
char *v = (char*)malloc(sizeof(char*));
k = "sayhello";
v = "hello";
this is where I seem to be having the problem.
toInsert->key = k;
toInsert->value = v;
hash_insert(toInsert, table);
}
int main()
{
printf("calling insertsomething.\n");
insertsomething();
struct hashRow *gotten;
gotten = hash_retrieve("sayhello", table);
printf("test: %s\n", gotten->value);
}
I'm trying to create a hash table, but whenever I try to set a value in the toInsert struct pointer it segfaults. Can someone explain to me what I am doing wrong?
Try this:
void insertsomething()
{
struct hashRow *toInsert;
toInsert = (struct hashRow *)malloc(sizeof(*toInsert));
printf("toInsert declared\n");
/*
char *k = (char*)malloc(sizeof(char*)); // wrong size
char *v = (char*)malloc(sizeof(char*)); // wrong size
k = "sayhello"; // bad assignment
v = "hello"; // bad assignment
*/
toInsert->key = strdup("sayhello");
toInsert->value = strdup("hello");
hash_insert(toInsert, table);
}
Also, I can't spot where you reserve memory for your hash_table. Is it hidden somewhere else??

Resources