1

I've been doing (in C)

char array[100];
if (array == NULL)
   something;

which is very wrong (which I have finally learned since my program doesn't work). What is the equivalent where I could test a new array to see if nothing has been put in it yet?

Also, how do you make an array empty/clean it out?

I know there are other posts out on this topic out there, but I couldn't find a straightforward answer.

user963070
  • 629
  • 2
  • 19
  • 24

1 Answers1

2

An array declared with

char array[100]

always has 100 characters in it.

By "cleaning out" you may mean assigning a particular character to each slot, such as the character '\0'. You can do this with a loop, or one of several library calls to clear memory or move memory blocks.

Look at memset -- it can "clear" or "reset" your array nicely.

If you are working with strings, with are special char arrays terminated with a zero, then in order to test for an empty array, see this SO question. Otherwise if you have a regular character array not intended to represent text, write a loop to make sure all entries in the array are your special blank character, whatever you choose it to be.

You can also declare your character array like so:

char* array = malloc(100);

or even

char* array = NULL;

but that is a little different. In this case the array being NULL means "no array has been allocated" which is different from "an array has been allocated but I have not put anything in it yet."

Community
  • 1
  • 1
Ray Toal
  • 86,166
  • 18
  • 182
  • 232