What am I doing wrong? (C programming, pointers, structs, functions) - c

I am unsure if my use of malloc is correct, but what bother's me is the inability to pass the struct into the put_age() function pointer. It looks right to me but apparently it isn't.
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int age;
// NPC methods
int (*put_age)(NPC *character, int age);
} NPC;
////////////////////////////////////
int set_age(NPC *character, int age);
int main(){
NPC *zelda = malloc(sizeof(NPC));
zelda->put_age = set_age;
zelda->put_age(zelda, 25);
printf("Zelda's age is %d\n", zelda->age);
return 0;
}
int set_age(NPC *character, int age){
character->age = age;
return 0;
}
COMPILER OUTPUT:
$ gcc ~/test.c
/test.c:7:21: error: expected ‘)’ before ‘*’ token
/test.c:8:1: warning: no semicolon at end of struct or union
/test.c: In function ‘main’:
/test.c:16:8: error: ‘NPC’ has no member named ‘put_age’
/test.c:17:8: error: ‘NPC’ has no member named ‘put_age’

Your problem is that NPC isn't the name of a type until the declaration of the struct typedef is complete. You can change this by giving the struct a name, e.g.
typedef struct tagNPC {
int age;
// NPC methods
int (*put_age)(struct tagNPC *character, int age);
} NPC;
or
typedef struct tagNPC NPC;
struct tagNPC {
int age;
// NPC methods
int (*put_age)(NPC *character, int age);
};

I don't think you can use typedef "NPC" inside the struct def. That's because until the compiler has not seen the closing "}" , it has no idea what NPC is.
Please try changing:
typedef struct{
int age;
// NPC methods
int (*put_age)(NPC *character, int age);
} NPC;
to:
typedf struct node_npc NPC;
struct node_npc
{
int age;
int (*put_age)(NPC *character, int age);
};

Try changing this:
int set_age(NPC *character, int age){
zelda->age = age;
return 0;
}
To:
int set_age(NPC *character, int age){
character->age = age;
return 0;
}

In set_age(), your variable's name is character, not zelda, so the code should be:
int set_age(NPC *character, int age){
character->age = age;
return 0;
}

I had that problem, when I had a constant defined someware in my code that was named like a member of a struct. Ex.
#define N 10
struct my_struct{
int N;
};

Related

Why does my char array not print anything?

In c I am trying to assign a char array inside a struct with a user provided value, here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct person
{
char name[20];
int age;
};
struct person *assign(char arr[], int age)
{
struct person *x = malloc(sizeof(struct person));
x->name[20] = arr[20];
x->age = 21;
return x;
}
int main()
{
char name[20] = "Arthur morgan";
int age = 34;
struct person* person1 = assign(name, age);
printf("name: %s\n", person1->name);
printf("age: %d\n", person1->age);
return 0;
}
The problem is that the name prints nothing for some reason, the age however prints as expected.
Why is the name not printing correctly?
x->name[20] = arr[20];
It does not copy the array
It copies 1 character and you are accessing array outside its bounds which is undefined behaviour (UB)
It is better to use objects not types in sizeof
Always check the result of malloc
You need to copy the string using strcpy function
struct person *assign(char arr[], int age)
{
struct person *x = malloc(sizeof(*x));
if(x)
{
strcpy(x->name,arr);
x->age = 21;
}
return x;
}
https://godbolt.org/z/vKddb4b9a

I tried to allocate memory using malloc in a structure but it didn't work?Why?

## Code to read general information ##
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct{
char *name =(char*)malloc(20);
int age;
int id;
}info;
main()
{
info a;
printf("Enter Name :");
scanf(" %[^\n]",a.name);
a.age=19;
a.id=11700055;
printf("Name :%s\nAge :%d\nId :%d\nSize of info
:%d\n",a.name,a.age,a.id,sizeof(a));
return 0;
}
https://i.stack.imgur.com/WoA0T.png
what is wrong with this code?
it's showing errors i don't understand like info has no member named 'name'?
it also says that name,age,id are not the members of info.
Inside struct declaration you are allocating memory that is not allowed.
If you need array inside of it
typedef struct{
char name[20];
int age;
int id;
}info;
Alternatively you can do this
#define MAXLEN 20
typedef struct{
char* name;
int age;
int id;
}info;
info p;
p.name = malloc(MAXLEN);
if(!p.name){ perror("malloc");exit(1);}
...
It should be int main(void) not main().

How can i access variables in structs in C to print?

**> Is there a way to access a variable that come from other struct? When
i try this code,i am getting this compile error.
**
test.c: In function ‘readRecordsFromFile’:
test.c:70:18: error: expected expression before ‘kdnode’
printf(" %f\n",kdnode.data.latitude);
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <math.h>
#define rec_size 112
typedef struct _Node kdnode;
typedef struct _Record record;
static void readRecordsFromFile(char *filename);
struct _Record{
int plateNumber;
long *name[32];
double area;
int population;
int density;
int popcitycenter;
long region;
double latitude;
double longtitude;
};
struct _Node
{
//kdnode left;
//kdnode right;
record data;
bool type;
double x;
double y;
int pagenumber;
};
int main(){
readRecordsFromFile("data.dat");
return 0;
}
static void readRecordsFromFile(char *filename)
{
FILE* inputFile;
inputFile = fopen(filename, "rb");
int i;
if(!inputFile) {
printf("Could not open file");
return;
}
int length,record_count;
fseek(inputFile,0,SEEK_END);
length=ftell(inputFile);
fseek(inputFile,0,SEEK_SET);
record_count = length/sizeof(record);
kdnode kd;
fread(&kd,rec_size,2,inputFile);
printf("%d",ftell(inputFile));
for (i = 0; i < record_count; i++)
{
printf(" %f\n",kdnode.data.latitude);
}
fclose(inputFile);
}
typedef struct _Node is typedefed as knode. knode represents a data type and it's not an identifier, so this
printf(" %f\n",kdnode.data.latitude);
has to be
printf(" %f\n", kd.data.latitude);
You should also check return values for functions like fread() for example.

i can't assign one struct to another in c

i have 2 structs, i want to assign one struct to another, but when i print the results, it prints crap, the functions : "ver_tope" is on charge to do that , what am i doing bad?, here is the code:
#include <stdio.h>
#include <stdlib.h>
#define TAM 4
typedef struct{
char nomyap[40];
int edad;
}t_info;
typedef struct {
t_info pila [TAM];
int tope;
}t_pila;
void ver_tope(const t_pila *p, t_info *d);
int main()
{
t_pila pila;
t_info info;
//I CHARGE BOTH STRUCTS
ver_tope(&pila, &info);
return 0;
}
void ver_tope(const t_pila *p, t_info *d)
{
*d = p->pila[(p->tope)-1];
return ;
}
Try adding an initialisation for pila.tope in main() ex:
... //I CHARGE BOTH STRUCTS
pila.tope =2;
ver_tope(&pila, &info);
...
That stopped the segmentation fault...
int main()
{
t_pila pila;
t_info info;
ver_tope(&pila, &info);
return 0;
}
You have not initialized either variable. Since pila is the source of the assignment you can do the following:
int main()
{
t_pila pila = { 0 };
pila.tope = 1;
t_info info;
ver_tope(&pila, &info);
return 0;
}
Here I default initialized pila and then set its tope member to 1. I did not initialize info since ver_tope assigns to it. It would be clearer if you converted ver_tope into a function that returned t_info.

Expected expression before error

I've been working on this project for a while and I wanted to test it, but I keep getting this error and I have no idea what to do and I am very confused. Here is my code:
typedef struct{
int nr_pages;
int id;
int a,b;
int aux;
}information;
int main(){
int i;
i = information.b;
//and more stuff happens
}
The error that I am always getting is "Expected expression before 'information'" exactly where I declare i = information.b
What am I doing wrong?
You need to instantiate the structure before using it. Try:
typedef struct{
int nr_pages;
int id;
int a,b;
int aux;
}information;
int main(){
information info;
info.b = 0;
info.a = 0;
...
etc
...
int i = information.b;
//and more stuff happens
}
You declare information as a type, not a variable. This is what the typedef is for.
And i = ... in the C terminology is not a declaration, but an assignment.

Resources