-1

I am trying to print all of the content in enum in a single line using the tab to separate each shirt size. When I try to compile my program it prints out random numbers instead of S,M,L,XL.

Here is my program:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

enum SIZE{S,M,L,XL};

  int i,j;

int main()
{
enum SIZE s;

int t[4][4]={1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7};

  int *p=t;

/********DISPLAY ARRAY******************/

printf("This is our inventory \n");

  for(s=S; s<=XL; s=(s+1))
  {
      printf("%d \t", t[s]);
  }

   printf("\n");

 for( i=0; i<4; i++)
 {
    for(j=0;j<4; j++)
      {
            printf("%d\t", *p++);
      }


    printf("\n");
 }
/*****************************************/

printf("\n\n");
system("PAUSE");
return 0;
}

output:

This is our inventory
2686668         2686684         2686700         2686716
1       2       3       4
5       6       7       8
9       1       2       3
4       5       6       7

Press any key to continue . . .


I don't understand why the following line is being printed out:

2686668         2686684         2686700         2686716

as opposed to:

S             M               L              XL

Can someone explain what is causing this to occur?

JonSnow
  • 67
  • 3
  • 14

3 Answers3

2

enums in C don't have names (see this tutorial)

Try this instead: How to convert enum names to string in c

Community
  • 1
  • 1
Longhup
  • 101
  • 6
1

As an alternative to @Longhup answer, you can use X-Macros:

#include <stdio.h>

#define SIZES \
    X(S) \
    X(M) \
    X(L) \
    X(XL)  

#define X(a) a,
enum SIZE{SIZES};
#undef X

#define X(a) #a,
static char *arr[] = {SIZES};
#undef X

int main(void)
{
    int i;

    for (i = 0; i <= XL; i++) {
        printf("%s\n",arr[i]);
    }
    return 0;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
1

The line

printf("%d \t", t[s]);

is printing out pointer values (&t[s][0]), not the values of the enumeration type, hence the weird numbers.

Unfortunately, there's no magic to enumeration constants that allows you to display the identifier based on the corresponding value. I usually use an array of strings corresponding to the enum identifiers.

John Bode
  • 119,563
  • 19
  • 122
  • 198