I'm trying to implement/understand stacks and I keep getting "value undeclared" for something that is declared inside the struct that is supposed to represent the stack
#define EmptyTOS ( -1 )
#define MinStackSize ( 5 )
typedef struct StackRecord *Stack;
struct StackRecord
{
int Capacity;
int TopOfStack;
int *Array;
};
Stack CreateStack( int MaxElements )
{
Stack S;
S = malloc( sizeof( struct StackRecord ) );
S->Array = malloc( sizeof( int ) * MaxElements );
S->Capacity = MaxElements;
MakeEmpty( S );
return S;
}
void MakeEmpty( Stack S ){
S->TopOfStack = EmptyTOS;
}
void Push( int X, Stack S ){
S->Array[++TopOfStack] = X;
}
int main(){
Stack s1 = CreateStack(10);
return 0;
}
If I try to compile just this I get: In function ‘Push’: error: ‘TopOfStack’ undeclared
I don't understand why
It is because TopOfStack is not declared.
If you want to access the member variable of the object pointed at by S, you should write S->TopOfStack.
Related
im trying to make an array of struct and initialize struct array member, but I don't know how to access struct member, i used (st->ch)[t] = 'c'; and others similar syntax but i did not succeed.
best regards.
struct ST
{
char ch;
};
bool init(ST* st, int num)
{
st = (ST*)malloc(num * sizeof(ST));
if (st == NULL) return false;
for (int t = 0; t < num; t++) (st->ch)[t] = 'c';
return true;
}
int main()
{
ST* s = NULL;
init(s, 2);
putchar(s[1].ch);
}
You declared in main a pointer
ST* s = NULL;
that in C shall be declared like
struct ST* s = NULL;
because you declared the type specifier struct ST (that in C is not the same as just ST)
struct ST
{
char ch;
};
that you are going to change within a function. To do that you have to pass the pointer to the function by reference. That is the function declaration will look at least like
bool init( struct ST **st, int num );
and the function is called like
init( &s, 2);
if ( s ) putchar( s[1].ch );
The function itself can be defined like
bool init( struct ST **st, int num )
{
*st = malloc( num * sizeof( struct ST ) );
if ( *st )
{
for ( int i = 0; i < num; i++) ( *st )[i].ch = 'c';
}
return *st != NULL;
}
If you are using a C++ compiler then substitute this statement
*st = malloc( num * sizeof( struct ST ) );
for
*st = ( struct ST * )malloc( num * sizeof( struct ST ) );
When the array of structures will not be needed you should free the memory occupied by the array like
free( s );
You can access struct member using following:
st[t].ch
As mentioned by #kaylum st being a local variable in the init() and doesn't update the variable s in the main function hence an alternative could be you either pass the add the address of the variable s to init() or could just return the allocated memory as shown in the code snippet below. Instead of using bool as return type to check you can use the ST* as return type and if it returns NULL or mem address to get mem alloc status.
Also you would have to typedef the struct typedef struct ST ST; to be able to directly use the type as ST else you would have to stick to using struct ST
typedef struct ST
{
char ch;
}ST;
ST* init(int num)
{
ST *st;
// Create num elems of ST type
st = (ST*)malloc(num * sizeof(ST));
// return NULL is st unintialised
if (st == NULL) {
return st;
}
// Assign ch member variable of the 't'th st element wit 'c'
for (int t = 0; t < num; t++) {
st[t].ch = 'c';
}
return st;
}
int main()
{
ST* s;
// creates an array of size two of type st
s = init(2);
putchar(s[1].ch);
return 0;
}
In this implementation of stack program in C, when i print the value of pop(),why do i get that number? It should have printed '4' but instead i get an address like number. What might be the problem here?
#define MAX 5
typedef struct stack{
int data[MAX];
int top;
}stack;
int empty(stack *s){
if(s->top==-1)
return 1;
return 0;
}
int pop(stack *s){
int x;
x = s->data[s->top];
s->top = s->top -1;
return x;
}
void display(stack *s){
while(!(empty(&s)) && (s->top)!=-1){
printf("%d\n",s->data[s->top]);
s->top=s->top-1;
}
}
int main()
{
stack s;
init(&s);
push(&s,2);
push(&s,3);
push(&s,4);
display(&s);
printf("Popped element is: ");
printf("%d",pop(&s));
return 0;
}
Output:
4
3
2
Popped element is: 4200976
Process returned 0 (0x0) execution time : 0.019 s
Press any key to continue.
After the display function your top will always have the value of -1.
When using the pop function it will return the -1'th element in the array.
This is undefined behaviour and so the returned x can be anything.
The function display is invalid.
For starters this call
!(empty(&s))
has the argument type stack ** while the parameter type is stack *. There should be
!(empty(s))
Though this check is redundant and may be removed.
And the function changes the data member top of the stack. As result the function pop called after the function display has undefined behavior.
The function can look like
void display(const stack *s)
{
for ( int i = s->top; i != -1; i-- )
{
printf("%d\n",s->data[i]);
}
}
Here is a demonstrative program
#include <stdio.h>
#define MAX 5
typedef struct stack
{
int data[MAX];
int top;
} stack;
void init( stack *s )
{
s->top = -1;
}
int empty( const stack *s )
{
return s->top == -1;
}
void push( stack *s, int x )
{
if ( s->top + 1 != MAX ) s->data[++s->top] = x;
}
int pop( stack *s )
{
int x = s->data[s->top--];
return x;
}
void display(const stack *s)
{
for ( int i = s->top; i != -1; i-- )
{
printf("%d\n",s->data[i]);
}
}
int main(void)
{
stack s = { { 0 }, -1 };
init( &s );
push (&s, 2 );
push( &s, 3 );
push( &s, 4 );
display( &s );
printf( "Popped element is: " );
printf( "%d\n", pop( &s ) );
return 0;
}
It yields the expected result
4
3
2
Popped element is: 4
I have created a struct:
typedef struct _POOL
{
int size;
void* memory;
}Pool;
and have then allocated space in the system memory for that structure but would like to return a pointer to the beginning of the allocated memory. I tried just returning the variable but got an error.
int main(void)
{
Pool* allocatePool(int n);
{
Pool *n = malloc(sizeof *n);
return n;
}
}
It seems you mean something like the following
#include <stdlib.h>
typedef struct _POOL
{
int size;
void* memory;
}Pool;
Pool * allocatePool( int n )
{
Pool *p = malloc( sizeof( Pool ) );
if ( p != NULL )
{
p->size = 0;
p->memory = malloc( sizeof( n ) );
if ( p->memory != NULL ) p->size = n;
}
return p;
}
int main(void)
{
int n = 10;
Pool *p = allocatePool( int n );
//...
if ( p != NULL ) free( p->memory );
free( p );
}
The function malloc is not declared because you missed to include the respective header stdlib.h. Thus, the compiler assumes an implicit declaration with a return type of int.
#include <stdio.h>
#include <stdlib.h>
int main()
{
typedef struct _POOL
{
int size;
void* memory;
} Pool;
Pool *p=(Pool*) malloc(sizeof(Pool));
return 0;
}
Here p is a pointer to the (first byte of the) allocated memory.
Code:
struct bunchofdata
{
int i;
void *dllist[i];
int spltq[i];
pthread_t tlist[i];
};
Errormsg:
error: ‘i’ undeclared here (not in a function)
void *dllist[i];
^
I can't understand why this doesn't work.
In addition to pikkewyn's answer, another way to implement this is to use Flexible Array Member
This makes it easier to manage than allocating members separately.
#include <stdio.h>
#include <stdlib.h>
typedef int pthread_t;
struct data
{
void *dl;
int spltq;
pthread_t thread;
};
struct bunchofdata
{
int i;
struct data data_list[];
};
struct bunchofdata * data_factory(int size)
{
struct bunchofdata * ret = malloc(sizeof(struct bunchofdata)
+size*sizeof(struct data));
/* fill in the members here*/
ret->i=size;
return ret;
}
int main(void) {
struct bunchofdata *data10=data_factory(10);
data10->data_list[9].spltq=0;
printf("data10->data_list[9].spltq=%d",data10->data_list[9].spltq);
free(data10)
return 0;
}
You can use sth like this, although since each field of your structure is array it might be nicer to have array of such structs:
#include <malloc.h>
#include <pthread.h>
struct bunchofdata
{
int i;
void** dllist;
int* spltq;
pthread_t* tlist;
};
struct anotherbunchofdata
{
int i;
void* dll;
int spltq;
pthread_t tlist;
};
void init_bunchofdata( int size, struct bunchofdata* bd )
{
bd->i = size;
bd->dllist = malloc( size * sizeof( void* ) );
bd->spltq = malloc( size * sizeof( int ) );
bd->tlist = malloc( size * sizeof( pthread_t ) );
}
void free_bunchofdata( struct bunchofdata* bd )
{
free( bd->dllist );
free( bd->spltq );
free( bd->tlist );
}
int main()
{
struct bunchofdata bd;
init_bunchofdata( 5, &bd );
free_bunchofdata( &bd );
return 0;
}
I have this structure here:
typedef struct _open {
int x;
struct _open *next;
} *NODE;
And on my main function I declared this pointer:
NODE open = initOpen(size);
Here's the initOpen function:
NODE initOpen(int size) {
return (NODE)malloc(sizeof(struct _open)*size);
}
I this correct? can I access my array in the main function like: open[0] to open[9] ?
First of all, the way you are doing dynamically allocated array is wrong.
I'm not sure if you actually want the thing you wrote, which is linked list, or the thing you said, which is dynamically allocated array.
Below is how you should do dynamically allocated array. Hope it helps.
By doing so, you can add as many ints into the array as you want, before you run out of memory. And you can access the array using array notation but with a pointer first: darray->array[0]
Your linked list, however, can not be accessed with this syntax.
#include <stdio.h>
#include <stdlib.h>
#define INITSIZE 8
typedef struct dyarr{
int num;
int max;
int *array;
}arr;
arr* makeArr();
void add( arr*, int );
int main( int argc, char const *argv[] ){
int t;
arr* darray = makeArr();
while( scanf( "%d", &t ) != EOF ){
add( darray, t );
}
int i;
for( i = 0; i<darray->num; i++ ){
printf( "%d\n", darray->array[i] );
}
getchar();
return 0;
}
arr* makeArr(){
arr* A = malloc( sizeof( arr ) );
A->max = MAXSIZE;
A->num = 0;
A->array = malloc( sizeof( int )*A->max );
return A;
}
void add( arr* a, int i ){
if( a->num == a->max ){
a->max *= 2;
a->array = realloc( a->array, a->max );
}
a->array[a->num++] = i;
}
First of all, you should respect some conventions:
typedef struct node {
int x;
struct node *next;
} *nodePtr;
Second, what is the usage of the parameter size ?
According to me the right way to allocate a new nodePtr is:
nodePtr initNodePtr() {
return (nodePtr)malloc(sizeof(struct node));
}
Also dont forget to release memory after usage:
nodePtr node = initNodePtr();
...
...
free(node); //should be wrapped in a function to respect design.
To Create an array of structure, you should do the following:
typedef struct {
int x;
node* next;
} node;
int main() {
node* nodeArray = (node*)malloc(sizeof(node)*50); // 50 = size of your array
...
// do whatever you want
...
free(nodeArray);
}
Not tested, let me know if errors.