简体   繁体   English

如何从 C 中的结构指针数组中输入 output 值

[英]How to input and output values from an array of struct pointers in C

I am trying to create an array of struct b pointers.我正在尝试创建一个 struct b 指针数组。

I do not know what the correct syntax is to create such a structure.我不知道创建这样一个结构的正确语法是什么。

This is a simplified version of what I am doing in a larger project... to create malloc, therefore I cannot use malloc.这是我在一个更大的项目中所做的简化版本......创建 malloc,因此我不能使用 malloc。

#include <stdio.h>

struct a {
    int val1;
    int val2;
} a;

struct b {
   struct a * next;

   int val1;
   int val2;
} b;
struct b * listOfB[3];



int main() {
    struct a * valueA = {1, 2};

    listOfB[0] = {valueA, 1, 2}; // assign value
    printf("%u\n", listOfB[0]->next->val1); // access value
}

If you want to do it this way you need to use compound literals如果你想这样做,你需要使用复合文字

int main() {
    struct a *valueA = &(struct a){1, 2};

    listOfB[0] = &(struct b){valueA, 1, 2}; 
    printf("%u\n", listOfB[0]->next->val1); 
}

https://godbolt.org/z/4P6jvsGeY https://godbolt.org/z/4P6jvsGeY

Please allocate the memory for the pointers to use them.请分配 memory 供指针使用。

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

      struct a{
      int val1;
      int val2;
      } a;
    
struct b {
      struct a * next;
      int val1;
      int val2;
      } b;

struct b *listOfB[3];

int main() {
        struct a * valueA;
        valueA = malloc(sizeof(struct a));

        valueA->val1 = 1;
        valueA->val2 = 2;

        listOfB[0] = (struct b *)malloc(sizeof(struct b));

        listOfB[0]->next = valueA;
        listOfB[0]->val1 = 1;
        listOfB[0]->val2 = 2; // assign value

        printf("%d\n", listOfB[0]->next->val1); // access value

        return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM