Arrays: Memory


The Relationship between Strings and Arrays

A string in C is essentially a block of memory where each subsequent byte stores the next character in the string. That is, the first character goes into the first byte the second character into the second byte. In other words, all of the characters are in contiguous bytes. The end of the string is then marked with a special character '\0' called the null character. If you consider what an array looks like in memory, it is essentially contiguous blocks of the same data-type. So a string in C is a type of an array, namely a char array which is null-terminated array. The null character marks the end of the array to make it easy to know when the string ends (and thereby avoid moving off the end of an array and possibly causing a memory violation).

Figure %: "SPARK" in Memory

For example, if you declare a string char *str="SPARK"; then you can index into the string by treating str as an array. So str[0] is the character 'S'. str[3] is the character 'R'. str[5] is the null character which marks the end of the string. Many string routines rely on strings being null terminated and may cause memory violations if this is not the case.

Take a Study Break

SparkLife

Star Trek gets SEXY

Chris Pine and Zoe Saldana heat up the red carpet!

SparkLife

Are you afraid of relationships?

Auntie SparkNotes can help!

SparkLife

Wanna get JLaw's gorgeous glow?

Click here for simple, sexy makeup tricks!

SparkLife

Sexy starlet style

See every single look from the Met Gala!

SparkLife

Who'd be on your zombie-apocalypse crew?

We already dib'sed Genghis Khan.

Geek out!

The MindHut

Geeky Actors: Then and Now

Travel back in time!

The MindHut

10 Movies Better Than Their Books

What do you think?

The MindHut

How To Look Like J-Law...

When you don't look like J-Law.

The MindHut

12 Scientific Inaccuracies in Into Darkness

What did Star Trek get wrong?

The MindHut

Villains We Want These Actresses to Play

From super cute to super bad!

The Book

Cover image

Read What You Love, Anywhere You Like

Get Our FREE NOOK Reading Apps