expected declaration specifier error , when declaring an external stack - c

There are three files :
test.c
#include "stack.h"
stackT s2;
StackInit(&s2, 15);
int main(){
stackT s1;
StackInit(&s1, 10);
StackDestroy(&s1);
return 0;
}
stack.h
typedef char stackElementT;
typedef struct {
stackElementT *contents;
int top;
int maxSize;
} stackT;
void StackInit(stackT *stackP, int maxSize);
void StackDestroy(stackT *stackP);
stack.c
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
void StackInit(stackT *stackP, int maxSize)
{
stackElementT *newContents;
newContents = (stackElementT *)malloc(sizeof(stackElementT) * maxSize);
if (newContents == NULL) {
fprintf(stderr, "Insufficient memory to initialize stack.\n");
exit(1);
}
stackP->contents = newContents;
stackP->maxSize = maxSize;
stackP->top = -1;
}
void StackDestroy(stackT *stackP)
{
free(stackP->contents);
stackP->contents = NULL;
stackP->maxSize = 0;
stackP->top = -1;
}
I really need to have an external stack and
stackT s2;
StackInit(&s2, 15);
in test.c is my attempt to declare that but compiler gives the following error.
test.c:4:11: error: expected declaration specifiers or ‘...’ before ‘&’ token
StackInit(&s2, 15);
^
test.c:4:16: error: expected declaration specifiers or ‘...’ before numeric constant
StackInit(&s2, 15);
^~
Here is what I have tried:
I declared stack s1 inside the main function and didn't get any errors for that.
I deleted #include "stack.h" in test.c and I got
the same error for the external stack s2.
So my questions are:
What is the error for? How can I declare the external stack without any errors?

You can't call functions at top-level in C, you can only have declarations and definitions. Move the call to StackInit() into the main() function.
#include "stack.h"
stackT s2;
int main(){
stackT s1;
StackInit(&s1, 10);
StackInit(&s2, 15);
StackDestroy(&s1);
StackDestroy(&s2);
return 0;
}

A function can only be called from another function. Imagine functions call like a tree in which the root node is the main() function.
Anyway, besides moving the initialization inside main(), if you really want the struct variable definition outside main you can statically initialize it, just doing what StackInit() would do: a stackElementT array of size 15, contents field pointing to the first element, and the top index initialized to -1.
#include "stack.h"
stackElementT elements[15];
stackT s2 = { elements, -1, 15};
int main(){
stackT s1;
StackInit(&s1, 10);
StackDestroy(&s1);
return 0;
}

Related

Creating pointer to a typedef stack

I am not able to initialize all three pointers to struct S, and I don't know why.
I am using a fixed-length array as stack to store values.
The header file is created this way to hide information (struct S), and should be kept as generic as possible.
main.c
// main.c
#include <stdio.h>
#include "stack_exercise4.h"
int main(void) {
Stack *stack_1, *stack_2, *stack_3;
int a, b;
make_empty(stack_1);
make_empty(stack_2);
make_empty(stack_3);
return 0;
}
Problem is, after Stack *stack_1, *stack_2, *stack_3, only stack_2 has a valid address for Struct stack. stack_1 and stack_3 have some strange looking addresses, and I can't assign any values to stack_1->top, nor stack_3->top. What is the problem?
header file
// stack_exercise4.h
#ifndef STACK_EXERCISE4_H
#define STACK_EXERCISE4_H
#include <stdbool.h> /* C99 only */
typedef struct S Stack; /* incomplete type to hide the content
of S. */
void make_empty(Stack *s);
bool is_empty(const Stack *s);
bool is_full(const Stack *s);
void push(Stack *s, int i);
int pop(Stack *s);
#endif
stack source file
// stack_exercise4a.c
#include "stack_exercise4.h"
#include <stdio.h>
#define MAX_STACK_SIZE (10)
struct S {
int top;
int contents[MAX_STACK_SIZE];
};
void make_empty(Stack *s) {
s->top = 0;
}
bool is_empty(const Stack *s) {
return (s->top <= 0);
}
bool is_full(const Stack *s) {
return (s->top >= MAX_STACK_SIZE - 1);
}
void push(Stack *s, int i) {
if (!is_full(s)){
(s->contents)[s->top++] = i;
} else {
printf("Failed to push, Stack is full.\n");
}
}
int pop(Stack *s) {
return (s->contents)[s->top--];
}
The stack pointers must point on memory spaces before being dereferenced in make_empty(). Something like this could be the starting point: make_empty() allocates the memory space.
void make_empty(Stack **s) {
(*s) = (struct S *)malloc(sizeof(struct S));
(*s)->top = 0;
}
And so the initialization of the pointers would be:
make_empty(&stack_1);
make_empty(&stack_2);
make_empty(&stack_3);
Declare stack_X on stack instead.
#include <stdio.h>
#include "stack_exercise4.h"
int main(void) {
Stack stack_1 = {0}, stack_2 = {0}, stack_3 = {0};
int a, b;
make_empty(&stack_1);
make_empty(&stack_2);
make_empty(&stack_3);
return 0;
}
Otherwise, I't would need to have constructor/destructor for your Stack data structure e.g new_stack(Stack *ptr) del_stack(Stack *ptr). For beginner, I would recommend to use stack instead of heap (stay away from malloc).

Define a function pointer to be32toh() function

I'm newly learned about function pointers here but I couldn't define a function pointer to be32toh() or other functions of endian.h header.
First of all, I can do what is told in the given thread:
#include <endian.h>
int addInt(int n, int m) {
return n+m;
}
int main(){
int (*functionPtr)(int,int);
functionPtr = addInt;
return 0;
}
But when I try to do the same for a function like be32toh(), I'll get a compilation error:
#include <stdint.h>
#include <endian.h>
int addInt(int n, int m) {
return n+m;
}
int main(){
int (*functionPtr)(int,int);
functionPtr = addInt;
uint32_t (*newptr)(uint32_t);
newptr = &be32toh;
return 0;
}
Compile as:
$ gcc test.c
Result is as below:
test.c: In function ‘main’:
test.c:15:15: error: ‘be32toh’ undeclared (first use in this function)
15 | newptr = &be32toh;
| ^~~~~~~
test.c:15:15: note: each undeclared identifier is reported only once for each function it appears in
What's the problem and how to fix it?
What's the problem
be32toh is a macro.
how to fix it?
Just write the function yourself.
uint32_t be32toh_func(uint32_t a) {
return be32toh(a);
}
....
newptr = &be32toh_func;

ADT (using a header file, source file and main file) in C

I am trying to create a simple ADT using a structure that takes 2 dates. Then returns an age. It must use a Header file, a source file for the Header file, and a main file.
This is what I have it runs and nothing happens. Can someone tell me what i am doing wrong?
age.h
#ifndef AGE_H_
#define AGE_H_
typedef struct getage * Age;
#define MAX 5
Age get_Age(int birthYear, int yearNow);
void age_Destroy(Age a);
#endif
age.c
#include <stdio.h>
#include "age.h"
struct getage {
int birthYear;
int yearNow;
};
Age a[1];
Age get_Age(int birthYear, int yearNow){
int giveAge = 0;
giveAge = a[0]->yearNow - a[0]->birthYear;
printf("%d",giveAge);
return 0;
}
void age_Destroy(Age a){
free(a);
}
main.c
#include <windows.h>
#include <stdio.h>
#include "age.h"
void age_print(Age a);
void age_print(Age a){
printf("%d\n", &a);
}
int main() {
Age a;
get_Age(1986, 2020);
age_print(a);
printf("%d\n", &a);
system("pause");
//age_Destroy(a);
}
What are wrong:
In the function get_Age:
Instead of allocating structures, a[0] (global variable, initialized to NULL) is dereferenced.
0 (converted to NULL) is returned instead of returning an age.
In the function age_Destroy:
free() is used without declaration nor including proper header.
In the function age_print:
Data having wrong type is passed to printf(): %d requests int but Age* is passed.
In the function main:
The return value of get_Age is dropped.
Data having wrong type is passed to printf(): %d requests int but Age* is passed.
Fixed code that won't cause Segmentation Fault nor undefined behavior:
age.h (not changed)
#ifndef AGE_H_
#define AGE_H_
typedef struct getage * Age;
#define MAX 5
Age get_Age(int birthYear, int yearNow);
void age_Destroy(Age a);
#endif
age.c
#include <stdio.h>
#include <stdlib.h> // for malloc() and free()
#include "age.h"
struct getage {
int birthYear;
int yearNow;
};
Age get_Age(int birthYear, int yearNow){
Age a = malloc(sizeof(*a)); // allocate a structure
if (a == NULL) { perror("malloc"); exit(1); }
a->yearNow = yearNow; // assign data
a->birthYear = birthYear;
int giveAge = 0;
giveAge = a->yearNow - a->birthYear;
printf("%d",giveAge);
return a; // return pointer to the allocated structure
}
void age_Destroy(Age a){
free(a);
}
main.c
#include <stdlib.h> // more portable header for system()
#include <stdio.h>
#include "age.h"
void age_print(Age a);
void age_print(Age a){
printf("%p\n", (void*)a); // use valid combination of format and data
}
int main() {
Age a;
a = get_Age(1986, 2020); // assign the return value
age_print(a);
printf("%p\n", (void*)a); // use valid combination of format and data
system("pause");
age_Destroy(a); // enable freeing
}
(Some behavior may look weird, but I believe this is valid because not desired behavior is described.)

Return Pointer from function

I am new in C and literally trying to return pointer from my function to the pointer variable and have this "[Warning] assignment makes pointer from integer without a cast" no idea why compiler defines it as an int.
Can't declare my function before main as well, it throws this "undefined reference to `free_block'".
#include <stdio.h>
#include <stdlib.h>
struct block{
int num;
};
int main(int argc, char *argv[]) {
struct block *b;
b = free_block();
struct block *free_block(){
struct block *b = NULL;
return b;
}
return 0;
}
Thank you
Yea, my fault I know not too much about c syntax and had no idea about nested functions, soz.
But what could be wrong in this case:
I am trying to make my own memory allocator without using malloc or calloc functions. In my code I have the same Warning on the line with pointer = free_space_get(size);, here I have no more nested func(), my methods defined before main(), but still have no idea do I have to declare my functions or no, coz in the answer given to me it worked fine as soon as functions were defined before the main().
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct header{
size_t size;
struct header *next;
unsigned int free;
};
void *m_alloc(size_t size){
size_t total_size;
void *block;
struct header *pointer;
if(!size)
return NULL;
pointer = free_space_get(size);
if(pointer){
pointer->free = 0;
return (void*)(pointer + 1);
}
}
struct header *get_free_space(size_t size){
struct header *b = NULL;
return b;
}
int main() {
return 0;
}
Your code can be re-written as
#include <stdio.h>
#include <stdlib.h>
struct block{
int num;
};
struct block *free_block(){
struct block *b = NULL;
return b;
}
int main(int argc, char *argv[]) {
struct block *b;
b = free_block();
if(b == NULL) // Checking whether pointer is returned
printf("\n Recieved NULL \n");
return 0;
}

Why does C give this error ‘size’ undeclared (first use in this function)?

I am a beginner of c programming. I can to write my own malloc function and I put main method code one. It gives following error.
test.c: In function ‘main’:
test.c:38:30: error: ‘size’ undeclared (first use in this function)
test.c:38:30: note: each undeclared identifier is reported only once for each function it appears in
code
/*An horrible dummy malloc*/
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void *malloc(size_t size);
void *malloc(size_t size){
void *p;
p = sbrk(0);
//if sbrk dails , we return null
if(sbrk(size)==(void*)-1){
return NULL;
}
printf("wada\n");
return p;
}
typedef struct s_block *t_block;
struct s_block{
size_t size;
t_block next;
int free;
};
int main(){
malloc(50);
malloc(100);
t_block b;
b = sbrk(0);
sbrk(sizeof(struct s_block)+size);//Error line (code 1)
b->size = size; //Error Line
return 0;
}
In this line: sbrk(sizeof(struct s_block)+size) you use a variable size that you have not defined anywhere. This is clearly stated in the error message.
BTW you should call your function something instead of malloc.

Resources