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]));
Related
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);
So im new to C programming and my assignment is to write a function(Max_way) that prints the driver who had the total of longest trips.
im using these 2 structs:
#define LEN 8
typedef struct
{
unsigned ID;
char name[LEN];
}Driver;
typedef struct
{
unsigned T_id;
char T_origin[LEN];
char T_dest[LEN];
unsigned T_way;
}Trip;
and a function to determine the total trips of a certain driver:
int Driver_way(Trip trips[], int size, unsigned id)
{
int km=0;
for (int i = 0; i < size; i++)
{
if (id == trips[i].T_id)
{
km = km + trips[i].T_way;
}
}
return km;
}
but when im trying to print the details of a specific driver from an array of drivers, i receive the correct ID, the correct distance of km, but the driver's name is not copied properly and i get garbage string containing 1 character instead of 8.
i've also tried strcpy(max_driver.name,driver[i].name) with same result.
void Max_way(Trip trips[], int size_of_trips, Driver drivers[], int size_of_drivers)
{
int *km;
int max = 0;
Driver max_driver;
km = (int*)malloc(sizeof(int) * (sizeof(drivers) / sizeof(Driver)));
for (int i = 0; i < size_of_drivers; i++)
{
km[i] = Driver_way(trips, sizeof(trips), drivers[i].ID);
for (int j = 1; j < size_of_drivers; j++)
{
if (km[j] > km[j - 1])
{
max = km[j];
max_driver.ID = drivers[i].ID;
max_driver.name = drivers[i].name;
}
}
}
printf("The driver who drove the most is:\n%d\n%s\n%d km\n", max_driver.ID, max_driver.name, max);
}
any idea why this is happening?
Note that one cannot copy a string using a simple assignment operator; you must use strcpy (or similar) as follows:
if (km[j] > km[j - 1]) {
max = km[j];
max_driver.ID = drivers[i].ID;
strcpy(max_driver.name,drivers[i].name);
}
Also note that since you were using ==, this was not even a simple assignment, put a comparison. Changing to == likely fixed a compile-time error, but it did NOT give you what you want.
First of all,the names of variables are in greek.
It's impossible to saw all the code,because is many files.
However a have a struct
typedef struct{
TTamias* Tamies;
}TPinakasTamiwn;
And TTamias is type
typedef struct{
int time_busy; /*xronos apasxolhshs tou tamia*/
int time_inactive; /*xronos pou o tamias einai adranhs*/
int arithos_pelaton; /*posous pelates eksipiretise o tamias*/
int enapomenon_xronos; /*enapomenon xronos eksipiretisi enos pelath*/
}TTamias;
With this function in main i create an array
void DimourgiaTamiwn(TPinakasTamiwn* tamias)
{
tamias->Tamies = (TTamias*)malloc(sizeof(TTamias) * TAMIES);
}
After some comparisons i want to raise the size of array with this function
int ProsthikiTamia(TPinakasTamiwn* tamias,int plithos_tamiwn)
{
TTamias* NeoiTamies;
int neo_plithos = plithos_tamiwn + 1;
NeoiTamies = (TTamias*)malloc(sizeof(TTamias) * neo_plithos);
for(int i = 0; i < plithos_tamiwn; i++)
NeoiTamies[i] = tamias->Tamies[i];
for(int i = neo_plithos - plithos_tamiwn; i < neo_plithos; i++)
TamiasDimiourgia(&NeoiTamies[i]);//fuction to initialize the data member of extra index
tamias->Tamies = (TTamias*)realloc(tamias->Tamies , neo_plithos);// <-----PROBLEM
for(int i = 0; i < neo_plithos; i++)
tamias->Tamies[i] = NeoiTamies[i];
free(NeoiTamies);
return neo_plithos;
}
The function return the new size that is raise than one.
I create a local array and copy to that the main array,
i want to reallocate the main array and copy again the local array to new main array.
Doesn't appear compile error,but in execution (also at debug) the program break at realloc.
When reallocating, you have forgotten to multiply the dimension by the unit size. The correct line shall be:
tamias->Tamies = (TTamias*)realloc(tamias->Tamies , sizeof(TTamias) * neo_plithos);
let's say I have a functions below.
void function createBands(boolean option) {
int i, j;
int ***bands = (int ***)malloc((SIZE + 1) * sizeof(int **));
for (i = 0; i < SIZE; i++) {
bands[i] = (int **)malloc(HEIGHT * sizeof(int *));
for (j = 0; j < HEIGHT; j++)
bands[i][j] = (int *)malloc(WIDTH * sizeof(int));
}
iterator *it =
createIterator(params); // do not be confused it is a structure with
// methods andaeribute just like Iterator class in
// java . Methods are poniters to functions.
repare_array(bands[Size], it);
}
void prepare_array(int **band, iterator *it) { read_array(band, it); }
read_array(int **band, iterator *it) {
for (int i = 0; i < Height; i++)
band[i] = (int *)it->next();
}
// Now in Iterator.c I have the iterator structure with the methods etc I will
// write just some line form iterator.
void *next() {
byte *b =
a function that reads bytes form a file and returns byte * CORECTLY !!!;
return b == NULL ? NULL : bytetoT(b);
// this function make void form byte conversion but it doesnt work so I make
// only a cast in read_aray as you see. SUppose just return b wich is byte(i
// know in C isn't any byte but I redeclared all the types to be JAVA.)
}
the questions is where I should allocate the bands because in this situation the 1D vector return by function is ok because I see the values in the function scope. But when it is return to array[i] I got a unallocated 3dVector.
I need to recieve bands[size][i][j] with the data form b. In b the data is good then I ve gote bands null.
What I have do so far I make another allocation in prepare aray before the call to read_array where I allocate **band and then I have some results but I am not confident.
Sorry for the confusion! And every comment is good for me. Maybe what I have do is ok I do not know!.
I am not new to C I just do not work with pointers for a long time.
If it is a 2D pointer(**) you have to assign it with the address of 2D array and if it is 1D array you have to assign it with the address of 1D array.
For your read_array function
read_array(int**array...)
{
for(i=0;i<HEIGHT(the same as in allocation);i++)
`enter code here`array[i] = function();//function return an 1D array
}
Make sure that function() returns the address of the 1D array.
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");