#Array Language C

1 messages · Page 1 of 1 (latest)

haughty wadi
#

I know how to make an array with x elements, and i can get values to put inside of them, but how do i name each element and use that element seperately, for example
int x[4]
how can i call the first element 'a' the use it like this printf("%d",a)

lilac violet
#

i hope i interpreted what u said right but say u have an int x[4] where x[0] is the first element u can use separate variables to represent

#

like int a = x[0]

#

and now u can printf("%d",a)

#

maybe if u want to make a struct called element with the variables 'value' and 'name'

#

so u make an element array and access the values directly like x[0].value = 1 for example

proud cloak
#

you can either use a struct to generate named variables

struct named{
  int a;
  int b;
  int c;
  int d;
}

named example;
int x = example.a;

but it wouldnt be index-able as an array.

you could just use pointers though:

int x[4];
int *a = &x[0];
printf("%d", *a);

at least this way you can still use your array, and reference an individual element by the pointer you made

ionic gyro
#

you can use like the following:

int &a = x[0]; // the variable a is like nickname/alias of x[0]
a = 10;
printf("%d\n", a);
round ferry
#

;compile c

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

typedef union _my_array_t {
int x[4];

// anonymous struct
struct {
  int a;
  int b;
  int c;
  int d;
};
} my_array_t;

int main()
{
  my_array_t v = {0};
  printf("[%d][%d][%d][%d]\n", v.x[0], v.x[1], v.x[2], v.x[3] );
  printf("[%d][%d][%d][%d]\n", v.a, v.b, v.c, v.d );
  printf("\n\n");

  v.a = 1;
  v.b = 2;
  v.c = 3;
  v.d = 4;
  printf("[%d][%d][%d][%d]\n", v.x[0], v.x[1], v.x[2], v.x[3] );
  printf("[%d][%d][%d][%d]\n", v.a, v.b, v.c, v.d );
  printf("\n\n");

  v.x[0] = 6;
  v.x[1] = 7;
  v.x[2] = 8;
  v.x[3] = 9;
  printf("[%d][%d][%d][%d]\n", v.x[0], v.x[1], v.x[2], v.x[3]);
  printf("[%d][%d][%d][%d]\n", v.a, v.b, v.c, v.d );
  printf("\n\n");

  memset(&v, 0, sizeof(v));
  printf("[%d][%d][%d][%d]\n", v.x[0], v.x[1], v.x[2], v.x[3]);
  printf("[%d][%d][%d][%d]\n", v.a, v.b, v.c, v.d );
  printf("\n\n");

  memset(&v, 0x10, sizeof(v));
  printf("[%d][%d][%d][%d]\n", v.x[0], v.x[1], v.x[2], v.x[3]);
  printf("[%d][%d][%d][%d]\n", v.a, v.b, v.c, v.d );
  printf("\n\n");

  return 0;
}
subtle compassBOT
#
Program Output
[0][0][0][0]
[0][0][0][0]


[1][2][3][4]
[1][2][3][4]


[6][7][8][9]
[6][7][8][9]


[0][0][0][0]
[0][0][0][0]


[269488144][269488144][269488144][269488144]
[269488144][269488144][269488144][269488144]
round ferry
#

@Groovyfalafel#5670 does this helps?

noble estuary
#

Sadly I think this person left.