473,701 Members | 2,918 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When you declare an array of chars and store a string in it, where isthe position of the null character \0? And what happens to the unused memorylocations ?

When you declare an array of chars and store a string in it, where is
the position of the null character \0? And what happens to the unused
memory locations?

#include <stdio.h>
int main(void)
{
char gstring2[25] = "dudes";
gstring2[5] = 'a';
printf("%s \n", gstring2);
return 0;
}

The output of main function was

dudesa

How come this code works, and the statement
gstring2[5] = 'a';
doesn't overwrite the null character?
Jun 27 '08 #1
8 2445
Gary wrote:
When you declare an array of chars and store a string in it,
where is the position of the null character \0?
Wherever you ask it to be, if you ask there to be one.
And what happens to the unused memory locations?
Uninitialised elements of a struct or array object will
be 'zero initialised'.
#include <stdio.h>
int main(void)
{
char gstring2[25] = "dudes";
Same as...

char gstring2[25] =
{ 'd', 'u', 'd', 'e', 's',
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
gstring2[5] = 'a';
printf("%s \n", gstring2);
return 0;
}

The output of main function was

dudesa

How come this code works, and the statement
gstring2[5] = 'a';
doesn't overwrite the null character?
It does overwrite the null character, which was followed by
another one.

You need to be careful though of situations like...

char foo[5] = "dudes";

C, unlike C++, allows such an initialisation. There is no
terminating null stored as there is no room for it.

--
Peter
Jun 27 '08 #2
Gary wrote:
When you declare an array of chars and store a string in it, where is
the position of the null character \0?
After the last character of string data.
And what happens to the unused
memory locations?
They are set to zero.
#include <stdio.h>
int main(void)
{
char gstring2[25] = "dudes";
gstring2[5] = 'a';
printf("%s \n", gstring2);
return 0;
}

The output of main function was

dudesa
You overwrote the null terminator with a character.
How come this code works,
Because there were extra characters that were set to zero due to the
partial initialization.
and the statement
gstring2[5] = 'a';
doesn't overwrite the null character?
It did, but a new terminator was in place.

If you had this:
char str[] = "dudes";

Then you'd probably be in trouble. The next adjacent byte wouldn't even
belong to your object so overwriting the null terminator would cause
undefined behavior as soon as you tried a string operation.

Brian
Jun 27 '08 #3
On Mon, 05 May 2008 15:17:44 -0700, Peter Nilsson wrote:
You need to be careful though of situations like...

char foo[5] = "dudes";

C, unlike C++, allows such an initialisation. There is no
terminating null stored as there is no room for it.

yes and you get garbage on the screen:

#include <stdio.h>
int main( void )
{
char oye[2] = "ok";

printf("%s\n", oye);

return 0;
}

============= OUTPUT =============
/home/arnuld/programs/C $ gcc -ansi -pedantic -Wall -Wextra test.c
/home/arnuld/programs/C $ ./a.out
okH▀ ┐3.L
/home/arnuld/programs/C $

it *accidentally* terminated because at some random place in memory it
found the NULL ?

--
http://lispmachine.wordpress.com/
my email ID is @ the above blog.
just check the "About Myself" page :)

Jun 27 '08 #4
rio

"arnuld" <su*****@see.si gs.invalidha scritto nel messaggio
news:pa******** *************** *****@see.sigs. invalid...
>On Mon, 05 May 2008 15:17:44 -0700, Peter Nilsson wrote:
>You need to be careful though of situations like...

char foo[5] = "dudes";

C, unlike C++, allows such an initialisation. There is no
terminating null stored as there is no room for it.


yes and you get garbage on the screen:

#include <stdio.h>
int main( void )
{
char oye[2] = "ok";
is it not better oye[4] = "ok"; ?
"ok" is o+k+\0
printf("%s\n", oye);

return 0;
}

============= OUTPUT =============
/home/arnuld/programs/C $ gcc -ansi -pedantic -Wall -Wextra test.c
/home/arnuld/programs/C $ ./a.out
okH▀ ┐3.L
here someone can see that "\0" is not copied from "ok" to oye[2]
/home/arnuld/programs/C $

it *accidentally* terminated because at some random place in memory it
found the NULL ?

--
http://lispmachine.wordpress.com/
my email ID is @ the above blog.
just check the "About Myself" page :)


Jun 27 '08 #5
arnuld wrote:
On Mon, 05 May 2008 15:17:44 -0700, Peter Nilsson wrote:
You need to be careful though of situations like...

char foo[5] = "dudes";

C, unlike C++, allows such an initialisation. There is no
terminating null stored as there is no room for it.


yes and you get garbage on the screen:
printf("%s\n", oye);
No, you get undefined behavior.


Brian
Jun 27 '08 #6
"rio" <a@b.cwrites:
"arnuld" <su*****@see.si gs.invalidha scritto nel messaggio
news:pa******** *************** *****@see.sigs. invalid...
>>On Mon, 05 May 2008 15:17:44 -0700, Peter Nilsson wrote:
>>You need to be careful though of situations like...

char foo[5] = "dudes";

C, unlike C++, allows such an initialisation. There is no
terminating null stored as there is no room for it.

yes and you get garbage on the screen:

#include <stdio.h>

int main( void )
{
char oye[2] = "ok";

is it not better oye[4] = "ok"; ?
"ok" is o+k+\0
Not to illustrate the point, no. Both Peter Nilsson and Arnuld posted
code that has an array that is not a string, and in both cases it was
deliberate.

If you want to fix the problem, it is hard to beat 'char oye[] = "ok";'
since you then don't need a size. If you must have a size, anything
other than 3 will be mildly confusing in this example.
>--
http://lispmachine.wordpress.com/
<snip>

Best to trim your replies a bit more. In particular, remove sig blocks
unless you are commenting on them.

--
Ben.
Jun 27 '08 #7
rio
"arnuld" <su*****@see.si gs.invalidha scritto nel messaggio
news:pa******** *************** *****@see.sigs. invalid...
>On Mon, 05 May 2008 15:17:44 -0700, Peter Nilsson wrote:
>You need to be careful though of situations like...

char foo[5] = "dudes";

C, unlike C++, allows such an initialisation. There is no
terminating null stored as there is no room for it.


yes and you get garbage on the screen:

#include <stdio.h>
int main( void )
{
char oye[2] = "ok";
is it not better oye[4] = "ok"; ?
"ok" is o+k+\0
printf("%s\n", oye);

return 0;
}

============= OUTPUT =============
/home/arnuld/programs/C $ gcc -ansi -pedantic -Wall -Wextra test.c
/home/arnuld/programs/C $ ./a.out
okH▀ ┐3.L
here someone can see that "\0" is not copied from "ok" to oye[2]
/home/arnuld/programs/C $

it *accidentally* terminated because at some random place in memory it
found the NULL ?

--
http://lispmachine.wordpress.com/
my email ID is @ the above blog.
just check the "About Myself" page :)

Jun 27 '08 #8
rio
"arnuld" <su*****@see.si gs.invalidha scritto nel messaggio
news:pa******** *************** *****@see.sigs. invalid...
>On Mon, 05 May 2008 15:17:44 -0700, Peter Nilsson wrote:
>You need to be careful though of situations like...

char foo[5] = "dudes";

C, unlike C++, allows such an initialisation. There is no
terminating null stored as there is no room for it.


yes and you get garbage on the screen:

#include <stdio.h>
int main( void )
{
char oye[2] = "ok";
is it not better oye[4] = "ok"; ?
"ok" is o+k+\0
printf("%s\n", oye);

return 0;
}

============= OUTPUT =============
/home/arnuld/programs/C $ gcc -ansi -pedantic -Wall -Wextra test.c
/home/arnuld/programs/C $ ./a.out
okH▀ ┐3.L
here someone can see that "\0" is not copied from "ok" to oye[2]
/home/arnuld/programs/C $

it *accidentally* terminated because at some random place in memory it
found the NULL ?

--
http://lispmachine.wordpress.com/
my email ID is @ the above blog.
just check the "About Myself" page :)

Jun 27 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
2543
by: Simon | last post by:
Hi, If I have a string, (variable len), and I am looking for the first position of one char in array starting from position 'x' For example, // the 'haystack' $string = "PHP is great, php is ok"; // the needles
5
2338
by: ali | last post by:
Hi, I'm trying to understand the reason for different output on the following codes Code1: #include <iostream.h> int main()
9
6275
by: Durgesh Sharma | last post by:
Hi All, Pleas help me .I am a starter as far as C Language is concerned . How can i Right Trim all the white spaces of a very long (2000 chars) Charecter string ( from the Right Side ) ? or how can i make a fast Right Trim Function in c,using Binary search kind of fast algorithm ? Offcourse...I can use the classical approach too. like : Start from the right most charecter of the string to the left of the
7
1862
by: JS | last post by:
I have this struct: int main() { struct jb { char actor; struct jb *next; }; struct jb *bond;
2
6858
by: melanieab | last post by:
Hi, I'm trying to store all of my data into one file (there're about 140 things to keep track of). I have no problem reading a specific string from the array file, but I wasn't sure how to replace just one item. I know I can get the entire array, then save the whole thing (with a for loop and if statements so that the changed data will be saved), but it seems like a lot of unnecessary reading and writing. Is there a way to directly save...
23
7405
by: sandy | last post by:
I need (okay, I want) to make a dynamic array of my class 'Directory', within my class Directory (Can you already smell disaster?) Each Directory can have subdirectories so I thought to put these in an array. The application compiles but aborts without giving me any useful information. What I suspect is happening is infinite recursion. Each Directory object creates an array of Subdirectories each of which has an array of...
10
18634
by: Lonifasiko | last post by:
Hi, Just want to replace character at index 1 of a string with another character. Just want to replace character at that position. I thought Replace method would be overloaded with an index parameter with which you can write wanted character at that position. But no, Replace method only allows replacing one known character with another. The problem is I don't know the character to replace, just must replace the character at a known...
4
3744
by: Chronictank | last post by:
Hi, as a bit of background (and seeing as it is my first post :)) i am a complete newbie at perl. I literally picked it up a week ago to do this project as it seemed like the best choice for a language to connect to a SQL database in a Unix envirment as well as script parsing so there is more than likely a ton of things i could have done a better way. I have been at this for 3 days now and cant for the life of me work out why the code is...
9
5746
by: qglyirnyfgfo | last post by:
I was reading an article regarding .Net arrays and on that article, the author mentioned something about SZ arrays. As far as I can tell, SZ arrays are one dimension arrays that are zero based, am I correct on this? Also, can someone tell me what does ôSZö stands for? Thank you.
0
9232
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9084
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8936
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7827
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectŚplanning, coding, testing, and deploymentŚwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5905
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4411
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3104
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2036
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.