function call from struct array [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a struct array that has the format:
struct command functions[] = {
{"1", function1},
{"2", function2},
etc....
}
In a function run(char* function), I check if the parameter is equivalent to one of the strings stored in the struct array. If it is, I want to call the corresponding function. For example, if "1" is passed in, I call function1().
How would this be accomplished?
So far, I have
run(char* function) {
for (int i = 0; i < num_functions; i++) {
if(*function == functions[i]) {
return (*function)();
}
}
}
With the following errors:
error: invalid operands to binary == (have int and struct command)
error: called object *function is not a function

There are several issues with your code that seem to be causing an error, but unfortunately you haven't posted enough for me to completely fix them.
In the line if(*function == function[i]) you are using function[i] when you probably want to be using functions[i] (with an "s")
In the same line, you are comparing a char against a struct command. You probably want to access the member of the struct that contains the string shown in your first code snippet.
You are (presumably) comparing a single character against a string. You should do this using strcmp.
You are not calling the function, you're calling a char, which just won't work.
At a guess, I think you want something like this:
run(char* function_name) {
for (int i = 0; i < num_functions; i++) {
struct_command function = functions[i];
if(strcmp(function_name, function.name) == 0) {
return function.exec();
}
}
}
This assumes that the members in your struct command are named name and exec.

Related

warning - assignment makes pointer from integer without a cast [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
i got this warning " assignment makes pointer from integer without a cast "
(MARKED IN CODE PIECE) the code works fine, what i'm doing wrong and how can i fix this warning? thanx
void Read_Keys(char *keys[MAX_LEN]) //Read the keys from input file
{
char c,Fname[MAX_LEN];
gets(Fname);
FILE *fptr = (fopen(Fname, "r")); // Input stream pointer assume
if(fptr == NULL)
{
printf("No Such File...");
exit(EXIT_FAILURE);
}
if(fptr) //if not empty get in
{
int i = 0;
while((c = getc(fptr)) != EOF) //while loop copies each char from file
{ //to keys array
** keys[i] = c; // ** WARNING IS HERE
i++;
}
keys[i+1] = END; //ending point assume
}
fclose(fptr); //Close file for security issues
} ```
The parameter keys is declared like
char *keys[MAX_LEN]
the compiler adjusts it to the following declaration
char **keys
So in this statement
keys[i] = c;
the left operand has the type char * that is it is a pointer while the right operand has the type char.
So the compiler issues a warning because this assignment does not make sense.
I suspect that in any case the parameter is declared incorrectly. It seems you mean the following declaration
void Read_Keys(char ( *keys )[MAX_LEN]);
that is you are trying to pass a two dimensional array to the function. But in any case this code snippet
int i = 0;
while((c = getc(fptr)) != EOF) //while loop copies each char from file
{ //to keys array
keys[i] = c; // ** WARNING IS HERE
i++;
}
keys[i+1] = END; //ending point assume
}
is invalid because it trues to write all the file in one record instead of an array of records.
You keys parameter is an array of MAX_LEN pointers to char. So, if you want to assign a value inside this array, it should be a pointer to a character type. Here, getc() returns a character, not a pointer.
I think what you expect is void Read_Keys(char *keys), with the following calling code:
char keys[MAX_LEN];
Read_Keys(keys);
Thus, your keys array is decayed into a char * pointer when Read_Keys is called. Inside Read_Keys, you can access all your array elements using an index, like keys[2].
Obviously, you also need to pass you array length to Read_Keys, so the function knows which array index is valid and which one is not.

Passing Struct * by reference C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
+I'm trying to pass from the main an array of CustomStruct by reference, but im doing something wrong:
I think i'm asking correctly for memory, but it doesn't seem so, because when i try to force some values, i get core dumped and i absolutely don't know why.
void readFile(OwnStruct **restaurant){
FILE *f;
int numTaules = 0;
f = fopen("hello.txt", "r");
if(f == NULL){
printf("Error at opening!\n");
exit(0);
}
fscanf(f,"%d",&numTaules);
//Asking for memory
*restaurant = (OwnStruct*)malloc(sizeof(OwnStruct) * numTaules);
//From here, at some point: Core Dumped
restaurant[0]->ocupades = 1;
restaurant[0]->disponibles = 2;
restaurant[1]->ocupades = 3;
restaurant[1]->disponibles = 4;
printf("%d\n",restaurant[0]->ocupades);
printf("%d\n",restaurant[0]->disponibles);
printf("%d\n",restaurant[1]->ocupades);
printf("%d\n",restaurant[1]->disponibles);
}
int main(){
typedef struct(){
int ocupades;
int disponibles;
}
OwnStruct *restaurant;
readFile(&restaurant);
return 0;
}
You are referencing the array wrong:
So far so good:
*restaurant = (OwnStruct*)malloc(sizeof(OwnStruct) * numTaules);
This is wrong:
restaurant[0]->ocupades = 1;
It should be:
(*restaurant)[0].ocupades = 1;
You must dereference the pointer to your pointer. That expression then points to the first element of the allocated array. The parentheses are needed, because postfix operators like EXPR[0] take precedence over unary operators like *EXPR, so *EXPR[0] is treated as *(EXPR[0]).
Suggestion: Work with a local pointer which is just Ownstruct *ptr. Then, just before returning from the function, store that pointer:
*restaurant = ptr;
Then you can just have ptr[0]->field = value type code in your function.
Your problem is that your function
void readFile(char fileName[], OwnStruct **restaurant)
expects two parameter, but you pass just one.
readFile(&restaurant);
Just write
readFile("myFile.txt", &restaurant);
or define your function as
void readFile(OwnStruct **restaurant)
The example you give should not currently compile - readFile expects a filename and a pointer to a pointer of OwnStruct. Your main is just providing the pointer.
The struct should defined somewhere at the top (before its use in main and readFile)
readFile is also reading numTauls from a file but then assuming it is at least 2 when assigning values to the allocated memory.

Converting individual pieces of assembly to machine code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to convert assembly to machine code. I have a MINGW compiler where if i type ./convert.exe mov %a then it should output 0x01 0xc0. I am thinking of using a struct listing each assembly code with its corresponding machine value. At the moment i keep getting errors like "request for member opcode in something not a structure". Any help would be appreciated.
#include <stdio.h>
#include <string.h>
struct _Instruction {
char mnemonic[10];
unsigned char opcode;} typedef Instruction;
Instruction instruction_list[] = {
{"mov", 0x01},
{"add", 0x04},
{"sub", 0x05},
{"mul",0x06},
{"div", 0x07},
{"and",0x08},
{"or",0x09},
{"xor",0x0a},
{"cmp",0x0b},
{"",-1},
};
Instruction get_inst(char mnemonic[]);
int main2(int argc, char *argv[])
{
char* instruction = argv[1];
Instruction get_inst = get_Instruction(instruction);
printf("%s ; %s",instruction_list.mnemonic,instruction_list.opcode);
return 0;
}
Instruction get_inst(char mnemonic[])
{
int i;
for(i=0; instruction_list[i].opcode != -1; i++)
{
if(!strcmp(instruction_list[i].mnemonic, mnemonic))
{
return instruction_list[i];
}
}
return instruction_list[i];
}
For one thing, your structure is declared incorrectly. You should format it like this instead:
typedef struct _Instruction {
....
} Instruction;
I'm not sure why that's not triggering syntax errors, but it's certainly not helping.
Also, you have both a variable and a function named get_inst. You call a non-existent function named get_Instruction(). You probably meant to name your function get_Instruction().
Also, the .opcode member of your structure is a single char. Your printf statement uses the "%s" format specifier to print it. This expects a string, which will cause printf to continue reading past the end of the .opcode member, displaying unpredictable garbage and accessing memory it shouldn't be touching.

return dynamic array of struct from function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
How do I dynamically create an array of struct in a function in C?
The struct:
typedef struct Track {
char artist[LONGSTR];
char file[LONGSTR];
int id;
int isAlbum;
char name[LONGSTR];
int pos;
char title[LONGSTR];
int time;
} Track;
The function:
int
processplaylist (struct Track** tracks, char* resp)
{
//count the tracks to return
//allocate space for the resulting tracks
*tracks = mem_alloc (count * sizeof (struct Track));
//process each track
return count;
}
And the usage:
char playliststr[] = "file: some-mp3\nTitle: Dire Straits - Romeo And Juliet\nName: TheRadio\nPos: 0\nId: 12\nOK\n"
struct Track* tracks = NULL;
int count = mpd_processplaylist(&tracks, playliststr);
Within the function the tracks are nicely processed and upto the return statement tracks points to the right location to get to the tracks. Most questions I have seen are about arrays to values, not structs.
This answer returns an array of structs, but I would like to return the count (question of style) and return the array through the parameter.
What is going wrong? After the function returns, count has the right value and tracks is still NULL.
As the not so nice people pointed out by down voting the question, the question is too broad and vague. I apologize for that, I was desperate.
As the nice people in the comments confirmed, the code is correct. Even though the debugger showed that just before the return statement everything was OK and after returning to the usage it was not.
By commenting out code lines and logging a lot, there are two things to note.
Within the function, you must refer to the individual tracks as (*tracks + i) or, for example, (*(*tracks + i)).file. Indeed, not shown in the sample code. I had tried *(tracks + i), &tracks[i] and tracks + i, which in the debugger all seemed to work and did not cause immediate errors. I guess the code messed up memory that only came out after the return.
Outside the function, in the usage, you refer to the tracks as an array, as tracks[i] or, for example, tracks[i].file.
I hope that at least my answer helps.

Segmentation fault using char pointers in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
With my current implementation of code, I'm getting a segmentation fault that I think is caused by trying to store several char* in another char*. However, I don't know a way around this being fairly new to C. I'm in a GLUE Unix environment. The code compiles but does not fully execute.
Here's my method that I think is causing the issue.
int totalLogins = 0, selectedLogins = 0,dateIn[3], timeIn[3], dateOut[3], timeOut[3];
int latest = 0,earliest=30,loggedIn = 0, firstTime[7][3],firstDate[7][3],i;
char* user[12], firstUser[7][12];
bool first = true;
void checkAndSetEarliest(int day)
{
first = true;
for(i = 0; i < 3 && first; i++)
{
first = (timeIn[i]<firstTime[day][i]);
}
if(first)
{
for(i = 0; i < 3; i++)
{
firstTime[day][i] = timeIn[i];
firstDate[day][i] = dateIn[i];
}
printf("user = %s\n",user);
firstUser[day] = user;
}
}
timeIn[],firstTime[][],firstDate[][], and dateIn[] are all ints
firstUser[] and user[] are char*
I'm trying to edit the contents of firstUser with the value of user.
First, the way you are using user[] in printf, it is suppose to be a char array, not an array of pointer to char (what you have declared).
Secondly, firstuser is a 2d arrray and you are using it as a 1d array.
You really need to show the definition of the variables this function uses. Fair chance that last line should be changed to:
strcpy( FirstUser[day], user );

Resources