Updating struct members in a for-loop - c

Is there a way to update struct members in a for loop, I want to avoid having to update the members one-by-one. For example:
Instead of doing this:
void Update(int vaule,struct Coolstruct *Ice)
{
int vaule;
Ice->member1=vaule;
Ice->member2=vaule;
Ice->member3=vaule;
Ice->member4=vaule;
}
I was wondering if something similar to this (pseudocode) was possible:
void Update(int vaule,struct Coolstruct *Ice)
{
int vaule;
for(int i=0;i++;i<4)
{
Ice->i =vaule
}
}

Yes, it is possible.
But you need an array of objects inside of the structure Coolstruct instead of defining multiple single objects.
Here is an example:
#include <stdio.h>
struct Coolstruct {
int b[4];
};
void Update(int vaule, struct Coolstruct *Ice)
{
for(int i=0;i<4;i++)
{
Ice->b[i] = vaule;
}
return;
}
int main(void) {
struct Coolstruct x;
int y = 25;
Update(y, &x);
for(int i = 0; i < 4; i++)
{
printf("x.b[%d] = %d\n", i, x.b[i]);
}
return 0;
}
Output:
x.b[0] = 25
x.b[1] = 25
x.b[2] = 25
x.b[3] = 25

Related

problem passing dynamic array via function c

I have this kind of code
typedef struct {
int x;
int y;
} Test;
Test* getTest(int *length) {
Test *toReturn = malloc(sizeof(Test));
// Some operations with realloc
return toReturn;
}
void printTest(Test *arrTest, int length) {
for(int i = 0; i < length; i++) {
// Some operations
}
}
int main() {
int testlength = 0;
Test *myTest = getTest(&testlength);
printTest(myTest, testLength) // Gives random numbers
}
Don't know why it gives random numbers, when I'm in the main tho (the whole code) it does not give these kinds of errors
Made minor changes to the code, see below:
#include <stdio.h>
typedef struct {
int x;
int y;
} Test;
Test* getTest(int *length) {
Test *toReturn = (Test *)malloc(sizeof(Test));
// Some operations with realloc
return toReturn;
}
void printTest(Test *arrTest, int length) {
printf("%d ", length);
for(int i = 0; i < length; i++) {
// Some operations
}
}
int main() {
int tlen = 0;
Test *myTest = getTest(&tlen);
printTest(myTest, tlen); // Gives random numbers
printf("....Exit....");
return 0;
}

C - Declaring a global array within a function not possible. Other solutions?

Here's what I'm trying to do:
I need a global array with a length that is dependent on a variable (NumOfRequests). That variable is set within a function. I don't think it's possible to declare a global array within a function as I tried to do in the following code:
static uint8 NumOfRequests;
typedef struct
{
uint16 IndexToRequest;
GdXRequestData_ts RequestData;
bool RequestSent;
} GdRequests;
static void SetupRequestStructures( void )
{
uint8 i;
for( i = 0; EepromData_ps.GD_Indices[i] != 0xFFFF; i++ )
{
NumOfRequests = i + 1;
}
GdRequests Requests[NumOfRequests];
for( i = 0; i < NumOfRequests; i++ )
{
Requests[i].IndexToRequest = EepromData_ps.GD_Indices[i];
}
}
It's not possible to declare an array and later decide what length it should be or change its length, as far as I know.
So does anyone know another solution for how to declare a global array with a length based on a variable that is set within a function?
Any feedback is appreciated. If you upvote or downvote, tell me why so I can improve with future questions.
You can use dynamic memory allocation to perform this task. Look at malloc and free. Here's a simple example of dynamic memory allocation on a global array of structs:
#include <stdio.h>
#include <stdlib.h>
typedef struct _MyStruct
{
int a;
int b;
} MyStruct;
MyStruct *g_Array = NULL;
void populatearray(MyStruct *array, int length)
{
int i;
for(i = 0; i < length; i++)
{
array[i].a = i;
array[i].b = i;
}
}
void printstructs(MyStruct *array, int length)
{
int i;
for(i = 0; i < length; i++)
{
printf("array[%d].a = %d\narray[%d].b = %d\n\n", i, array[i].a, i, array[i].b);
}
}
int main()
{
g_Array = malloc(50 * sizeof(MyStruct));
if(!g_Array)
{
puts("Malloc failed");
return 0;
}
populatearray(g_Array, 50);
printstructs(g_Array, 50);
free(g_Array);
return 0;
}

How do I call a function inside a struct?

I have this code:
int suma(int);
int produs(int);
struct calcul{
int suma();
int produs();
}
suma()=1+2+..n;// return S
produs()=1*2*..n;// return P
I want to call it in main with
calcul sp. How do I call function inside a struct?
If I give n a struct type n=5; the result to be sp(15,120).
Thanks!!!
I guess you want something like:
struct calcul
{
int suma(int n)
{
int result = 0;
for (int i = 1; i <= n; ++i)
result += n;
return result;
}
//... similar for produs
};
int main()
{
calcul sp;
int x = sp.suma(10);
};
int suma(int);
int produs(int);
and
struct calcul{
int suma();
int produs();
};
are two completely different sets of functions, even though they have the same name. The functions in your struct are member functions and can only be called on an instance of your struct. You would do it like so:
int main()
{
calcul x;
int a = x.suma(0);
int b = x.produs(1);
}

Hash table implementation bad access error

I was trying to make a hash table for my project but I keep getting bad access error. There is no mistake in syntax as compiler tells me. I think I have made a mistake in memory allocation but I can't see it. Any help is appreciated.
I get a bad access error in this loop:
hash_itself_p hash_table = (hash_itself_p)malloc(sizeof(hash_itself_t));
for (i = 0; i < 50; i++)
{
hash_table->data_id[i]->id = -1; // EXC_BAD_ACCESS here
}
And here is the all of the code:
#include <stdio.h>
#include <stdlib.h>
#define size 50
typedef struct hash_value
{
int id;
int data;
int key;
} hash_values_t[1], *hash_values;
typedef struct hash_itself
{
hash_values data_id[size];
} hash_itself_t[1], *hash_itself_p;
int hash_key(int n)
{
return ( n*n + 2*n ) % size;
}
int hash_id(int n)
{
return n % size;
}
void insert(hash_itself_p hash_table, int person)
{
int id;
int key;
key = hash_key(person);
id = hash_id(key);
if (hash_table->data_id[id]->id == -1)
{
hash_table->data_id[id]->id = id;
hash_table->data_id[id]->data = person;
}
else
{
int block = id;
while (hash_table->data_id[block%50]->id != -1)
{
block++;
if (block%50 == id) return;
}
hash_table->data_id[block]->id = id;
hash_table->data_id[block]->data = person;
}
}
void display(hash_itself_p hash_table)
{
int i;
for (i = 0; i < size; i++)
{
printf("id = %d, data = %d, key = %d \n", hash_table->data_id[i]->id, hash_table->data_id[i]->data, hash_table->data_id[i]->key);
}
}
int main()
{
int i;
hash_itself_p hash_table = (hash_itself_p)malloc(sizeof(hash_itself_t));
for (i = 0; i < 50; i++)
{
hash_table->data_id[i]->id = -1;
}
insert(hash_table, 30);
display(hash_table);
}
You've declared the data_id array in hash_itself as an array of pointers to hash_value structs. Since those pointers are not initialized, it accesses invalid memory.
I think you wanted to create an array of the structs directly, in which case you want:
typedef struct hash_itself
{
hash_values_t data_id[size];
}

passing structures to functions

How do you pass structures to a function? is it the same way as with variables (i.e. &var1 to pass it, and *ptr_to_var from function).
Suppose in the following code I wanted to send agencies[i].emps[j].SB and agencies[i].emps[j].ANC to a function which does some calculations on them and then returns a value and store it in agencies[i].emps[j].SNET
how do I go about that?
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char mat[20];
double SB;
int ANC;
double RCNSS;
double SNET;
} employee;
typedef struct {
char name[20];
employee* emps;
int emps_count;
} agency;
int main(void)
{
int num_ag, num_emps, i, j;
printf("enter number of agencies\n");
scanf("%d", &num_ag);
agency* agencies = malloc(sizeof(agency) * num_ag);
for (i = 0; i < num_ag; i++) {
sprintf(agencies[i].name, "agency %d", i+1);
printf("enter num of employees for agency %d\n", i+1);
scanf("%d", &num_emps);
agencies[i].emps = malloc(sizeof(employee) * num_emps);
agencies[i].emps_count = num_emps;
for (j = 0; j < num_emps; ++j) {
scanf("%s", &agencies[i].emps[j].mat);
}
}
for (i = 0; i < num_ag; i++) {
printf("agency name: %s\n", agencies[i].name);
printf("num of employees: %d\n", agencies[i].emps_count);
}
for (i = 0; i < num_ag; ++i) {
free(agencies[i].emps);
}
free(agencies);
return 0;
}
You can simple pass a structure pointer to your function:
// Void of a type void function, which saves result of the calculation
void modify_employee(employee * emp) {
emp->SNET = emp->SB * emp->ANC;
}
// Example of type double function, which returns result
// of of the calculation (withuot saving it)
double modify_employee2(employee * emp) {
return emp->SB * emp->ANC;
}
Use it like this:
employee* emp = malloc(sizeof(employee));
emp->SB = 20.5;
emp->ANC = 15;
printf("SNET: %f\n", emp->SNET);
modify_employee(emp);
printf("SNET: %f\n", emp->SNET);

Resources