【问题标题】:Allocate memory for char array pointer of struct inside function为函数内部结构的 char 数组指针分配内存
【发布时间】:2016-11-18 18:44:37
【问题描述】:

我花了大约一天时间寻找如何解决我的问题。我找到了与我类似的问题的解决方案,但是当我应用更改错误时: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; 
}

【问题讨论】:

  • 后缀 -> 的优先级高于一元 *
  • 这段代码充满了语法错误。此外,john 不是指向结构的指针。
  • @EOF 即使添加括号也无济于事。 _st 是一个三重指针; *-> 仅取消引用两次。
  • @melpomene 啊,旧的typedefd 指针。经典。
  • 你能把它们(充满错误)指向我吗,这样,我可以修复它们。

标签: c pointers struct malloc


【解决方案1】:

只需替换

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

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

_st 是一个指针, content 是结构的地址,所以 ...

1) 首先您需要取消引用 _st,然后...
2)其次,用你得到的 value ,你指向字段 mark

就是这样!

【讨论】:

    【解决方案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; 
        }
     }
    

    【讨论】:

      猜你喜欢
      • 2015-08-22
      • 2012-07-10
      • 2021-12-12
      • 1970-01-01
      • 2013-04-18
      • 2011-02-23
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      相关资源
      最近更新 更多