I want to make a structure in C with one of the structure variable having an initial default value
struct process{
char process_name[2];
int burst_time;
int completion_time;
int turn_around_time;
int waiting_time;
int priority;
int arrival_time= 0;
};
in the above structure, i want to make arrival_time=0 but i gives me an error
Priority.c:11:19: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
In C, it's not possible. You can't initialize structure members inside a structure itself. First you need to create an instance or variable of the structure type; only after that can you initialize a structure member. For example:
struct process{
char process_name[2];
int burst_time;
int completion_time;
int turn_around_time;
int waiting_time;
int priority;
int arrival_time; /* here you can't initialize */
} process_instance = { .arrival_time = 0 }; /* first process_instance created then initialize the members */
And you can access like arrival_time like below.
int main(void) {
printf("%d\'n",process_instance.arrival_time);
return 0;
}
Though in C++ (not in C), structs are almost synonymous to classes and can have members initialized in the constructor. For example:
struct process{
int arrival_time; /* member of structure */
process() : arrival_time(0) { } /*constructor */
};
int main(void) {
process obj;
std::cout<<obj.arrival_time;
return 0;
}
Related
The below is my code. Compiler generates the errors as
#include<stdio.h>
struct Shelf{
int clothes;
int *books;
};
struct Shelf b;
b.clothes=5;
*(b.books)=6;
Compiler generates the errors as below for both statements b.clothes=5; and b->books=6; in above code.
error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘->’ token
I'm not a beginner at C and I believe that what I have written is correct. Kindly solve my problem
FIRST
You cannot do this
struct Shelf{
int clothes;
int books;
};
struct Shelf b;
b.clothes=5;
b.books=6;
In global scope
You can assign value inside a function
int main (void )
{
b.clothes=5;
b.books=6;
}
Or initializing values on declaration
struct Shelf b = { .clothes = 5, .books = 6 };
Moreover as you can see b is not a pointer so using -> is not correct: use . to access members of struct.
SECOND
Your struct has a pointer member book
struct Shelf{
int clothes;
int *books;
};
What you can do is to set it to the address of another variable, like
int book = 6;
struct Shelf b = { .clothes = 5, .books = &book };
Or allocate memory for that pointer like
int main (void )
{
b.clothes=5;
b.books=malloc(sizeof(int));
if (b.books != NULL)
{
*(b.books) = 6;
}
}
BTW I guess you want an array of books, so
int main (void )
{
b.clothes=5;
b.books=malloc(sizeof(int) * MAX_N_OF_BOOKS);
if (b.books != NULL)
{
for (int i=0; i<MAX_N_OF_BOOKS; i++)
b.books[i] = 6;
}
}
COMPETE TEST CODE
#include <stdio.h>
#include <stdlib.h>
struct Shelf
{
int clothes;
int *books;
};
int main(void)
{
struct Shelf b;
b.clothes = 5;
b.books = malloc(sizeof(int));
if (b.books != NULL)
{
*(b.books) = 6;
}
printf ("clothes: %d\n", b.clothes);
printf ("book: %d\n", *(b.books) );
}
OUTPUT
clothes: 5
book: 6
b is a struct, not a pointer, so -> is not correct.
It's like doing (*b).books, which is wrong.
struct Shelf{
int clothes;
int *books;
};
One data member of the struct is a pointer, however:
struct Shelf b;
is not a pointer, it is just a struct as I said before.
As for your question in comment:
b.clothes=5;
is correct. Also something like this would be ok:
int number = 6;
b.books = &number;
-> operator used to access of member of struct via pointer. b is not dynamically allocated so b->books=6; is wrong. You should first allocate memory for member books and then dereference it.
b.books = malloc(sizeof(int));
*(b.books)= 6;
This question already has answers here:
Why can't we initialize members inside a structure?
(6 answers)
Closed 7 years ago.
I wanted to make an object oriented preprocessor to my programming language which converts my language into C (like early C++). And I want to simulate the classes with structures. And the question is: how can I declare a variable inside a struct like this:
typedef struct { //equivalent of class
int a = 5;
int (*sub)(int) = &int_sub; //function of a class, uses an external declared function
} class_name;
I tried the code above but the compiler wrote this:
error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
void (*sub)(int) = &int_sub;
I have two questions:
Can I declare a variable inside a struct?
If yes, how?
You can't assign a pointer value inside a struct definition. You could use a function to init it.
typedef struct { //equivalent of class
int a;
int (*sub)(int);
} class_name;
int int_sub (int a)
{
// your stuff
return 0;
}
int main()
{
class_name myClassVariable;
myClassVariable.a = 5;
myClassVariable.sub = int_sub;
printf("class_name.a = %d\n", myClassVariable.a );
printf("class_name.sub = %p\n", myClassVariable.sub );
printf("int_sub address = %p\n", int_sub );
return 0;
}
Or, as shown in artm answer, you could init your allocated variable:
class_name my_struct = { .a = 5, .sub = int_sub };
Alternatively, you can also initialize the variable of your struct type.
int func( int a ){}
typedef struct {
int a;
int (*sub)(int);
} class_name;
class_name my_struct = { .a = 5, .sub = func };
I take it your question is not about how to declare but how to initialize a structure member.
Define the class as opaque type in the h file. Use typedef for function pointers.
h file
// opaque type declaration
typedef struct class_name class_name;
// types used by this class
typedef int sub_func_t (int);
// member functions of the class
class_name* class_init (int a, sub_func_t* sub);
Then initialize it from inside its constructor:
c file
struct class_name { //equivalent of class
int a;
sub_func_t* sub;
};
class_name* class_init (int a, sub_func_t* sub)
{
class_name* new_class = malloc(sizeof(*new_class));
assert(new_class != NULL);
*new_class = (class_name){a, sub};
return new_class;
}
I am trying to create a list of threads that would be locked and executed in the order of the list. here is the code( it's a busy wait simulation I have for a course)
# include <stdio.h>
# include<pthread.h>
# include<stdlib.h>
# define NKIDS 10
pthread_mutex_t mutx;
struct kidrec {
int data;
pthread_t id;
};
struct coada {
struct kidrec th;
struct coada *next;
};
void *copilfunc(void*p)
{
int *ip=(int*)p;
int tmp;
int v;
pthread_mutex_lock(&mutx);
tmp=v; v=*ip;
printf(" We are at thread %d \n",v);
pthread_mutex_unlock(&mutx);
}
int main(){
struct kidrec kids[NKIDS];
struct coada c[NKIDS];
int m;
for(m=0;m<NKIDS;m++){
kids[m].data=m;
pthread_create(&kids[m].id,NULL,copilfunc,&kids[m].data);
c[m].th=kids[m];
if(m>0) c[m-1]->next=c[m];
if(m==NKIDS) c[NKIDS]->next=c[0];
}
for(m=0;m<NKIDS;m++)
pthread_join(c[m].th.id,NULL);
}
You are trying to access an attribute on an array of a struct using -> which is an access operator used for pointers (non-arrays)...
Try using
c[i].next = &c[j]
instead of
c[i]->next = c[j]
;)
The variable c[] is an array of struct coada, not struct coada *.
So the expression c[m-1] is a struct coada, and you access its fields with ..
Thus, it should be:
c[m - 1].next = &c[m];
It doesn't matter that next is a pointer, the period is for accessing the struct-typed value on its left. Also note that you need to take the address of the array element, thus the & on the right.
I'm working with structs for the first time in a long time and I am having multiple issues. I'm just trying to systematically address them but this one in particular is giving me a hard time. When I try to make the program, I get this:
`datime.c:9:23:error: expected ‘;’, ‘,’ or ‘)’ before ‘.’ token bool
isConflict(Class.Time*, Class.Time*){`
and
`datime.c:18:21: error: expected ‘;’, ‘,’ or ‘)’ before ‘.’ token bool
isEarlier(Time.Start*, Time.Start*){`.
My file, schedule.h:
/*
* file: datime.h
*/
typedef struct
{ int hour;
int min;
} Start;
typedef struct
{ int hour;
int min;
} Stop;
typedef struct
{ struct Start;
struct Stop;
} Time;
typedef struct
{ struct Time;
int Days[7];
} Class;
bool isConflict(struct TimeA*, struct TimeB*);
bool isEarlier(struct TimeA*, struct TimeB*);
My file, schedule.c:
/*
* file: datime.c
*/
#include <stdio.h>
#include <stdbool.h>
#include "datime.h"
bool isConflict(Class.Time*, Class.Time*){
free(classA);
free(classB);
if ((classA.Start <= classB.Start) && (classA.Stop >= classB.Stop))
return 1;
else
return 0;
}
bool isEarlier(Time.Start*, Time.Start*){
free(classA);
free(classB);
if (classA.Start < classB.Start)
return 1;
else
return 0;
}
Also, the driver.c, being used just to test the functions and structs:
#include <stdbool.h>
#include "datime.h"
main()
{
void setClass(struct Class)
{ struct Class EE205{
EE205.Time.Start.hour = 8;
EE205.Time.Start.min = 30;
EE205.Time.Stop.hour = 9;
EE205.Time.Stop.min = 20;
// Initializing array to zero
memset(EE205.Days, 0, 7 * sizeof(Days[0]));
EE205.Days[1] = 1;
EE205.Days[3] = 1;
EE205.Days[5] = 1;
};
struct Class EE367{
EE367.Time.Start.hour = 10;
EE367.Time.Start.min = 30;
EE367.Time.Stop.hour = 11;
EE367.Time.Stop.min = 20;
// Initializing array to zero
memset(EE367.Days, 0, 7 * sizeof(Days[0]));
EE367.Days[1] = 1;
EE367.Days[3] = 1;
EE367.Days[5] = 1;
};
struct Class EE315{
EE315.Time.Star.hour = 12;
EE315.Time.Start.min = 30;
EE315.Time.Stop.hour = 13;
EE315.Time.Stop.min = 20;
// Initializing array to zero
memset(EE315.Days, 0, 7 * sizeof(Days[0]));
EE315.Days[1] = 1;
EE315.Days[3] = 1;
EE315.Days[5] = 1;
};
if(isConflict(EE315, EE367))
printf("Scheduling conflict! EE315 and EE367 conflict.");
if(isConflict(EE315, EE205))
printf("Scheduling conflict! EE315 and EE205 conflict.");
if(isConflict(EE205, EE367))
printf("Scheduling conflict! EE205 and EE367 conflict.");
}
There are a lot of errors, but these errors are the two that I cannot move passed for whatever reason. Thanks in advance.
Allen
This isn't any legal C syntax.
bool isConflict(Class.Time*, Class.Time*)
(Actually almost nothing of the code is valid. I suggest you start learning structs and pointers with a much smaller example/program)
You'll have to declare it as e.g.
bool isConflict(Class* classA, Class *classB){
The body is quite strange too, I cannot really figure out what you intend to do:
free(classA); <--- free() classA/classB, but 2 lines down you try to access them ?
free(classB);
// if ((classA.Start <= classB.Start) && (classA.Stop >= classB.Stop))
//since classA/classB are pointers you need -> to access their members:
// You also need to compare the members of Time, you can't compare structs
// in C, e.g. to check the hours:
if ((classA->Start.hour <= classB->Start.hour) &&
(classA->Stop.hour >= classB->Stop.hour))
return 1;
else
return 0;
}
Your isEearlier function has the same problem.
main()
{
//you can't declare a function within another function like this.
//what is the purpose of the setClass function ? There is no code that calls this function
//you also need to give names to your function parameters, if you want a pointer, it'd be
//void setClass(struct Class *my_class)
void setClass(struct Class)
{
Your Time struct is wrong, you havn't given any variable names to the members, it should be:
typedef struct
{ Start Start;
Stop Stop;
} Time;
(However, your struct Start and struct Stop are identical, there's no need to create 2 struct definitions for both)
The initializers for your struct is wrong:
struct Class EE205{
EE205.Time.Start.hour = 8;
EE205.Time.Start.min = 30;
EE205.Time.Stop.hour = 9;
EE205.Time.Stop.min = 20;
};
Note that you say struct Class, but nowhere have you defined a struct Class. You have a typedef
to a struct, the typedef is just called Class, so the compiler will not know about struct Class, it only knows about Class
You can set the members like:
Class EE205;
EE205.Time.Start.hour = 8;
EE205.Time.Start.min = 30;
EE205.Time.Stop.hour = 9;
EE205.Time.Stop.min = 20;
// Initializing array to zero
memset(EE205.Days, 0, 7);
EE205.Days[1] = 1;
EE205.Days[3] = 1;
EE205.Days[5] = 1;
Or initialize it:
Class EE205 = {
{
{8, 30},
{9,20}
},
{0,1,0,1,0,1}
};
This is completely wrong, you cannot use structure type as structure members.
/* 2 structures type doing the same thing? */
typedef struct
{ int hour;
int min;
} Start;
typedef struct
{ int hour;
int min;
} Stop;
typedef struct
{ struct Start; /* variable name missing */
struct Stop;
} Time;
typedef struct
{ struct Time;
int Days[7];
} Class;
bool isConflict(struct TimeA*, struct TimeB*); /* makes no sense */
bool isEarlier(struct TimeA*, struct TimeB*);
Let's rewrite it:
/* Replaced Start/Stop with time */
typedef struct
{ int hour;
int min;
} Time;
/*
Added member names.
Removed struct because using typedef for Time
*/
typedef struct
{ Time start;
Time stop;
} TimeSpan;
typedef struct
{ TimeSpan timeSpan;
int Days[7];
} Class;
/*
First type, then variable name for each parameter.
Also removed the invalid struct marker.
*/
bool isConflict(Time * a, Time * b);
bool isEarlier(Time * a, Time * b);
This does't fix the problems with the actual code yet, but now you should
at least have your type declarations right.
You have multiple errors.
You are using typedef so there is not need to use struct after
You just enter the type in the struct and you forgot the name
Same in the function declaration
Here is your header file:
/*
* file: datime.h
*/
typedef struct
{ int hour;
int min;
} Start;
typedef struct
{ int hour;
int min;
} Stop;
typedef struct
{ Start start;
Stop stop;
} Time;
typedef struct
{ Time time;
int days[7];
} Class;
bool isConflict(Time *timeA, Time *timeB);
bool isEarlier(Time *timeA, Time *timeB);
In your source file there is mistakes too:
You are using struct pointer so to acces member you have to use -> and not .
You are using bool with <stdbool.h> so you should return true or false
You can't free things that you will access later (or you will have a segmentation fault)
Here is your source file:
/*
* file: datime.c
*/
#include <stdio.h>
#include <stdbool.h>
#include "datime.h"
bool isConflict(Time *timeA, Time *timeB) {
if ((timeA->start <= timeB->start) && (timeA->stop >= timeB->stop))
return true;
else
return false;
}
bool isEarlier(Time *timeA, Time *timeB) {
if (timeA->start < timeB->start)
return true;
else
return false;
}
There is also a lot of mistakes in your main. I let you see the other responses ....
os-sim.h
typedef enum {
PROCESS_NEW = 0,
PROCESS_READY,
PROCESS_RUNNING,
PROCESS_WAITING,
PROCESS_TERMINATED
} process_state_t;
typedef struct _pcb_t {
const unsigned int pid;
const char *name;
const unsigned int static_priority;
process_state_t state; <<---Trying to access this
op_t *pc;
struct _pcb_t *next;
} pcb_t;
file1.c
static pcb_t **current;
extern void yield(unsigned int cpu_id)
{
/* FIX ME */
while (1)
{
pthread_mutex_lock(¤t_mutex);
current[cpu_id].state = PROCESS_WAITING; ///<-------ERROR HERE
pthread_mutex_unlock(¤t_mutex);
break;
}
schedule(cpu_id);
}
in main method():
current = malloc(sizeof(pcb_t*) * 10);
I have error in this line current[cpu_id].state = PROCESS_WAITING;
error: request for member ‘state’ in something not a structure or union
What does this error mean?
Is this not the right way to access current array which holds pcb_t?
If so, how do i access the current array? and state field?
You're likely looking for:
current[cpu_id]->state = PROCESS_WAITING;
The type of current is pcb_t **. So the type of current[cpu_id] is pcb_t *.