简体   繁体   English

将值分配给结构数组中的变量

[英]Assigning value to variable from struct array

I have an array of structs in my header file and I have written some code in main file.我的头文件中有一个结构数组,我在主文件中编写了一些代码。

char temp, index;
for (index = 0; index < 5; index++)
       temp = cards[index].foo;

I notice that temp gets the value of the first char but then it won't change after that;我注意到 temp 获取第一个字符的值,但之后它不会改变; ie if the first char from struct array is 'c' then it gets 'c' but if the second char is 'f' it won't get 'f' — it will stay with 'c'.即,如果结构数组中的第一个字符是“c”,那么它会得到“c”,但如果第二个字符是“f”,它就不会得到“f”——它会留在“c”。

How can I fix this?我怎样才能解决这个问题?

my struct array is in my header and looks like this我的结构数组在我的标题中,看起来像这样

struct x{
char foo;
 } cards[Size];

Hai bro i just tried your code in C it is seems to work properly.... my header file is嗨,兄弟,我刚刚在 C 中尝试了您的代码,它似乎可以正常工作.... 我的头文件是

#include<stdio.h>
#define Size 5

struct x
{
    char foo;
} cards[Size];

Main is:主要是:

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

int main()
{
    int i,index;
    char temp;
    for (i = 0; i < 5; i++)
        cards[i].foo = 'a' + i;
    for (index = 0; index < 5; index++)
    {
        printf("c[%d].foo = %c\n", index, cards[index].foo);
        temp = cards[index].foo;
        printf("t = %c\n", temp);
    }

}

output is:输出是:

c[0].foo = a
t = a
c[1].foo = b
t = b
c[2].foo = c
t = c
c[3].foo = d
t = d
c[4].foo = e
t = e

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

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