1

I have a these structures definitions

typedef struct my_s {
   int x;
   int y;
} my_T;

typedef struct your_s {
    my_T * x;
} your_T;

your_T array[MAX_COL][MAX_ROW];

To initialize the array's pointer to NULL, can I do:

memset (array, 0, sizeof(array))

this does not look right to me.

1
  • Shouldn't that be "your_T array[MAX_ROW][MAX_COL];" since arrays in C++ are row-major order? Commented Dec 29, 2008 at 5:40

2 Answers 2

3

easiest is

your_T array[MAX_COL][MAX_ROW] = {{{0}}};
Sign up to request clarification or add additional context in comments.

3 Comments

+1, just to clarify, this works because all members not explicitly initialized will be set to 0 which is a null pointer.
hmn, trying this, compiler gave warnings: missing braces around initializer near array[0][0], my warnings are treated as errors.
sorry, forgot third set of braces. Array of array of struct.
1
typedef struct my_s {
   int x;
   int y;
} my_T;

typedef struct your_s {
    my_T * x;
} your_T;

your_T array[MAX_COL][MAX_ROW];

You cannot initialize the pointers of your_T to null using memset, because it is not specified that a null pointer has its bit pattern all consisting of null bits. But you can create your array like this:

your_T array[MAX_COL][MAX_ROW] = {{}};

The elements will be default initialized, which means for a pointer that the pointer will contain a null pointer value. If your array is global, you don't even have to care. That will happen by default then.

9 Comments

Thanks for the information. I know when global, it is defaulted to NULL, but I want to make sure it is NULL-ed since I am running in the embedded space...
right then you are fine with {{}}. the indent is that an implementation could store a value different from 0x0 in the pointer, which when dereferenced by a following read of that memory cell could cause a trap to be generated. thus, the 0x0 bit pattern is not neccassary what is in a null pointer.
+1. Empty brace initialization is illegal in C but, as I just learned, legal in C++, is this a common/useful construct?
I believe that a null pointer is defined as being 0 (C++03,4.10): ' A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates to zero.' This of course does not mean that the pointer will be zero, but that assigning 0 will make the pointer null
yes, a null pointer constant is every integer constant expression that yields zero (all bits zero). such as ('a'-'a') or simple 0. converting it to a pointer will yield a null pointer value, which is NOT all bits zero anymore necassarily.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.