![](/img/trans.png)
[英]How to correctly allocate memory for a structure in a function to return its value for later use and how to cast a structure into a pointer?
[英]C pointer to structure with elements that are pointers - how to allocate memory and use as function output
如果我具有以下C結構:
struct group_of_pointers {
double *p1, *p2, *p3;
} *pointers;
現在,我想為指針-> p1,指針-> p2,指針-> p3分配n個空間(每個空間的大小為double)。 我該怎么做呢? 我是否必須為指向結構“指針”本身的指針分配空間?
謝謝。
預計到達時間:相關問題:我需要此結構的原因是因為我想從一個函數返回3個可變長度的數組。 我應該做嗎
void foo(const double* const input, double *output1, double *output2, double *output3)
還是我應該做
struct group_of_pointers *foo(const double* const input)
前者看起來與捆綁在一起的輸入和輸出有些混亂。 但這僅僅是C的方式嗎?
是的,您必須首先為指針的結構分配空間。 然后為每個組件分配。
pointers = malloc(sizeof *pointers);
pointers->p1 = malloc(n * sizeof(double));
pointers->p2 = malloc(n * sizeof(double));
pointers->p3 = malloc(n * sizeof(double));
是的,因為你的pointers
變量本身是一個指針,你需要給它一些內存指向。
struct group_of_pointers {
double *p1, *p2, *p3;
} *pointers;
pointers = malloc(sizeof(*pointers));
pointers->p1 = malloc(n*sizeof(*pointers->p1));
pointers->p2 = malloc(m*sizeof(*pointers->p2));
pointers->p3 = malloc(o*sizeof(*pointers->p3));
如果我正確地閱讀了您的問題,是的,您需要“指針”結構來分配或在堆棧上分配空間,並且您為p1-p3分配了malloc()或-variant-space:
struct group_of_pointers *pointer = malloc(sizeof(*pointer));
pointer->p1 = malloc(n * sizeof(double));
pointer->p2 = malloc(n * sizeof(double));
pointer->p3 = malloc(n * sizeof(double));
/* do stuff here... */
free(pointer->p1);
free(pointer->p2);
free(pointer->p3);
free(pointer);
當然,我從未在那里檢查過malloc失敗,因此該代碼不被認為可以投入生產!
你想做什么? 是否需要一個可以指向三個double值的結構? 然后,是的,您需要為任何這些對象分配內存:
#include <stdio.h>
#include <stdlib.h>
struct group_of_pointers {
double *p1, *p2, *p3;
} *pointers;
int main(int argc, char *argv[]) {
pointers = malloc(sizeof(struct group_of_pointers));
pointers->p1 = malloc(sizeof(double));
pointers->p2 = malloc(sizeof(double));
pointers->p3 = malloc(sizeof(double));
*(pointers->p1) = 10.0;
*(pointers->p2) = 20.0;
*(pointers->p3) = 30.0;
printf("%lf %lf %lf\n", *(pointers->p1), *(pointers->p2), *(pointers->p3));
return EXIT_SUCCESS;
}
如果這三個數組高度相關,並且您經常將它們作為一個組使用,則應使用第二種方法,但是與其在堆上創建結構,不如在堆棧上創建結構,然后將其指針傳遞給函數,例如
void foo(struct group_of_pointers * ptr,const double * input);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.