Name variables dynamically - c

I am creating n threads. I would like to create n variables b1,b2,b3,.,bi,..bn.
How can I do this in C? I mean to choose the name of the global variable according to the number of the thread.
thanks

Taken from NapoleonBlownapart's comment to the OP: "You can't. Variable names only exist at compile time, while threads only exist at runtime."
Use an array, with as much elements as you have threads. Then use the thread's number as index to the arrary
See some pseudo code below:
#define THREAD_MAXIMUM (42)
int b[THREAD_MAXIMUM];
thread_func(void * pv)
{
size_t i = (size_t) pv;
int bi = b[i];
...
}
int main()
{
...
for(size_t i = 0; i < THREAD_MAXIMUM; ++i)
{
b[i] = some thread specific number;
create-thread(thread_func, i) /* create thread and pass index to array element);
}
...
}

You can try with arrays or vectors(in C++). I would have preferred coding in C++ and use vector instead of C and array.
Simple implementation with array can be as follows -
#define MAX_THREAD(100)
int var[MAX_THREAD]
ThreadImpl(Params)
{
int i = (int) Params;
int vari = var[i];
}
int main()
{
for(int i = 0; i < MAX_THREAD; ++i)
{
var[i] = val; (val can be ThreadID or other value as per requirement)
pthread_create(ThreadImpl, ... other params);
}
return 0;
}

Related

Everytime I declare I function, my variable made by the function changes. C Language

so I am working on my Binary adding program, but now I am stuck. I want to declare 2 variables for the first binary and second one, so I use the getBinary function I created to declare these 2. However, after I entered value for firstBin, I got the value I want, but after I entered the value for secBin, the value of firstBin somehow changes and become the same as secondBin. I was hoping for the variable to be unchangable. Thanks for the help
#include <stdio.h>
int * getBinary(){
int i;
int j;
static int first8bits[8];
for (i = 0; i != 8; i++){
printf("Input 8-bits Binary:");
scanf("%d",&first8bits[i]);
}
for (j = 0; j != 8; j++)
printf("%d",first8bits[j]);
printf("\n");
return first8bits;
}
int main(){
int o;
printf("Input the first Set of Binary...");
const int * firstBin = getBinary();
printf("Input the second Set of Binary...");
int * secBin = getBinary();
for (o = 0; o != 8; o++)
printf("%d",firstBin[o]);
}
Because of the static keyword.
Don't use static. Try:
int* first8bits = malloc(8 * sizeof(int));
This way you will allocate new memory each time you call it. You can still access it with the same [ i ] subscript. Remember to free the memory again at the end of main!
free(firstBin);
free(secBin);

I implemented a Map object in C, but using it gives me a Segmentation Fault

Below, I've defined a Map struct in C. It functions as a map, with setValue and getValue functions. Key values default to -1.
typedef struct {
int key;
int value;
} Index;
typedef Index Map[1000];
void initMap(Map *map)
{
for (int i = 0; i < 1000; i++)
{
Index thisIndex = *map[i];
thisIndex.key = -1;
thisIndex.value = 0;
}
}
int getValue(Map *map, int keyToGet)
{
for (int i = 0; i < 1000; i++)
{
Index thisIndex = *map[i];
if (thisIndex.key == keyToGet)
{
return thisIndex.value;
break;
}
}
return -1;
}
void setValue(Map *map, int keyToSet, int valueToSet)
{
int set = 0;
for (int i = 0; i < 1000; i++)
{
Index thisIndex = *map[i];
if (thisIndex.key == keyToSet)
{
thisIndex.value = valueToSet;
set = 1;
break;
}
}
if (set == 1)
return;
for (int i = 0; i < 1000; i++)
{
Index thisIndex = *map[i];
if (thisIndex.key == -1)
{
thisIndex.key = keyToSet;
thisIndex.value = valueToSet;
break;
}
}
}
int findValue(Map *map, int valueToGet)
{
for (int i = 0; i < 1000; i++)
{
Index thisIndex = *map[i];
if (thisIndex.value == valueToGet)
return thisIndex.key;
}
return -1;
}
At some point in the code, when run, I get a SegFault, presumably for accessing or trying to write over memory over which I do not have jurisdiction. My question is, where is that happening? Which function could be doing that, and where? I've sifted through multiple times and I can't seem to find where that would be happening.
There are two major errors in your code.
First, you typedef Map to an array. That means when you have a function prototype like this:
int getValue(Map *map, int keyToGet);
you really get something like this:
int getValue(Index (*map)[1000], int keyToGet);
In C, definition mimicks use, so you should access your map elements like this:
Index thisIndex = (*map)[i];
Your way to use it, *map[i] is equivalent to *(map[i]) and requires the array to be an array of 1,000 pointers to Index, which it isn't.
The (*map)[i]sytnax complicated, and you don't need it. Because your Map is an array, it decays into a pointer to its first element. You do not need to pass a pointer to an array if you want to modify the elements. It is enough to pass a pointer to the first element, which in your case can be either of:
int getValue(Map map, int keyToGet);
int getValue(Index map[], int keyToGet);
int getValue(Index *map, int keyToGet);
Accessing the elements of the array is then just map[i].
Fixing that fixes your segmentation fault, but it doesn't fix the fact that your map doesn't work. When you assign to a struct like this:
Index thisIndex = map[i];
and then modify thisIndex, you will not modify anything in your map! Here, thisIndex is a copy. When thisIndex goes out of scope, all modifications are lost.
You can either use the map directly:
if (map[i].key == keyToSet) {
map[i].value = valueToSet;
return;
}
(and why don't you? thisIndex is longer than map[i]), or you can make thisIndex a pointer to the array element:
Index *thisIndex = &map[i];
if (thisIndex->key == keyToSet) {
thisIndex->value = valueToSet;
return;
}
Here, you access and modify the fields of map[i] through the pointer.
Hiding an array in a typedef is probably not such a good idea. Perhaps at one time you want to keep the number of active items alongside the array. (That would make your code more efficient, because you wouldn't have to traverse all 1,000 items in the worst case.) In that case, you could make Map a struct with an array of 1000 key/value pairs and a count. Then you would have to pass pointers to the struct type, so that you can update the fields. This is left as an exercise ... :)

C: How to sort a Struct by one of its element? Can't use pointers

How do I sort struct like this one:
typedef struct
{
int weight;
int price;
Color color;
Equip equip;
}Cars;
by one of it's attributes like price, or weight? Automobil array is previously declared.
I can't use pointers, and any other built-in function.
Cars automobil[5];
Cars mobilOne={};
for(i=0; i<5; i++)
{
if((i+1)==5)
{
break;
}else
{
if (automobil[i].weight> automobil[i+1].weight)
{
mobilOne = automobil[i];
automobil[i] = automobil[i+1];
automobil[i+1] = mobilOne;
}
}
}
I tried to do this, this way, but it does not do anything...
Also if someone could tell me, how can I pass a struct like this one into a function I would be really thankful!
OK, well first what you are trying to do is not quite as bad as some people might tell you as for small N bubble sort is still pretty fast. The following will do you and of course you need a double loop:
int main() {
Cars automobil[NC];
// Initialiase automobil here
for (int i = 0; i < NC - 1; ++i) {
int am = i;
for (int j = i+1; j < NC; ++j) {
if ( automobil[am].weight > automobil[j].weight )
am = j;
}
if ( am != i) {
Cars tmp = automobil[am];
automobil[am] = automobil[i];
automobil[i] = tmp;
}
}
for (int i = 0; i < NC; ++i)
printf("%d\n", automobil[i].weight);
}
Notice that we can copy structs but even here we try to do it as little as possible.
However, it's very easy to say "I'll never have more than ten cars" and then find you are trying to sort several thousand so I would urge you to learn and understand qsort():
int carsSort(const void *a, const void *b) {
return ((Cars *) a)->weight - ((Cars *) b)->weight;
}
int main() {
Cars automobil[NC];
// Initialiase automobil here
qsort(automobil, NC, sizeof *automobil, carsSort);
for (int i = 0; i < NC; ++i)
printf("%d\n", automobil[i].weight);
}
John
PS: in reply to "how do I pass the array to a function?" remember one of the many wise sayings of K&R: "When an array name is passed to a function, what is passed is the location of the beginning of the array".
Hence:
int carsSort(const void *a, const void *b) {
return ((Cars *) a)->weight - ((Cars *) b)->weight;
}
void sortThem(Cars autom[]) {
qsort(autom, NC, sizeof *autom, carsSort);
}
int main() {
Cars automobil[NC];
// Initialiase automobil here
sortThem(automobil);
for (int i = 0; i < NC; ++i)
printf("%d\n", automobil[i].weight);
}
Inside sortThem() "autom" is a variable whose value is the address of automobil[0].
Without going into implementation details here is a procedural algorithm for a bubble sort (not in C): Bubble Sort Algorithm. Note, as mentioned in comments, this bubble sort implementation uses nested loops.
One other item to keep in mind: In order to switch two objects, a third temporary object of the same type needs to be used. For example:
int temp
int arr1[]={2,5,7,2,9,1,8,0,5,2,1};
int count = sizeof(arr1)/sizeof(arr1[0])
for(int i = 0; i < count-1; i++ )
{
if(arr1[i]>arr1[i+1])
{
temp = arr1[i];
arr1[i] = arr1[i+1];
arr[i+1] = temp;
}
}
Because you are sorting on a single member of a collection of members, the assignment swapping routine will need to swap every member each time the condition for a swap exists, i.e. although determining if the swap condition exists only considers one member, swapping will include all members: weight, price, Color and Equip. And, if Color and Equip are of struct type (your post does not specify), then each member of these objects belonging to array elements being compared, will also need to be swapped.
You should look forward to eventually using pointers as this will significantly reduce the number of assignment statements needed to complete this sort.

Arduino - Optimising existing method for iterating through an array

Is there a more efficient and cleaner way of doing what the following method is already doing?
void sendCode(prog_uint16_t inArray[], int nLimit) {
unsigned int arr[nLimit];
unsigned int c;
int index = 0;
while ((c = pgm_read_word(inArray++))) {
arr[index] = c;
index++;
}
for (int i = 0; i < nLimit; i=i+2) {
delayMicroseconds(arr[i]);
pulseIR(arr[i+1]);
}
}
This is in reference to an existing question I had answered.
Arduino - Iterate through C array efficiently
There should be no need for the local arr array variable. If you do away with that you should both save temporary stack space and speed up execution by removing the need to copy data.
void sendCode(const prog_uint16_t inArray[]) {
unsigned int c;
for (int i = 0; c = pgm_read_word(inArray++); i++) {
if (i % 2 == 0) { // Even array elements are delays
delayMicroseconds(c);
} else { // Odd array elements are pulse lengths
pulseIR(c);
}
}
}
This code assumes that the maximum integer stored in an int is greater than the maximum size of inArray (this seems reasonable as the original code essentially makes the same assumption by using an int for nLimit).

increment in a loop and keeping state

gcc 4.4.4 c89
I have the following code and 2 structures that have to be filled.
I have 3 functions that will fill the handles for each of the devices.
However, the device_type structure will need to increment from where the last function finished.
For example:
load_resources() starts at 0 and finishes at 9
dev_types starts at 0 and finishes at 9
load_networks() starts at 0 and finishes at 9
dev_types starts at 10 and finishes at 19
load_controls() starts at 0 and finishes at 9
dev_types starts at 20 and finishes at 29
However, as I don't want to use a static or global variable is there any way I can increment a
value for this. So it will start where the last function finished.
Many thanks for any suggestions,
#define NUMBER_OF_DEVICES 10
#define NUMBER_OF_TYPES 3 /* resources
networks
controls */
int events(int evt);
int load_resources();
int load_networks();
int load_controls();
static struct device_table {
int resource_handle;
int network_handle;
int control_handle;
} dev_tbl[NUMBER_OF_DEVICES];
struct device_types {
size_t id;
int dev_handle;
int dev_type;
}dev_types[NUMBER_OF_DEVICES * NUMBER_OF_TYPES];
enum dev_name_types {RESOURCE, NETWORK, CONTROL};
/* Simulates the API calls, by returning a dummy handle */
int get_resources();
int get_networks();
int get_controls();
int main(void)
{
srand(time(NULL));
load_resources();
load_networks();
load_controls();
return 0;
}
int load_resources()
{
size_t i = 0;
for(i = 0; i < NUMBER_OF_DEVICES; i++) {
dev_tbl[i].resource_handle = get_resources();
printf("dev_tbl[i].resource_handle [ %d ]\n", dev_tbl[i].resource_handle);
dev_types[i].id = i;
dev_types[i].dev_handle = dev_tbl[i].resource_handle;
dev_types[i].dev_type = RESOURCE;
}
}
int load_networks()
{
size_t i = 0;
for(i = 0; i < NUMBER_OF_DEVICES; i++) {
dev_tbl[i].network_handle = get_networks();
printf("dev_tbl[i].network_handle [ %d ]\n", dev_tbl[i].network_handle);
dev_types[i].id = i;
dev_types[i].dev_handle = dev_tbl[i].network_handle;
dev_types[i].dev_type = NETWORK;
}
}
int load_controls()
{
size_t i = 0;
for(i = 0; i < NUMBER_OF_DEVICES; i++) {
dev_tbl[i].control_handle = get_controls();
printf("dev_tbl[i].control_handle [ %d ]\n", dev_tbl[i].control_handle);
dev_types[i].id = i;
dev_types[i].dev_handle = dev_tbl[i].control_handle;
dev_types[i].dev_type = CONTROL;
}
}
Why not change the prototypes to something like:
void load_resources(int*)
(they're not actually returning anything) then, in your main code, have:
int base = 0;
load_resources (&base);
load_networks (&base);
load_controls (&base);
Each function is then responsible for using and updating *base like this:
void load_resources (int *pBase) {
size_t i = 0;
for(i = 0; i < NUMBER_OF_DEVICES; i++, (*pBase)++) { // <-- see here!
dev_tbl[i].resource_handle = get_resources();
printf("dev_tbl[i].resource_handle [ %d ]\n", dev_tbl[i].resource_handle);
dev_types[*pBase].id = i;
dev_types[*pBase].dev_handle = dev_tbl[i].resource_handle;
dev_types[*pBase].dev_type = RESOURCE;
}
}
One option is to have each of your functions take the base index as a parameter, and returning the first available index:
int index = 0;
index = load_resources(index);
index = load_network(index);
// and so on
With this yout functions would look something like this:
int load_resources(int base_index)
{
size_t i = 0;
size_t index;
for(i = 0; i < NUMBER_OF_DEVICES; i++) {
index = base_index + i;
dev_tbl[index].resource_handle = get_resources();
//
}
return index + 1;
}
By the way, your functions do have int return types, but do not return anything.
Hold a pointer or index variable within the structure itself. It's an indicator for how far the structure has been filled up generally.
There are only two ways to persist data from one scope to the next - on the stack and on the heap. Since you have already ruled out any global variables here, that would require you to use stack variables, by passing in a parameter and returning a value, or passing in a pointer to a parameter.

Resources