2016-11-18 62 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; 
    } 
}