Trying to copy a string into a struct aray - c

I am trying to copy a string into my struct array. I get the following error message:
error: expected ';', ',' or ')' before '.' token
for the bold line. I tried different variants but without success.
#include <stdio.h>
#include <string.h>
typedef struct Album {
char Interpret[20];
char Titel[10];
int Jahr;
int Zustand;
} album;
album regal[2];
strcpy(char *regal[0].Interpret, "Led Zeppelin"); // here
int main() {
return 0;
}

You're attempting to run a statement (a function call in this case) outside of a function. It should be moved inside main:
int main ()
{
strcpy(regal[0].Interpret, "Led Zeppelin");
return 0;
}

In the file scope you may place only declarations. You may not use statements.
Also there is no need to define the array as global. And the call of the function strcpy is incorrect. The function main can look like
int main()
{
album regal[2];
strcpy(regal[0].Interpret, "Led Zeppelin");
return 0;
}

strcpy() is a function from "string" library.
You can't call functions in the global scope of a file. It must have a scope that relates to the one of the main() function of your program (as in, if you go up in the call stack, you end up in your main() function), or to the scope of a constructor of a class/struct of which you create a static object.
But you can assign values or execute statement in global scope.

Line strcpy(char regal[0].Interpret, "Led Zeppelin"); // here needs to be inside main. also regal is already defined so you don't need char in strcpy function.

Can't define struct outside of function, define in main, should look like:
#include <stdio.h>
#include <string.h>
typedef struct Album {
char Interpret[20];
char Titel[10];
int Jahr;
int Zustand;
} album;
int main() {
album regal[2];
strcpy(char *regal[0].Interpret, "Led Zeppelin");
return 0;
}

Related

pointer to struct in function prototype before defining struct

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

Function Pointer present inside a structure in C

I am working on a problem of running a function through a function pointer, which is a variable of a structure. I tried making a small code but I am not able to build it.
The error I am getting is as below:
Please review the code below. The first statement in the main function is the cause of the error.
I am new to C.Thank you for your kind help.
#include <stdio.h>
#include <stdlib.h>
#include<stdint.h>
typedef int16_t (*reset_start_f)(void); //typedef used for function Pointer
int ThermMgrSvc_Reset(void)
{
int retVal;
retVal=5;
return retVal;
}
typedef struct
{
reset_start_f reset; // function pointer
}module_function_t;
static const module_function_t MODULE_TABLE[]=
{
{(reset_start_f)ThermMgrSvc_Reset},
};
int main()
{
int x2= MODULE_TABLE[0].(*reset)(); // This statement causing Error
printf("x2= %d\n",x2);
return 0;
}
This syntax is invalid:
int x2= MODULE_TABLE[0].(*reset)();
Because the structure access operator . must be followed immediately by the name of the field. The dereferencing operator needs to be before the whole subexpression:
int x2= (*MODULE_TABLE[0].reset)();
Or, since function pointers are dereferenced implicitly when called, you can remove the * entirely:
int x2= MODULE_TABLE[0].reset();

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 declare a function that has a structure containing an array, whose size is determined by argv, as an argument?

I have a structure dt that contains an internal array whose size is determined by argv. I need to feed this structure to a function func so I tried to declare it with a void pointer argument but the compiler is complaining that it's not being void at the end of the day. Here is the code :
#include <stdio.h>
#include <string.h>
void func(void *);
int main(int argc, char *argv[])
{
int RETSIZE;
sscanf(*++argv, "%d", &RETSIZE);
struct
{
char name[6];
char ret[RETSIZE];
} dt[100];
func(dt);
}
void func(void *dt)
{
dt->ret[2] = 3;
}
How and where do I declare the structure dt and the function func so it works out ?
If you want to use a structure in two (or more) functions, you need to define it in the global scope, so both functions have access to it. There's simply no way around it.
As for the array, in this case it's not possible to use variable-length arrays. You need to either use a flexible array member or to use a pointer. Both of these requires dynamic allocation of the heap. You also need to keep the number of elements in the array as a member in the structure.
Try This:
#include <stdio.h>
#include <string.h>
#define MAX_OBJECT 100
typedef struct
{
char name[6];
char ret[];
} dt;
void func(dt *strPtr)
{
strPtr->ret[2] = 3;
}
int main(int argc, char *argv[])
{
dt obj[MAX_OBJECT];
func(&obj[0]);
printf("Verify values written successfully or not: %d \n",obj[0].ret[2]); //Just for example
}
Here are few corrections/comments for your code:
- Keep the struct in global scope so that the struct is visible to all the whole code.
- In the func void func(void *dt), you should again type cast it the original datatype(struct in this case), in order to use it.
- As suggested in the above post, in C lang the size of the array(string) should be known to the compiler. Or else some garbage value will be present in RETSIZE and that much amount of stack memory is allocated to the ret. So, the struct should be
struct mystruct
{
char name[6];
char *ret;
};
And for memory allocation,
dt.ret = (char *)malloc(RETSIZE*sizeof(char));
- Also your func should be modifed cuz you have declared an struct array of 100, and you are passing it to the func

How to access elements in an array of structs (not global)

Trying to continue with my assignment but would like to sidetrack and figure out how array of structs work. Not sure if I'm not looking hard enough but I can't seem to find an answer.
Let's say I have one source file, main.c
#include "data.h" //this contains the struct data.
newPerson person[20];
int mainMenu(){
addName();
}
void addName(){
strcpy(person[0].firstName, "George");
}
Doing it this way, I'm able to access the array of struct, however isn't this method considered taboo since my array of person is a global variable?
I then tried moving the array initialization into the main function instead
#include "data.h" //this contains the struct data.
int mainMenu(){
newPerson person[20];
addName();
}
void addName(){
strcpy(person[0].firstName, "George");
}
Doing it this way, when I get to the addName() function, I get a 'person undeclared' error. How can I access the person[] array outside of its function without making it a global variable? Thank for the help in advance. Below I have the example data.h included if needed.
data.h
typedef struct person{
char firstName[20];
char familyName[20];
char telephoneNum[20];
}newPerson;
Just pass parameters to the addName() function.
Example
#include "data.h" //this contains the struct data.
int mainMenu(){
newPerson person[20];
addName(person, 0, "George");
}
void addName(newPerson *person, unsigned int index, const char *const name) {
if ((person == NULL) || (index >= 20))
return; /* ^ this number could be specified with a macro */
/* or via a parameter */
strcpy(person[index].firstName, name);
}
Yeah, pass the variable, person in this case.
person is an array of struct newPerson.
to pass arrays as parameters you should define the function like this
//Option 1, the last dimension without number
void addName(newPerson person[]){
//...
}
//Option 2, as a pointer, but it neets a cast on the call (newPerson*)
void addName(newPerson *person){ //I prefer option 1
//...
}

Resources