我花了大约一天的时间寻找如何解决我的问题。我找到了类似于我的问题的解决方案,但当我应用更改错误:error: request for member 'mark' in something not a structure or union
一直显示。
到目前为止,我有一个struct
,我想在函数调用中初始化它。
编辑代码:
typedef struct student * Student;
struct student {
char *mark; /* or array[2] like array[0] = 'A' , array[1] = 'B' */
int age;
int weight;
};
typedef enum{
MEMORY_GOOD,
MEMORY_BAD} Status;
int main(int argc, char* argv[]) {
int status = 0;
Student john
/* Function call to allocate memory*/
status = initMemory(&john);
return(0);
}
Status initMemory(Student *_st){
_st = malloc(sizeof(Student));
printf("Storage size for student : %d n", sizeof(_st));
if(_st == NULL)
{
return MEMORY_BAD;
}
_st->mark = malloc(2*sizeof(char)); /* error: request for member 'mark' in something not a structure or union */
return MEMORY_GOOD;
}
直接替换
_st->mark = malloc(2 * sizeof(char));
(*_st)->mark = malloc(2 * sizeof(char));
_st是一个指针,其中内容是结构体的地址,所以…
1)首先需要对解引用_st,然后…
2)第二,用你得到的值指向字段标记
尽量避免代码中出现太多*,
在做了一些更改后能够运行它,请参阅下一行的ideone链接。
http://ideone.com/Ow2D2m#include<stdio.h>
#include<stdlib.h>
typedef struct student* Student; // taking Student as pointer to Struct
int initMemory(Student );
struct student {
char* mark; /* or array[2] like array[0] = 'A' , array[1] = 'B' */
int age;
int weight;
};
typedef enum{
MEMORY_GOOD,
MEMORY_BAD} Status;
int main(int argc, char* argv[]) {
Status status;
Student john; /* Pointer to struct */
/* Function call to allocate memory*/
status = initMemory(john);
printf("got status code %d",status);
}
int initMemory(Student _st){
_st = (Student)malloc(sizeof(Student));
printf("Storage size for student : %d n", sizeof(_st));
if(_st == NULL)
{
return MEMORY_BAD;
} else {
char* _tmp = malloc(2*sizeof(char)); /* error: request for member 'mark' in something not a structure or union */
_st->mark = _tmp;
return MEMORY_GOOD;
}
}