如何从分配函数外部访问结构指针的值?
How to access the value of a struct pointer from outsite of the allocatiing function?
我使用声明和初始化结构的文件
typedef struct {
uint8_t * ringBuffer;
size_t head;
size_t tail;
size_t capacity;
bool full;
} RingBuffer;
static inline void ringBufferInit(RingBuffer* ringBuffer)
{
ringBuffer = (RingBuffer *) malloc(sizeof(RingBuffer));
//ringBuffer->ringBuffer = buffer;
ringBuffer->capacity = 128;
printf("%d \n", ringBuffer->capacity);
}
以及我调用此函数的文件:
int main()
{
testRingBufferPushPopSingle();
}
void testRingBufferPushPopSingle()
{
RingBuffer ringBuffer;
ringBufferInit(&ringBuffer);
size_t a = (ringBuffer->capacity);
printf("%d \n", a);
}
问题是指针似乎没有在主函数中更新,因为程序打印
128
2125407052
只有 128 个值(在分配块中读取是正确的)。
知道我做错了什么吗?谢谢!
函数ringBufferInit
没有意义。在函数 testRingBufferPushPopSingle
中,您已经创建了一个 RingBuffer
.
类型的对象
RingBuffer ringBuffer;
那么函数ringBufferInit
要做的就是初始化已经创建的对象的数据成员ringBuffer
可以这样看
static inline void ringBufferInit(RingBuffer* ringBuffer)
{
//ringBuffer->ringBuffer = buffer;
ringBuffer->capacity = 128;
printf("%d \n", ringBuffer->capacity);
}
否则在函数内
static inline void ringBufferInit(RingBuffer* ringBuffer)
{
ringBuffer = (RingBuffer *) malloc(sizeof(RingBuffer));
//ringBuffer->ringBuffer = buffer;
ringBuffer->capacity = 128;
printf("%d \n", ringBuffer->capacity);
}
你修改了它的局部变量ringBuffer
(指针类型RingBuffer *
)退出函数后不会存活
我使用声明和初始化结构的文件
typedef struct {
uint8_t * ringBuffer;
size_t head;
size_t tail;
size_t capacity;
bool full;
} RingBuffer;
static inline void ringBufferInit(RingBuffer* ringBuffer)
{
ringBuffer = (RingBuffer *) malloc(sizeof(RingBuffer));
//ringBuffer->ringBuffer = buffer;
ringBuffer->capacity = 128;
printf("%d \n", ringBuffer->capacity);
}
以及我调用此函数的文件:
int main()
{
testRingBufferPushPopSingle();
}
void testRingBufferPushPopSingle()
{
RingBuffer ringBuffer;
ringBufferInit(&ringBuffer);
size_t a = (ringBuffer->capacity);
printf("%d \n", a);
}
问题是指针似乎没有在主函数中更新,因为程序打印
128
2125407052
只有 128 个值(在分配块中读取是正确的)。
知道我做错了什么吗?谢谢!
函数ringBufferInit
没有意义。在函数 testRingBufferPushPopSingle
中,您已经创建了一个 RingBuffer
.
RingBuffer ringBuffer;
那么函数ringBufferInit
要做的就是初始化已经创建的对象的数据成员ringBuffer
可以这样看
static inline void ringBufferInit(RingBuffer* ringBuffer)
{
//ringBuffer->ringBuffer = buffer;
ringBuffer->capacity = 128;
printf("%d \n", ringBuffer->capacity);
}
否则在函数内
static inline void ringBufferInit(RingBuffer* ringBuffer)
{
ringBuffer = (RingBuffer *) malloc(sizeof(RingBuffer));
//ringBuffer->ringBuffer = buffer;
ringBuffer->capacity = 128;
printf("%d \n", ringBuffer->capacity);
}
你修改了它的局部变量ringBuffer
(指针类型RingBuffer *
)退出函数后不会存活