Hi guys I am working on a program and I am having problem assigning null or 0 to a value in a structure.My structure looks like this:
struct question {
exprstr expr;
float ans;
int level;
int score;
//optional
int hit; //no. of times used by students
int correct; //no of times correct answer is returned by students
} bank[MAXQ];
Actually I just want to replace the current contents with another user input it won't work.Here's part of the code for reference:
showexpr();//prints out a numbered list of mathematical expressions
printf("Please enter the number of the expression that you want to edit:\n");
scanf("%d", &qno);
TAB4; bank[qno].expr=0;//this is the problematic part
printf("Please re-enter the expression after editing below:\n");
TAB4;
scanf("%s", &bank[qno].expr);
fflush(stdin);
bank[qno].ans = evaluate(bank[qno].expr);
The membervariable that has problems is of type exprstr. What is this type? It isn't build in or standard (or i just havent seen it before), can you upload its defenition?
1) I'm assuming since you are scanning the expression is as a string (%s) with scanf, that exprstr is char*. In that case, you need to allocate memory for each expr for each element of bank. This means you need to do something like:
Where MAXSIZE is the maximum size of the expression. You could just allocate all this space once you declare bank by looping for each element of bank and calling malloc().
2) When you use scanf() on a string, do not include the address-of operator (&). Your scanf statement should look like:
scanf("%s", bank[qno].expr);
3) What are those TAB4; statements???
Here is how I altered your code to make it work (had to change some stuff around cuz I don't have your full code):
#include <stdio.h>
#include <stdlib.h>
#define MAXQ 10
struct question {
char* expr;
float ans;
int level;
int score;
//optional
int hit; //no. of times used by students
int correct; //no of times correct answer is returned by students
};
int main() {
struct question bank[MAXQ];
int qno;
printf("Please enter the number of the expression that you want to edit:\n");
scanf("%d", &qno);
bank[qno].expr=0;//this is the problematic part
printf("Please re-enter the expression after editing below:\n");
bank[qno].expr = (char*)malloc( sizeof( char ) * 10 );
scanf("%s", (bank[qno].expr));
printf("%s", bank[qno].expr );
return 0;
}