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.
Related
I am trying to create a struct that I will use in a function via pointers. The issue is that I do not want to use global variables therefore I can't use a pointer to a struct as a parameter for the function prototype if I try to define the struct in main file, since it has not been defined yet.
How would I go about doing this? What I think the solution is, is to define the struct in a header file, then create local variables of that type in the main file. Is this the right way to go about this? Would appreciate some info about what i'm actually doing here if this is correct.
Sorry if I did anything wrong when posting, Its my first time.
Example of what I am thinking the solution is
Main.h
#include <stdio.h>
typedef struct Vehicle{
int a;
char b;
};
function(Vehicle *p);
Main.c
#include "Main.h"
Vehicle Car1;
Vehicle *p=&Car1;
function(p);
The proper syntax for a typedef is
typedef T-IDENTIFIER IDENTIFIER-LIST;
wherein the comma separated identifiers listed in IDENTIFIER-LIST become aliases for T-IDENTIFIER. A lot of the time IDENTIFIER-LIST will consist of a single identifier.
For example, in
typedef int integer, number;
integer and number are now type aliases for int.
When it comes to using typedef with structs, the form
typedef struct foo { /* ... */ } foo_type;
is more or less shorthand for
typedef struct foo foo_type;
struct foo { /* ... */ };
but does allow you to typedef an anonymous struct
typedef struct { /* ... */ } foo_type;
With all that said, in your code you have omitted the IDENTIFIER-LIST from your typedef.
If main.c really does consist entirely of the code you've posted, it will not compile. Every C program needs an entry point, and in a hosted environment that is the function main with the signature int main(void) or int main(int argc, char **argv).
While you can declare variables outside of functions (i.e., globals), you can not call functions from outside of functions. Everything starts from main.
A working example program:
main.h:
typedef struct {
int a;
char b;
} Vehicle;
void function(Vehicle *p);
main.c:
#include <stdio.h>
#include "main.h"
int main(void) {
Vehicle car = { 51, 'A' };
function(&car);
}
void function(Vehicle *v) {
printf("Vehicle: a: %d, b: %c\n", v->a, v->b);
}
I can't use the struct as a parameter for the function prototype
You misunderstood something.
Your typedef is rather useless.
You of course can use pointers to structs as function parameters and in the function prototypes.
typedef struct {
int a;
char b;
} Vehicle;
int foo(Vehicle *); // prototype
You can't call function not outside other functions (as it is shown in the main.c
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);
}
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;
}
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;
}
I created a function which returns a pointer to an object of a self-made structure. Then, I declared another pointer which I set equal to a pointer returned by the the aforementioned function. I get the error "Assignment makes pointer from integer without a cast" - but I do not understand why I should be casting... because all of these pointers were declared to be of the same type.
In disk.h I defined the following:
struct generic_attribute{
char *name;
int current_value;
int previous_value;
//int time_series[500];
};
In disk.c, I made a constructor for generic_attribute like so:
#include "disk.h"
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
struct generic_attribute* construct_generic_attribute(char* name, int current_value){
struct generic_attribute *ga_ptr;
//ga_ptr = (struct generic_attribute*) malloc (sizeof(struct generic_attribute));
ga_ptr = malloc (sizeof (struct generic_attribute));
ga_ptr -> name = name;
ga_ptr -> current_value = current_value;
ga_ptr -> previous_value = 0;
return ga_ptr;
}
In disk_test.c I want to test this constructor:
#include "disk.h"
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
void test_generic_attribute_constructor(char* name, int current_value){
struct generic_attribute* ga_ptr;
ga_ptr = construct_generic_attribute(name, current_value);
printf("%i\n", construct_generic_attribute(name, current_value));
}
int main() {
test_generic_attribute_constructor("test", 2000);
}
I get the error on this line:
ga_ptr = construct_generic_attribute(name, current_value);
I do not understand why. ga_pointer was declared as a pointer to type struct generic_attribute. So was the return of function construct_generic_attribute. I am new to C, so I might be misunderstanding how all of this works.
You did not declare construct_generic_attribute() in disk.h, so upon seeing the function call the compiler assumes it has the default signature -- that is, int construct_generic_attribute();.
Thanks for questioning this instead of blindly adding the cast (which could have seemed to work !)
You are missing the function declaration in your header file, disk.h.
add the declaration:
struct generic_attribute* construct_generic_attribute(char* ,int);
and the compiler will know the return type of your function is a pointer.
add following line in disk_test.c :
struct generic_attribute* construct_generic_attribute(char* ,int);