473,772 Members | 2,414 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 2452
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
2547
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
2346
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
6279
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
1863
by: JS | last post by:
I have this struct: int main() { struct jb { char actor; struct jb *next; }; struct jb *bond;
2
6860
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
7416
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
18638
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
3750
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
5754
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
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10261
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...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8934
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...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6713
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
5354
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
4007
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
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.