2016-11-18 87 views
-1

我四处寻找如何解决我的问题。我找到类似于我的问题的解决方案,但是当我应用更改错误时:error: request for member 'mark' in something not a structure or union不断显示。为函数中的char数组指针分配内存

我到目前为止是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

Postfix' - >'具有比一元'*'更高的优先级。 – EOF

+0

此代码充满语法错误。而且,'john'不是一个指向结构体的指针。 – melpomene

+1

@EOF即使添加parens也无济于事。 '_st'是一个三重指针; '*'和' - >'只能解除引用两次。 – melpomene

回答

1

只需更换

_st->mark = malloc(2 * sizeof(char)); 

随着

(*_st)->mark = malloc(2 * sizeof(char)); 

_st是一个指针至极内容是结构的地址,所以...

1)首先你需要提领 _st,并...
2)第二,与你,你点到外地马克

这一切!

1

尽量避免在你的代码太多* S,

能够作出一些改变后运行它,请参阅在该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; 
    } 
}