DEV Community

loading...

Strings in C

Sanskrati Jain
CS student
Updated on ・1 min read

What is a String?
A string is a 1-d character array terminated by a null(\0). The null character is used to denote string termination, characters are stored in contiguous memory locations.

How to initialize and print a string?
To initialize and print a string there are many ways like using pointers. Three methods that I am aware of to do this are mentioned in the image.

Alt Text

Discussion (3)

Collapse
raddevus profile image
raddevus

This is a nice write-up with good small examples.
You say that the array on line 3 cannot be changed but I don't believe the array in Line 1 can be either, right?
Also, it would be nice to know the length of the final strings and/or arrays.
For example you state at the beginning that a string is a 1 dimensional array of characters terminated by \0. Is the terminating character included in the length of the string?
Is the length of str[] 4 or 5? It'll be 4, right? Doesn't include \0.
thanks

Collapse
sanskrati01 profile image
Sanskrati Jain Author

The first and the third way are the same except one is easier to type. So the comment for the third is also valid for the first.
And yes, it will not include '\0' in length. It reduces the length by 1 but it is still there.

Collapse
sanskrati01 profile image
Sanskrati Jain Author

Do let me know if anyone knows more ways to do the same.