i can't declare a pointer as a global variable [duplicate] - c

This question already has answers here:
use malloc out of main
(3 answers)
Closed 4 years ago.
I'm trying to run this program that manage login but I have a problem with declaring this pointer as a global variable , the error that it shows me is
"initializer element is not constant"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char nom_utilisateur[20];
char mot_de_passe[20];
char nom[20];
char prenom[20];
}USER;
USER *u =(USER *)malloc(sizeof(USER)*20);
int nbr_usr=0;
void adduser() {};
......

In C you cannot call functions during initialisation of global variables.
You need to do the initialisation for example in main:
...
USER *u;
...
int main()
{
u = malloc(sizeof(USER)*20);
...
}
BTW:
you don't need to cast the result of malloc.
the variable name u is not a good idea. Give it a meaningful name, e.g. users.
Not directly related to your question, but be aware that the 20 in the struct declaration below is not at all related to the 20 in malloc(sizeof(USER)*20).
typedef struct {
char nom_utilisateur[20];
char mot_de_passe[20];
char nom[20];
char prenom[20];
} USER;
in this struct declaration the 20 means that each user's password, nom, prenom etc. can have a length of 19 at most, 19 because strings are NUL terminated.
The 20 in malloc(sizeof(USER)*20) means that you can have at most 20 users.

The problem is not the declaration.
The problem is that you are initializating the pointer with a runtime information.
Think about malloc as something that can only be executed when the program is actually running. Such stuff must be placed in a function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char nom_utilisateur[20];
char mot_de_passe[20];
char nom[20];
char prenom[20];
}USER;
USER *u;
int nbr_usr=0;
void adduser() {};
void initialize(){
u = (USER *)malloc(sizeof(USER)*20);
//do all the other initializations here
}
int main(){
initialize();
return 0;
}

Related

C Declare array of struct/pointer to array of structs

I have an example tutorial with 2 files, "functions.c" and "functions.h" which contain the prototypes and the body of the functions.
In the example there isn't the main that containing the declaration of the array of struct/pointer to array of structs and the calls to the functions.
functions.c:
#include "functions.h"
const char *getTeamA(const sTest *p)
{
return p->teamA;
}
void setTeamA(sTest *p, char *s)
{
strcpy(p->teamA, s);
}
int getNum(const sTest *p)
{
return p->num;
}
void setNum(sTest *p, int i)
{
p->num = i;
}
functions.h:
#ifndef FUNCTIONS_H_
#define FUNCTIONS_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CHAR 20
#define SIZE 5
typedef struct {
char teamA[MAX_CHAR];
int num;
// ...
} sTest;
const char *getTeamA(const sTest *p);
void setTeamA(sTest *p, char *s);
int getNum(const sTest *p);
void setNum(sTest *p, int i);
#endif /* FUNCTIONS_H_ */
So my question is
How can i declare the struct according to the code written above?
So for example:
int main()
{
sTest data[SIZE]; //size isn't important
sTest *dataPtr = data;
setTeamA(dataPtr[0].teamA, "name1");
// ...
printf("%d", getNum(dataPtr[1].num)); // just an example. i know that it isn't initialized
// ...
return 0;
}
Is this the correct way? Or is there a better way to declare variables and pass them to the functions?
The important thing is that i have to stick to the code written in functions.c and functions.h, so the functions cannot directly modify the struct data, you need to use pointers (because there are member selection operator "->" in functions.c).
You don't need to have dataPtr. You can do the exact same thing by doing data[i], since you declared data as an array of sTests, and so data points to the first element in the array.
Let's deconstruct what you're doing when you're calling setTeamA(dataPtr[0].teamA, "name1"). You're trying to set the first sTest struct in the data array to have "name1" as the teamA field. Notice that the prototype for setTeamA() actually takes in a sTest *p. In your example, you're passing in the teamA field. So what you really want to call is setTeamA(&dataPtr[0], "name1"). This translates to the pointer pointing to the data at dataPtr[0].
While this works, as I said before, the dataPtr is unecessary. So this is equivalent to:
setTeamA(&data[0], "name1").
Also worth noting, you can simply write:
setTeamA(data, "name1")
since data is already a pointer to the first element in the array.
Use
setTeamA(&data[0], "name1")
It indexes to index 0 and then takes the reference (which is a pointer) of the result therefore making the type an sTest* then the setTeamA function will do it's job setting the teamA field.
That dataPtr variable is useless here.

How to call member of a struct using string declaration as representation of the actual member? [duplicate]

This question already has answers here:
Reflection support in C
(10 answers)
Closed 3 years ago.
My goal is to call a member of a struct without using the actual member. It sounds confusing but here's my sample code for further explanation:
#include <stdio.h>
#include <conio.h>
#include <string.h>
typedef struct record
{
char name[50];
}REC;
int main()
{
REC r;
char input[50] = "name"; //goal is to access r.name
char test1[50] = "Successful!";
r.input = test1; //This returns an error obviously
}
I declared char input to "name" as one of REC struct members. When compiled, error returns with "REC has no member named 'input'". How can i use 'input' to call one of rec struct members? Thank you in advance.
Like this, basically:
if (!strcmp(input, "name"))
strcpy(r.name, test1);
else
printf("Invalid field!\n");
C does not provide a way to access struct fields based on their name.
Perhaps you can think of more clever ways to write the above code, but whichever way you do it, you'll need to write a list of all the possible fields yourself.
I didn't figure out your goal. It seems that you want the member name of struct variable. But the member name if fixed when you define the struct. I only image maybe you have several different struct define. In that case, you can set struct member's value as following:
#include <stdio.h>
#define STR_SET(str,m,v) (str.m=(v))
#define MEM1 name
#define MEM2 age
typedef struct
{
char* name;
}REC_1;
typedef struct
{
char* age;
}REC_2;
int main(void)
{
REC_1 r1;
REC_2 r2;
char test1[50] = "Successful!";
STR_SET(r1, MEM1, test1);
STR_SET(r2, MEM2, test1);
}

Undeclared variable c in structure pointer function

I am still learning C and I am doing an exercise where I have to program a car database. In the main function I declared an array of 100 pointers to 'carinfo_t' structures. In the function '*createcarinfo' a new carinfo_t instance should be created. But I get the problem that the 'brandOfCar' variable is undeclared. I do not really understand why I am getting this message because the compiler should know that this variable is part of the structure, right? The structure is declared as a datatype in the program and a pointer to the struct is initialized in the beginning of this function.
I am sorry if this question has already been asked somewhere. Any help is very much appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <limits.h>
struct carinfo_t
{
char *brandOfCar;
char *modelOfCar;
int yearCarWasBuilt;
float valueOfCar;
};
struct carinfo_t *createCarinfo(char *brand, char *model, int year, float
value)
{
struct carinfo_t *newCarInfo=(struct carinfo_t*) malloc(sizeof(struct
carinfo_t));
newCarInfo->brandOfCar=(char*)malloc(sizeof(char)*
(strlen(brandOfCar)+1));
//Message: error: 'brandOfCar' undeclared (first use in this function)
//function not finished
}
int main()
{
struct carinfo_t *carbase[100]={};
return 0;
}
This is because you called the variable passed into your constructor function brand, not brandOfCar. Similarly, you called model variable model, not modelOfCar. That's why strlen does not compile.
It's a good idea to name variables identically to the fields of the structure for consistency, and add const where it is appropriate:
struct carinfo_t *createCarinfo(
const char *brandOfCar
, const char *modelOfCar
, int yearCarWasBuilt
, float valueOfCar) {
struct carinfo_t *newCarInfo=malloc(sizeof(struct carinfo_t));
newCarInfo->brandOfCar=malloc(strlen(brandOfCar)+1);
...
}
Also note that in C you do not cast malloc, and do not multiply by sizeof(char), which standard requires to be 1 on all platforms.

filling structures with a pointer C

We started programming in School and need to fill a structure via a pointer but we get this error:
'Schueler' has no member named 'Schueler'
We are using eclipse Indigo with the MinGW Compiler.
#include <stdio.h>
int main()
{
typedef struct Schueler{
char Vorname[10];
char Nachname[10];
}Schueler;
Schueler* vpName;
char cSchuelerVName[10]="Hans";
vpName->Schueler.Vorname=cSchuelerVName;
return 0;
}
Firstly you need to allocate memory to the structure pointer
vpName
The way the structure element Vorname is accessed is wrong.
It should be pointername->Structure_element_name
Vorname is a character array. = cannot be used to assign the value
modified code:
#include <stdio.h>
int main()
{
typedef struct Schueler{
char Vorname[10];
char Nachname[10];
}Schueler;
Schueler* vpName=(Schueler*)malloc(sizeof(Schueler));
char cSchuelerVName[10]="Hans";
// vpName->Schueler.Vorname=cSchuelerVName;
strcpy(vpName->Vorname,cSchuelerVName);
printf("vpName->Vorname=%s\n",vpName->Vorname);
return 0;
}

Compiling: [Error] array type has incomplete element type

I'm having a problem with a program I am trying to complete, as far as I was aware, i had defined the structs correctly, but when compiling I get this error code 3 times, once for each struct
Error message:
34 18 - [Error] array type has incomplete element type
My code is shown below, any advice would be extremely appreciated, there's approx 300 lines of code in the full program, let me know if you need to see it, I didn't want to overload you guys with it. Thanks again.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void fileRead();
void readGrades();
void readResults();
void pointCompute();
void sortGrades();
void print();
typedef struct{
char subject[15];
char level[2];
char grade[3];
int points[3];
} temp;
typedef struct{
char subject[15];
char level[2];
char grade[3];
int points[3];
} grades;
typedef struct{
char subject[15];
char level[2];
char grade[3];
int points[3];
} results;
struct temp temp[50];
struct grades grades[50];
struct results results[50];
As they are typedefs, remove the struct from the variable definition lines. You put struct if the types are actual structs, not typedefs. Also, the variable names cannot be the same as the type names.
temp temp_var[50];
grades grades_var[50];
results results_var[50];

Resources