代码之家  ›  专栏  ›  技术社区  ›  lplplplp

为什么不能访问函数外的结构指针

  •  1
  • lplplplp  · 技术社区  · 2 年前

    描述问题:

    任何尝试访问*(缓冲区+在此插入一些索引)->malloc函数之外的数据会导致以下错误

    mem* demo = malloc(2);
    if(*(demo+1)->data == 0x00) {
    ... do some stuff here 
    }
    

    kernel.c:96:21: error: invalid type argument of '->' (have 'int')
       96 |         if(*(demo+1)->data == 0x00) {
    

    //Licensed under public domain
    //also please note there is no standart library this is on a embedded system
    
    typedef struct{
        _Bool allocated;
        unsigned char data;
    } mem;
    mem memory[1000];
    
    mem* malloc(size_t size){
        mem* buffer[size];
        unsigned int successfulCounts = 0;
        unsigned int bufferCounter = 0;
        for(unsigned int i = 0; i < sizeof(memory); i++){
            //Hey that's available memory for us
            if(memory[i].allocated == 0){
                //because buffer is 16 4 items in memory (16*4)-15*4 can be found like this
                if(successfulCounts < sizeof(buffer)-sizeof(buffer-1)){
                    *(buffer+successfulCounts) = &memory[i];
                    successfulCounts++;
                    memory[i].allocated = 1;
                }else{
                    break;
                }
            }
        }
        return buffer;    
    }
    
    
    //... some more code that implements stuff like free() and calloc()
    

    当函数中的mem*更改为无符号字符并返回时 *(buffer+1) 我可以出于某种奇怪的原因访问数据,我可以得到与我推送的数据完全相同的数据。没有任何东西像我预期的那样由于某种奇怪的原因而损坏

    2 回复  |  直到 2 年前
        1
  •  0
  •   Vlad from Moscow    2 年前

    此if语句

    if(*(demo+1)->data == 0x00) {
    

    相当于

    if( *( ( demo + 1 )->data ) == 0x00) {
    

    data 不是指针。它有类型 unsigned char

    typedef struct{
        _Bool allocated;
        unsigned char data;
    } mem;
    

    if( (demo+1)->data == 0x00) {
    

    请注意,该函数在任何情况下都是无效的

    mem* malloc(size_t size){
        mem* buffer[size];
        //...
        return buffer;    
    }
    

    mem * 而返回表达式的类型为 mem ** . 此外,该函数返回一个指向局部对象(数组)的指针。因此,返回的指针不会无效,因为数组在退出函数后将不活动。

        2
  •  0
  •   Maxwell D. Dorliea    2 年前

    您的问题是在使用箭头运算符(-gt;)之前取消引用指针。

    箭头运算符(-gt;)当您希望使用指针访问结构的成员时使用。

    struct new_t
    {
        char *str;
        int num;
    };
    
    struct new_t p1 = {"Dog", 5};
    struct *ptr = &p;
    
    char *s = ptr->str; //is valid
    
    char *s1 = ptr.str; // is not valid
    
    char *s2 = *(ptr)->str; // is not valid
    
    

    int n = p1.num; //is valid
    
    n = p1->num; //is not valid
    

    if(*(demo+1).data == 0x00) {
    ... do some stuff here 
    }
    

    if((demo+1)->data == 0x00) {
    ... do some stuff here 
    }