I think there’s something basic that I’m not understanding(new to C) regarding strings. Basically I am using uthash and it works when I send strings directly but not from a loop(thats getting its data from an array).
Here’s an example:
enum { MAX_ID_LEN = 5 };
struct my_struct {
char id[MAX_ID_LEN]; /* key */
float price;
UT_hash_handle hh; /* makes this structure hashable */
};
struct my_struct *users = NULL;
void new_stock(char *user_id, float price) {
//printf("%c - %f \n", *user_id, price);
struct my_struct *s;
s = (struct my_struct*)malloc(sizeof(struct my_struct));
strcpy(s->id, user_id);
s->price = price;
HASH_ADD_STR( users, id, s ); /* id: name of key field */
}
int main() {
printf("starting.. \n");
new_stock("IBM", 10.2);
new_stock("goog", 2.2);
return 0;
}
That works but when I try to do the same thing from an array it does not(I get no errors when compiling).
char *name_all[] = {"ibm", "goog"};
int name_all_size =sizeof(name_all)/sizeof(char);
float price_all[] = {10.2, 2.2};
enum { MAX_ID_LEN = 5 };
struct my_struct {
char id[MAX_ID_LEN]; /* key */
float price;
UT_hash_handle hh; /* makes this structure hashable */
};
struct my_struct *users = NULL;
void insert_data() {
printf("inserting data \n");
int data_loc;
for (data_loc=0;data_loc<name_all_size;data_loc++) {
//printf("%s - %f \n", name_all[data_loc], price_all[data_loc]);
//new_stock(name_all[data_loc], price_all[data_loc]);
//new try
struct my_struct *s;
s = (struct my_struct*)malloc(sizeof(struct my_struct));
strcpy(s->id, name_all[data_loc]);
s->price = price_all[data_loc];
//printf("%s - %f \n", s->id, s->price); //ahh displays correctly but still fails
HASH_ADD_STR( users, id, s ); /* id: name of key field */
}
}
int main() {
insert_data();
return 0;
}
I’m new to C so I am probably assessing this wrong but I think it has to do with the way I’m passing the variables. When I first tried I was sending it to the new_stock function but it was only displaying the first char, so to get around the problem of passing the variable I just moved all the contents of the function into the function I was using to add all the data to but I still get the same problem.
Any idea of what I’m doing wrong?
also just out of personal interest is there any tools that warns me of problems in my code? I find gcc is helpful but once the warnings stop I have no idea how to troubleshoot. Is there something that could help me catch problems like this earlier(something more verbose than gcc). Not sure if its possible but wanted to ask.
Here’s your error:
The array
name_allis an array ofcharpointers, notchar, and therefore will only be eight-bytes if you’re on a 32-bit system with 32-bit pointers, and 16-bytes on a 64-bit system with 64-bit pointers. Keep in mind that the string literals being pointed to are not stored in the array, only the pointers to the string literals are in the array. What you really want is:That should give you a value of
2, which is the correct number of elements inname_all.