Solved

Best way to initialize arrays

Posted on 2001-06-11
9
205 Views
Last Modified: 2010-04-15
In my code I have the following declaration of Enums (I'm writing in C++ so I don't use typedef and such, but the question is for C):

enum MyColor {
   color1 = 0,
   color2,
   color3,
   color4,
   color_invalid
};

enum MyType {
   type1 = 0,
   type2,
   type3,
   type_invalid
};

Now I want to declare an array in the size of the MyType enum of type MyColor initialize it. Inside my include file I wrote:

static MyColor array[];

Inside my C code I wrote:
MyColor array[type_invalid] = { color1, color2, color3 };

The question is:
When the enum MyType changes and gets bigger I don't get any warning/error from the compiler on the line of initializing the array. Instead I get uninitialized partitioned of the array. Is there a way/trick so that the code can be safer and protect me from this problem? Maybe the compiler can issue some warning/error?
0
Comment
Question by:s_l
  • 2
  • 2
  • 2
  • +3
9 Comments
 

Expert Comment

by:aceventura
ID: 6176710
Hi !
   The compiler will not prevent you from accessing the
memory locations outside your declaration. You may have
declared array[4], but even if you try to access a[6], the
compiler will not complain, nor will it give you an error.
   If you want to trap this error, there is no direct way.
You will have to resort to round about methods using the
sizeof operator.
   See the example that I have written.

/* Size.c */
#include <stdio.h>

void main()
{
 int  array[] = { 1, 2, 3, 4, 5 };  
 /* sizeof( array ) is 20         */
 /* sizeof( array[0] ) is 4       */
 /* Count of items in array       */
 int Index;

 size_t  sizearr = sizeof(array) / sizeof(array[0]);

 printf("Array size = %d", sizearr);

 printf("\nEnter Index to get : ");
 scanf("%d",&Index);
 if (Index > sizearr)
    printf("\nYou have specified an Index out of bounds.");
 else
    printf("\nElement at location %d is %d.",
                            Index, array[Index]);
 getch();
}



Hope this helps.
Regards,
ace
0
 
LVL 6

Expert Comment

by:zebada
ID: 6176720
You say you are writing in C++ but the question is for C. Does that mean you want a solution for C code or can the solution involve C++ objects and constructors?
0
 
LVL 6

Expert Comment

by:zebada
ID: 6176725
I think I understand the problem now...

Are you asking how to get the compiler to warn you about array initialisation that contains less elements than the defined size of the array?
0
 
LVL 2

Expert Comment

by:MadYugoslav
ID: 6177293
If I understand ok You want to have properly initialized array. You may write some initialize function to do that.
This is the correct way.
Another way is to implement this query somewhere in the start of your program.
if( MyColor[color_invalid-1] != color_invalid )
   ;//Error

Same thing with types.
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 2

Accepted Solution

by:
MadYugoslav earned 200 total points
ID: 6177347
Error in previous comment !
Query should be this:
if( MyColor[color_invalid-] != (color_invalid-1) )
  ;//Error
0
 
LVL 1

Author Comment

by:s_l
ID: 6177807
zebada - this is exactly what I need. But without any tricks of C++.

aceventura - thanks for the help but it's not what I was looking for.

MadYugoslav - this is a nice idea (to check if the last element is valid or not. But how can I be sure of what the compiler puts inside if I initialized it with too few parameters? I know that in optimized mode the compilers usually don't clear arrays...
0
 
LVL 2

Expert Comment

by:obg
ID: 6177899
Ok, if I understand you correctly, you can not make this check at compile time. Instead, put a for-loop in the beginning and make the initialization there.
0
 
LVL 5

Expert Comment

by:nebeker
ID: 6178552
You will not have an "uninitialized" section of your array.  If you do not provide enough initializers for an array, the unspecified items will automatically be set to 0 (as per the C standard).

So, if you have this declaration:

int x[5] = {1};

it is the same as if you had specified:

int x[5] = { 1, 0, 0, 0, 0 };
0
 
LVL 1

Author Comment

by:s_l
ID: 6178644
Thanks. I will go with the query you suggested.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
How do I test for current date? 9 90
Is string constant address ? 10 189
C++ vs C compilers 13 155
Problem to show menu 5 82
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now