简体   繁体   中英

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; 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'.

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

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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