简体   繁体   English

如何在C中的结构指针处为数组中的元素分配值

[英]How to assign value for element in array at struct pointer in C

I have struct like this: 我有这样的结构:

struct temper_t {
   unsigned char rom[8];
   struct temper_t *next;
};

In this main code, I want assign value for rom[8], how do i can do that: 在这个主要代码中,我想为rom [8]赋值,我该怎么做:

                new_node = (struct temper_t *) malloc(
                        sizeof(struct temper_t));
                new_node->next = NULL;

                int m;
                unsigned char rom_value[8];

                //Luu thong tin vao node moi
                for (m = 0; m < 8; m++) {
                    new_node->rom = rom_value[m]; // not working
                }

Thank you for reading my question. 感谢您阅读我的问题。

Update 更新资料

I create a MCVE for easy understanding: /* * test.c * * Created on: Sep 29, 2015 * Author: phuongh1 */ 为了方便理解,我创建了一个MCVE:/ * * test.c * *创建于:2015年9月29日*作者:phuongh1 * /

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

    struct temper_t {
        int rom[8];
        struct temper_t *next;
    };

    int main(void) {

        struct temper_t *new_node;
        new_node = NULL;

        int m;
        int rom_value[8];
        rom_value[0] = 10;
        rom_value[1] = 13;
        rom_value[2] = 15;
        rom_value[3] = 16;
        rom_value[4] = 18;
        rom_value[5] = 21;
        rom_value[6] = 25;
        rom_value[7] = 27;

        new_node = (struct temper_t *) malloc(sizeof(struct temper_t));
        new_node->next = NULL;

        //Luu thong tin vao node moi
        for (m = 0; m < 8; m++) {
            new_node->rom[m] = rom_value[m]; // not working
        }

    }

Update: Solved 更新:已解决

I found a reason. 我找到了原因。 Because my IDE for firmware coding and it is optimize when compling, the info in debug window shows value of new_node->rom and rom_value not matching. 因为我的IDE用于固件编码,并且在编译时已优化,所以调试窗口中的信息显示new_node-> rom的值和rom_value不匹配。 => because firmware code, so I cannot printf value. =>因为固件代码,所以我无法打印值。 After I run code with Visual Studio, they were match. 在我使用Visual Studio运行代码之后,它们是匹配的。

You forgot to specify the index of rom in the assignment loop: 您忘记在分配循环中指定rom的索引:

 //Luu thong tin vao node moi
 for (m = 0; m < 8; m++) {
      new_node->rom[m] = rom_value[m]; // not working
 }

Note : currently you are assigning to new_node->rom[m] unknown values since rom_value is not initialized. 注意 :由于rom_value尚未初始化,当前您正在分配给new_node->rom[m]未知值。

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

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