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.

1 Answer 1

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."

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.