const C结构体中的指针

时间:2018-08-03 08:03:16

标签: c

假设存在以下结构...

typedef struct MyFirstStruct
{
    uint8_t someContent;
}
typedef struct MySecondStruct
{
    MyFirstStruct* firstStructs;
    uint8_t firstStructCount;
}

...,一个函数获取以下参数。

const MySecondStruct* const secondStruct

是否可以更改任何值?

我确定这是不正确的: secondStruct->firstStructCount++

但是编译器和PC-Lint都没有抱怨secondStruct->firstStructs->someContent++

是否允许更改someContent是因为firstStructs不是const还是行为未定义?

谢谢!

2 个答案:

答案 0 :(得分:0)

只要指针不变,嵌套struct(s) firstStructs的值就可以改变。指针的常量性阻止了指针值的更改,但是结构的常量性仅意味着其值不得更改(即指针的值和计数)。

您可以在不更改指针的情况下任意修改struct(s)指向的firstStructs。您也可以从结构定义中清楚地看到这是合法的,因为firstStructs是指向struct MyFirstStruct的指针,而不是指向const struct MyFirstStruct的指针。

这里是一个示例,用于了解不带const指针的const元素的原理:

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int x;
} Simple;

typedef struct {
    Simple* s;
    int scount;
} Nested;

int main()
{
    Nested x;
    x.scount = 10;
    x.s = malloc(sizeof(Simple) * x.scount);
    const Nested n = x;
    for (int i = 0; i < n.scount; ++i)
    {
        n.s[i].x = i;
        printf("%d\n", n.s[i].x);
    }
}

答案 1 :(得分:0)

没关系,很容易检查自己:

typedef struct 
{
    uint8_t someContent;
} MyFirstStruct;
typedef struct 
{
    MyFirstStruct* firstStructs;
    uint8_t firstStructCount;
}MySecondStruct;

MyFirstStruct fs;
MySecondStruct str = {.firstStructs = &fs};
const MySecondStruct* const secondStruct = &str;

int main()
{
    secondStruct->firstStructs->someContent++;
}

但没有,因为发布的代码充满语法错误。

您当然不能更改指针本身:

这会给你错误:

typedef struct 
{
    uint8_t someContent;
} MyFirstStruct;
typedef struct 
{
    MyFirstStruct* firstStructs;
    uint8_t firstStructCount;
}MySecondStruct;

MyFirstStruct fs[2];
MyFirstStruct ss;
MySecondStruct str = {.firstStructs = fs};
const MySecondStruct* const secondStruct = &str;

int main()
{
    secondStruct->firstStructs++->someContent++;
    secondStruct->firstStructs = &ss;
}