How to use table pointer with fonction in C [duplicate] - c

This question already has answers here:
Passing 2D array of const size
(5 answers)
Closed 2 months ago.
This post was edited and submitted for review 2 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I have a struct like:
struct oda {
char isim[10];
int id[1];
};
and 2d table created with this type:
struct oda* tab[X][Y];
This table should be allocated dynamically on memory, so if we have product placement on x and y tab[X][Y] should point to our struct, otherway value of pointer tab[X][Y] = NULL
I have created a fonction for init this table:
void init_tab_empty(struct oda** ptr_tab)
{
int i, j;
for (i = 0; i < X; i++) {
for (j = 0; j < Y; j++) {
ptr_tablo[i][j] = NULL;
}
}
}
But this is not working, i have:
Cannot assign a value of type void * to an entity of type struct oda
Can you help me please?
I played with *'s but i can't understand what can i do more
it seems correct for me but not working

If I understood you well, you want to pass a table to your function. Then the following change will make it okay:
void init_tab_empty(struct oda ***tab)
{
int i, j;
for (i = 0; i < DIM_X; i++) {
for (j = 0; j < DIM_Y; j++) {
tab[i][j] = NULL;
}
}
}
This tells the function that you will input a table of pointers to struct oda data type.
There, you have:
struct oda *my_tab[DIM_X][DIM_Y];
...
init_tab_empty(my_tab);

Related

Using Structs in C

Hi im building a simple game in c (im new to the language). Im using the following structs:
typedef struct
{
int adjacent_mines;
bool revealed;
bool is_mine;
} Tile;
struct GameState
{
Tile tiles[NUM_TILES_X][NUM_TILES_Y];
};
typedef struct GameState GameState;
Im wondering how to properly call and set the structs? I have the following code where i would like to set state of each Tile.
void intialize_mines(){
for (int i =0; i < NUM_TILES_X; i++){
for (int j =0; j < NUM_TILES_Y; j++){
tiles[i,j].revealed = false;
}
}
}
But according to my console output i have done this incorrectly. How would i go about setting this correctly?
struct GameState just declares a type (just as int is just a type). You have to create a real struct in memory with GameState foo; similar to a normal variable (int foo;). And you can not access the contents of a struct without referencing the struct like foo.tiles. tiles on it's own is not known in this scope.
Afterwards you can access the struct with foo.tiles[i][j].revealed.
But to have access to this struct in your function you either have to pass it to the function as a pointer or declare the struct in filescope ( also called global). I would prefer the first version it is clearer an more function like.
Your function would look like this:
void intialize_mines( GameState *foo){
for (int i =0; i < NUM_TILES_X; i++){
for (int j =0; j < NUM_TILES_Y; j++){
foo->tiles[i][j].revealed = false; // -> is a special operator for pointers to structs. It's the same as (*foo).
}
}
}
the corresponding function call would be:
GameSate bar;
intialize_mines( GameState &bar);
You should also check how to use multidimensional arrays. You declared it correctly with two seperate [] but in your function you use [x,y] which is not correct in C. It would be the same as in the declaration tiles[i][j]
For a multi-dimensional array like tiles, you have to specify array subscript of each dimension within [] like this:
tiles[i][j].revealed = false;
This means that revealed belonging to jth column of ith row of tiles is set to false.
And you will have to define a structure variable of the type GameState before performing any operations on it.
GameState initGS;
void intialize_mines(){
for (int i =0; i < NUM_TILES_X; i++){
for (int j =0; j < NUM_TILES_Y; j++){
initGS.tiles[i][j].revealed = false;
}
}
}
You just missed to instantiate a GameState structure.
GameState gs;
void initialize_mines() {
for (int i =0; i < NUM_TILES_X; i++) {
for (int j =0; j < NUM_TILES_Y; j++) {
gs.tiles[i][j].revealed = false;
}
}
}

Segmentation Fault when returning integer

I recently joined Stackoverflow community because I had to ask this question. I've been searching for possible explanations and solutions on the website but so far nothing enlightened me as I wanted. My error is probably caused by a very specific line of code. I'm trying to create a function that reads an array of struct votes, (struct contains integer member number, char *category, char *nominee) and copies all the votes that contain the same number and category to another array of struct. Basically to show all the repeated votes.
typedef struct
{
int member;
char *categ;
char *nom;
}Vote
Vote vote(int member, char *categ, char *nom)
{
Vote result;
result.member = member;
result.categ = categ;
result.nom = nom;
return result;
}
int votes_count(Vote *v, int n, Vote *v1)
{
int result = 0;
int *index = malloc(sizeof(int) * 1000);
int a = 0;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
if (a == 0 && v[i].member == v[j].member && strcmp(v[i].categ, v[j].categ) == 0)
{
v1[result++] = vote(v[j].member, str_dup(v[j].categ), str_dup(v[j].nom));
index[a++] = j;
}
for (int b = 0; b < a; ++b)
{
if( a > 0 && v[i].member == v[j].member && strcmp(v[i].categ, v[j].categ) == 0 && j != index[b])
{
v1[result++] = voto(v[j].member, str_dup(v[j].categ), str_dup(v[j].nom));
index[a++] = j;
}
}
}
}
return result;
}
Afterwads, it returns the number of elements of new array that contains all repetitions. I want to use an array of ints to save all line indexes so that the function doesn't read and copy the lines it already accounted.
Sorry if the code is hard to understand, if needed I can edit to be more understandable. Thanks for any answears.
P.S: I'm portuguese, sorry in advance for grammar mistakes
if your only intention is to harvest the duplicates, you only need to compare to the elements that came before an element
you don't need the index[] array
For simplicity, I used two integer arrays, you should change them to your struct arrays, also change the compare function.
unsigned fetchdups(int orig[], int dups[], unsigned count)
{
unsigned this, that, ndup=0;
for (this=1; this<count; this++){
for (that=0; that<this; that++){
/* change this to your compare() */
if(orig[that] == orig[this]) break;
}
if (this == that) continue; /* no duplicate */
dups[ndup++] = this;
}
return ndup;
}

Creating a three dimensional struct array on the heap in c

I am trying to create a three dimensional struct array using malloc in c on MSVC. It compiles without error but when i debug it it gives an error after initializing some elements.
declaration:
typedef struct table_info
{
unsigned long size;
char code[33];
char path[300];
}table_info;
table is a global variable and is defined as:
struct table_info ***table=NULL;
malloc and initialize table:
char garb[33] = { '\0' };
char garb_path[300] = { '\0' };
table = (table_info***)malloc(ROWS* sizeof(**table));
for (int m = 0; m < ROWS; m++)
{
table[m] = (table_info**)malloc(COLS* sizeof(*table[m]));
for (int j = 0; j < COLS; ++j)
{
table[m][j] = (table_info*)malloc(DEPTH * sizeof(table[m][j]));
for (int k = 0; k < DEPTH; ++k)
{
table[m][j][k].size = 0;
strcpy_s(table[m][j][k].code, sizeof(table[m][j][k].code), garb);
memcpy(table[m][j][k].path, garb_path, sizeof(garb_path));
}
}
}
Am I initializing it correctly? or what should I correct to make it work?
The size passed to malloc is incorrect in the following line:
table[m][j] = (table_info*)malloc(DEPTH * sizeof(table[m][j]));
sizeof(table[m][j]) is just sizeof(**table), which is sizeof(table_info *). It should be sizeof(table_info), or alternatively sizeof(*table_info[m][j]) or sizeof(***table_info).
You also don't need to cast the result of malloc, which is generally frowned upon today (at least in C). See this post for more info.
So the following should work (in C):
table[m][j] = malloc(DEPTH * sizeof(*table[m][j]));

Initializing Strings in an Array of Sturts within a Struct

I have a struct gradebook with(among other things) an array of student structs that has two string fields
#define MAX_NAME_LEN 50
#define MAX_EMAIL_LEN 80
#define MAX_NUMBER_OF_STUDENTS 200
#define MAX_NUMBER_OF_ASSIGNMENTS 100
typedef struct students {
char *name;
char *email;
} Students;
typedef struct gradebook {
int number_of_students;
Students students[MAX_NUMBER_OF_STUDENTS];
int number_of_assignments;
char assignments[MAX_NUMBER_OF_ASSIGNMENTS][(MAX_NAME_LEN + 1)];
int scores[MAX_NUMBER_OF_STUDENTS][MAX_NUMBER_OF_ASSIGNMENTS];
} Gradebook;
I have an initialization function
int init_gradebook(Gradebook *book) {
int row, col, ndx, count;
book->number_of_students = 0;
count += book->number_of_students;
for(ndx = 0; ndx < MAX_NUMBER_OF_STUDENTS; ndx++) {
book->students[ndx].name = 0;
book->students[ndx].email = 0;
}
book->number_of_assignments = 0;
count += book->number_of_assignments;
for(row = 0; row < MAX_NUMBER_OF_ASSIGNMENTS; row++) {
for(col = 0; col < (MAX_NAME_LEN + 1); col++) {
book->assignments[row][col] = 0;
count += book->assignments[row][col];
}
}
for(row = 0; row < MAX_NUMBER_OF_STUDENTS; row++) {
for(col = 0; col < MAX_NUMBER_OF_ASSIGNMENTS; col++) {
book->scores[row][col] = 0;
count += book->scores[row][col];
}
}
if (count == 0) {
return 1;
} else {
return 0;
}
}
and I need to then insert, into those two string fields, the passed in strings, with my add_student function.
int add_student(Gradebook *book, char *nom, char *mail) {
int ndx, count;
if (book->number_of_students == 0) {
book->students[(book->number_of_students)].name = malloc(sizeof(51));
book->students[(book->number_of_students)].email = malloc(sizeof(81));
strcpy(book->students[(book->number_of_students)].name, nom);
strcpy(book->students[(book->number_of_students)].email, mail);
book->number_of_students++;
} else {
for (ndx = 0; ndx < book->number_of_students; ndx++) {
book->students[(book->number_of_students)].name = malloc(sizeof(51));
book->students[(book->number_of_students)].email = malloc(sizeof(81));
strcpy(book->students[(book->number_of_students)].name, nom);
strcpy(book->students[(book->number_of_students)].email, mail);
book->number_of_students++;
}
}
return 1;
}
My code compiles, but when I run it with the main function, I get a seg fault. The add_student function is what I am ultimately trying to do (copy the given string into book->student[ndx].name) If you need to see the main file or the gradebook.h file, let me know.
Edit: Thanks to all of you, this issue has been solved. The main problem, as abginfo pointed out, was my If Else + the For loop inside of it. But now I have other problems further along in my program. Haha, Thank You.
From what portion of your code I can see, I'm going to make the assumption that the init_gradebook function takes a non allocated reference to gradebook and attempts to initialize it.
In this case the gradebook reference you have has no memory allocated to it just yet. Try using the malloc() function to assign the required memory to your gradebook reference before attempting to initialize the rest of its variables.
gb = (Gradebook*)malloc(sizeof(*Gradebook));
I've changed the variable name to avoid any confusion.
To supplement varevarao's answer, you should allocate everything explicitly as a matter of habit instead of relying on segfaults to tell you something's not allocated. (Not that you necessarily do!) Messing with unallocated memory is undefined behavior, so in some cases this code does not trigger an error -
int main (void) {
Gradebook mybook;
init_gradebook(&mybook);
printf("there are %i students\n", mybook.number_of_students);
add_student(&mybook, "blerf", "blerf#gmail.com");
printf("now there are %i students\n", mybook.number_of_students);
printf("%s has an email address of %s\n", mybook.students[0].name, mybook.students[0].email);
return 0;
}
returned (on my machine)
there are 0 students
now there are 1 students
blerf has an email address of blerf#gmail.com

Can't assign string to pointer inside struct

Here is a piece of my code, I tried to make it simpler I am trying to assign a string to a pointer inside a struct that is inside an array, also I would like to initialize pointers to NULL so I can check whether or not there is already a doctor using the room...
I keep getting seg fault errors
I would appreciate any help
struct appointment{
char *SSN;
int status;//is appointment already taken?
};
struct room{
int doctorID;
char *doctorname;
struct appointment hours[10];
};
struct room clinic[5];
for(int i = 0; i < 5; i++){ //I was trying to initialize all pointers to NULL but didn't work
clinic[i].doctorID = 0;
for(int j = 0; i < 10; i++){
clinic[i].hours[j].status = 0;
}
}
for(int i = 0; i < 5; i++){
clinic[i].doctorname = malloc(sizeof(char) * 30); // Am I doing something wrong here?
*clinic[i].doctorname = "fernando";
printf("the name of the doctor on clinic %d is %s\n", i, clinic[i].doctorname
free(consultorios[i].medico);
}
return 0;
}
If you want to assign a string user strcpy instead.
Change your line
*clinic[i].doctorname = "fernando";
to
strcpy(clinic[i].doctorname, "fernando");

Resources