Iterate through an array defined in other source file - c

For someone of you maybe a simple question:
How to iterate through an array defined in other c source file.
Here is an example:
Source file producer.c
typedef struct
{
int a;
int b;
}values;
values myvalues[] =
{
{ 2, 5 },
{ 10,15},
{ 20,25},
{ 30,35},
{ 40,45},
};
Source file consumer.c
static void iterateLoop (void)
{
int i;
int x = 5;
for (i = 0; i< (sizeof(myvalues)/sizeof(values)); i++)
{
// Do something with myvalues[i].a;
if (x != myvalues[i].b)
{
// something;
else
{
// something;
}
}
}
This can be done by using callbacks? I need here a 3rd source file which acts as an interface or consumer can access directly the producer?

You can do for example this:
You need a header file values.h
typedef struct
{
int a;
int b;
} values;
Source file producer.c
#include "values.h"
values myvalues[] =
{
{ 2, 5 },
{ 10,15 },
{ 20,25 },
{ 30,35 },
{ 40,45 },
};
int nbofvalues = sizeof(myvalues) / sizeof(myvalues[0]);
Source file consumer.c
#include "values.h"
extern values myvalues[];
extern int nbofvalues;
static void iterateLoop(void)
{
int i;
int x = 5;
for (i = 0; i < nbofvalues; i++)
{
// Do something with myvalues[i].a;
if (x != myvalues[i].b)
{
// something;
}
else
{
// something;
}
}
}

Related

Pointers to a struct inside a struct

I have two structures (one_d and two_d).
I have a function that will take struct two_d *smg as input. In main(), I am trying to create such smg so it will return value c increased.
My problem is that, while creating an array of struct two_d smg[2], I am not sure how to put inside information about its values, as it is a pointer to a different struct.
So how do you use pointer to a struct inside a struct? I would like to create struct two_d smg[2] but i dont now how to deal with struct one_d *a field in it
#include <stdio.h>
enum sid
{
DRB,
DRA,
};
struct one_d
{
unsigned int r;
unsigned int *p;
};
struct two_d
{
struct one_d *a;
enum sid z;
};
unsigned int getSmg(struct two_d *smg)
{
unsigned int c = 0;
const struct two_d *sd = NULL;
const struct one_d *ed = NULL;
for (sd = smg; sd->a != NULL; ++sd)
{
for (ed = sd->a; ed->p != NULL; ++ed)
{
if (DRA == sd->z)
{
/*P Increment the clear-state buffer size */
c += 1 + ed->r;
}
}
}
return c;
}
int main(void)
{
unsigned int rVal = 0;
struct two_d smg[2]={
//
// [0].a ={1,0},
// [0].z =DRA,
// [1].a={1,0},
// [1].z =DRA,
};
rVal = getSmg(smg);
printf("Return value is a %d\n", rVal);
printf("Return value is a l");
return( 0 );
}
Well, at least this compiles... I'm not game to run it, though...
For what it's worth...
enum sid { DRB, DRA, DRAwhoCares };
typedef struct {
unsigned int r;
unsigned int *p;
} oneD_t;
typedef struct {
oneD_t *a;
enum sid z;
} twoD_t;
unsigned int getSmg( twoD_t *smg ) {
unsigned int c = 0;
for( twoD_t *sd = smg; sd->a != NULL; +sd++ ) {
for( oneD_t *ed = sd->a; ed->p != NULL; ed++ ) {
if( DRA == sd->z ) {
/*P Increment the clear-state buffer size */
c += 1 + ed->r;
}
}
}
return c;
}
int main( void ) {
oneD_t foo[] = { { 1, NULL }, /* ... */ };
oneD_t bar[] = { { 1, NULL }, /* ... */ };
twoD_t smg[]={
{ foo, DRA, },
{ bar, DRA, },
{ NULL, DRAwhoCares, },
};
unsigned int rVal = getSmg( smg );
printf( "Return value: %u\n", rVal );
return 0; // return is not a function call... No parenthesis...
}

C - Want to put functions of type struct in separate .c-file

So I have this code with a struct and a bunch of functions, and I want to put those functions (at least) in a separate .c-file. However, when I do, it no longer recognizes the struct card type that I have. What do I do?
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
struct card {
int suit;
int value;
};
const char *suitName( int suitNum)
{
switch (suitNum) {
case 1: return "spades";
case 2: return "clubs";
case 3: return "hearts";
case 4: return "diamonds";
}
return "(invalid suit)";
}
struct card makeCard(int suit, int value) {
struct card tempCard;
tempCard.suit = suit;
tempCard.value = value;
return tempCard;
}
struct card *createDeck()
{
const size_t count = 52;
struct card *deck;
/* Allocate new deck of 'count' cards. */
deck = malloc(count * sizeof deck[0]);
if (!deck) {
fprintf(stderr, "createDeck(): Out of memory!\n");
exit(EXIT_FAILURE);
}
int i = 0;
struct card *deckArrayPtr = deck;
for (int suit = 1; suit < 5; suit++)
{
{
for (int value = 1; value < 14; value++) {
deck[i] = makeCard(suit, value);
i++;
}
}
}
return deck;
}
void shuffleDeck(struct card *deck) {
int cardSwitch1, cardSwitch2;
struct card temp;
cardSwitch1 = (rand() % 52);
cardSwitch2 = (rand() % 52);
temp = deck[cardSwitch1];
deck[cardSwitch1] = deck[cardSwitch2];
deck[cardSwitch2] = temp;
}
int main()
{
srand((unsigned int)time(NULL)); //initializing srand
struct card *deckAr = createDeck(); //creating the struct card deck array
for (int i = 0; i < 5000; i++)
{
shuffleDeck(deckAr);
}
for (int a = 0; a < 52; a++) {
//printf("%d of %s\n", deckAr[a].value, suitName(deckAr[a].suit));
printf("%d of %s\n", deckAr[a].value, suitName(deckAr[a].suit));
}
return 0;
}
Write a header file where you declerate your types and function prototypes
mytypes.h
struct card {
int suit;
int value;
};
const char *suitName( int suitNum);
struct card makeCard(int suit, int value);
...
Write a .c file where you implement your functions (include your header file)
myfunc.c
#include "mytypes.h"
const char *suitName( int suitNum)
{
...
}
...
Finally the file for your main program
main.c
#include "mytypes.h"
int main()
{
...
}

C: Dynamically Allocated Struct Array Usage

Getting errors such as
stats.c:28:36: error: ‘factoryStats’ has no member named ‘candyConsumed’ factoryStatsArray[producer_number].candyConsumed++;
What I want to be able to achieve is to create an array of structs, then access it's members. Is this the wrong way to do it?
Tried using -> but that shouldn't and don't work since I'm storing structs, not pointers to structs.
#include "stats.h"
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int factoryNumber = 0;
int candyProduced = 0;
int candyConsumed = 0;
double minDelay = 0;
double avgDelay = 0;
double maxDelay = 0;
} factoryStats;
factoryStats *factoryStatsArray;
int NUM_FACTORIES = 0;
void stats_init (int num_producers) {
factoryStatsArray = malloc(sizeof(factoryStats) * num_producers);
NUM_FACTORIES = num_producers;
}
void stats_cleanup (void) {
free(factoryStatsArray);
}
void stats_record_produced (int factory_number) {
factoryStatsArray[factory_number].candyProduced++;
}
void stats_record_consumed (int producer_number, double delay_in_ms) {
factoryStatsArray[producer_number].candyConsumed++;
if (factoryStatsArray[producer_number].minDelay == 0) {
factoryStatsArray[producer_number].minDelay = delay_in_ms;
} else {
if (factoryStatsArray[producer_number].minDelay > delay_in_ms) {
factoryStatsArray[producer_number].minDelay = delay_in_ms;
}
}
if (factoryStatsArray[producer_number].maxDelay == 0) {
factoryStatsArray[producer_number].maxDelay = delay_in_ms;
} else {
if (factoryStatsArray[producer_number].maxDelay < delay_in_ms) {
factoryStatsArray[producer_number].maxDelay = delay_in_ms;
}
}
factoryStatsArray[producer_number].avgDelay+= delay_in_ms;
}
void stats_display(void) {
printf("%8s%10s%10s10s10s10s\n", "Factory#", "#Made", "#Eaten", "Min Delay[ms]", "Avg Delay[ms]", "Max Delay[ms]");
for (int i = 0; i < NUM_FACTORIES; i++) {
printf("%8d%8d%8d%10.5f%10.5f%10.5f",
factoryStatsArray[i].factoryNumber, factoryStatsArray[i].candyProduced,
factoryStatsArray[i].candyConsumed, factoryStatsArray[i].minDelay,
factoryStatsArray[i].avgDelay/factoryStatsArray[i].candyConsumed,
factoryStatsArray[i].maxDelay);
}
}
structs cannot be initialized this way. Remove all those = 0 in typedef struct { ... } factoryStats;. Afterwards it compiles as in http://ideone.com/uMgDzE .

how to access first element of a struct array

So I implemented the following method. The problem is that when I begin
searching the variableVector pointer I noticed that variableVector->variables
might not be pointing to the beginning variable element.
Variable* findVariable(VariableVector *variableVector,
char *variableNameOfVariableToReturn) {
if (variableVector->size < 1) {
return NULL ; // since variableVector is empty
}
Variable *currentVariable = variableVector->variables;//<== HOW TO RESET TO BEGINNING???
int numberOfVariablesInVariableVector = variableVector->size;
for (int i = 0; i < numberOfVariablesInVariableVector; i++) {
if (strcmp(currentVariable->variableName,
variableNameOfVariableToReturn) == 0) {
return currentVariable;
} else {
currentVariable++;
}
}
return NULL ; // variable not found in variableVector
}
These are what my structs look like:
struct _Variable {
char *variableName;
char *arrayOfElements;
int32_t address;
};
typedef struct _Variable Variable;
struct _VariableVector {
int size; // elements full in array
int capacity; // total available elements
Variable *variables;
};
typedef struct _VariableVector VariableVector;
Also this is how I add a new variable:
bool appendVariable(VariableVector *variableVector, Variable *variable) {
if (variableVector->size == variableVector->capacity) {
return false;
} else { // append since vector is not full
int indexOfFirstEmptyElement = variableVector->size;
memcpy(&variableVector->variables[indexOfFirstEmptyElement], variable, sizeof(Variable));
//variableVector->variables[indexOfFirstEmptyElement] = *variable;
variableVector->size++;
return true;
}
}

Accessing certain elements in an Struct in C

So I have the following struct I created:
struct _I_TypeInstructions {
const char *instructionName;
char *opcode;
} I_TypeInstructions[] = { { "lw", "100011" }, { "sw", "101011" }, { "beq",
"000100" } };
typedef struct _I_TypeInstructions I_TypeInstructionsStruct;
If I have a new instructionName and I want to check if it is in the I_TypeInstructionsStruct how do I iterate through just the *instructionName part of the struct above. For example the function I want to write would look something like
bool checkIfInstructionIsI_Type(char *instructionName) {
// somehow iterate through instructionNames in the struct above
// checking if parameter char *instructionName in this method is equal to
// "lw" "sw" "beq" but skipping over the binary numbers.
}
Searching a list of structs is rather straight forward:
bool checkIfInstructionIsI_Type(char *instructionName)
{
for (int i = 0; i<NumInstructions; i++)
{
if (strcmp(I_TypeInstructions[i].instructionName, instructionName) == 0)
{
return true;
}
}
return false;
}
int i;
for(i = 0; i < 3; ++i)
{
if (strcmp(instructions[i].instructionName, instructionName) == 0)
{
printf("Match found");
}
}
It's generally more useful to return the actual element that matches your string. It's the same amount of work anyway.
Add an empty element to the end of your array and then you have a end marker.
typedef struct _I_TypeInstructions {
const char *instructionName;
char *opcode;
} I_TypeInstructionsStruct;
I_TypeInstructionsStruct I_TypeInstructions[] = {
{ "lw", "100011" },
{ "sw", "101011" },
{ "beq", "000100" },
{ 0, 0}
};
I_TypeInstructionsStruct *find_instruction(char *name)
{
I_TypeInstructionsStruct *i ;
for (i = I_TypeInstructions ; i->instructionName ; i++)
if (!strcmp(i->instructionName,name)) return i ;
return 0 ;
}

Resources