我正在寻找约一天如何解决我的问题。我找到类似于我的问题的解决方案,但是当我应用更改错误时: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;
}
答案 0 :(得分:1)
尽量避免在代码中使用太多*,
在进行一些更改后能够运行它,请参阅下一行中的ideone链接。
#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;
}
}
答案 1 :(得分:1)
只需替换
_st->mark = malloc(2 * sizeof(char));
使用
(*_st)->mark = malloc(2 * sizeof(char));
_st 是指针,内容是结构的地址,所以......
1)首先你需要取消引用 _st ,然后...... 2)第二,你得到值,你指向字段标记
这就是全部!