473,796 Members | 2,565 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Beginner: A question about strings/arrays

I'm still a newbie into C++ programming, so I got a quite foolish
string related question.

Using: Dev-cpp 4.9.9.2 (I think Dev-Cpp uses a gcc compiler of some
sort)
If i declare a char string like this:

char szString[5] = "Hello";

The content of the szString array is now somthing similar to this:
szString[0] == H, szString[1] == e.. and so on, until szString[5] ==
\0. (right?)

But my compiler returns a following error:

"initialize r-string for array of chars is too long"

If i do the declartaion like this

char szString[6] = "Hello";

it compiles correctly. If I choose to write something on the screen
like:

cout << szString[6] << endl;

It outputs a strange symbol that often differs (Probably something in
the memory).

The 'cout << szString << endl;' ouputs Hello.

Is there something wrong with my compiler? Or is my logical talent
really that bad?

(I'm a beginner so bear with me)
Mvh

Tarjei

Aug 21 '05 #1
5 11409
Tarjei Romtveit wrote:
I'm still a newbie into C++ programming, so I got a quite foolish
string related question.

Using: Dev-cpp 4.9.9.2 (I think Dev-Cpp uses a gcc compiler of some
sort)
If i declare a char string like this:

char szString[5] = "Hello";

The content of the szString array is now somthing similar to this:
szString[0] == H, szString[1] == e.. and so on, until szString[5] ==
\0. (right?)

But my compiler returns a following error:

"initialize r-string for array of chars is too long"

If i do the declartaion like this

char szString[6] = "Hello";

it compiles correctly. If I choose to write something on the screen
like:

cout << szString[6] << endl;

It outputs a strange symbol that often differs (Probably something in
the memory).

The 'cout << szString << endl;' ouputs Hello.

Is there something wrong with my compiler? Or is my logical talent
really that bad?


Your compiler is just a little bit better at counting than you:

szString[0] = 'H'
szString[1] = 'e'
szString[2] = 'l'
szString[3] = 'l'
szString[4] = 'o'
szString[5] = \0

Your compiler thinks that this is 6 lines, now you asked the compiler to
provide an array of 5 characters. The compiler thinks 6 > 5 and complains.

Generally, T[n] is an array of n objects numbered from 0 to (n-1).
Best

Kai-Uwe Bux
Aug 21 '05 #2
"Tarjei Romtveit" <ta************ *@gmail.com> writes:
If i declare a char string like this: char szString[5] = "Hello"; The content of the szString array is now somthing similar to this:
szString[0] == H, szString[1] == e.. and so on, until szString[5] ==
\0. (right?) Trouble is, you need 6 characters to store Hello\0, but you've only
asked for 5 characters.
char szString[6] = "Hello";
This is ok.

If I choose to write something on the screen
like: cout << szString[6] << endl;


This prints the 7th character of the szString array, an array that
only has 6 characters.

Aug 21 '05 #3
LR
Tarjei Romtveit wrote:

If i declare a char string like this:

char szString[5] = "Hello";

The content of the szString array is now somthing similar to this:
szString[0] == H, szString[1] == e.. and so on, until szString[5] ==
\0. (right?)
Close, but no.

char s[5];

will make an array of char with five (5) elements. The first index is
zero (0) and the last index is four (4). 0, 1, 2, 3, and 4 are five
seperate digits.

"Hello" including the final trailing '/0' is six chars. So you're off by
one.

But my compiler returns a following error:

"initialize r-string for array of chars is too long"

If i do the declartaion like this

char szString[6] = "Hello";

it compiles correctly.
Sure.

char s[6] = "Hello";

Six elements in the array named s. Valid indicies inclusive range from
zero to five.

Maybe better to write:

const char szString[] = "Hello";

Because I do so hate to count the number of characters in a string. I
often get it wrong and it just leads to headaches later should I want
the string to contain something else like "Goodbye".

or even better, perhaps,

#include <string>
..
..
..
const std::string sHello = "Hello";
If I choose to write something on the screen
like:

cout << szString[6] << endl;

It outputs a strange symbol that often differs (Probably something in
the memory).
Because char x[6] has six valid indicies inclusive 0 to 5. 6 is one past
the last valid index. Who knows what's there?

Try this little bit of code:
----------
#include <iostream>
int main() {
std::cout << sizeof("Hello") << std::endl;
}
----------


The 'cout << szString << endl;' ouputs Hello.

Is there something wrong with my compiler?
It's hard to tell from just this simple case. Continue with your
testing and you're bound to eventually find a bug. ;)

Or is my logical talent
really that bad?

(I'm a beginner so bear with me)


For some people the idea that arrays in C++ have zero as their first
index can be a bit of a stumbling block. Get up, dust yourself off and
carry on.

BTW, if you don't mind, could you tell us what book you're using? Or are
you taking a course?

LR
Aug 21 '05 #4
Oki, Thanks alot. As I thought, a simple solution.

In this case I think there has been a misunderstandin g between me and
the teacher of the course I'm taking. (It isnt always easy when your
native language isnt english, and the teacher is from Wales or
something)*blus h*

Aug 21 '05 #5

"Tarjei Romtveit" <ta************ *@gmail.com> wrote in message
news:11******** **************@ g49g2000cwa.goo glegroups.com.. .
I'm still a newbie into C++ programming, so I got a quite foolish
string related question.

Using: Dev-cpp 4.9.9.2 (I think Dev-Cpp uses a gcc compiler of some
sort)
If i declare a char string like this:

char szString[5] = "Hello";

The content of the szString array is now somthing similar to this:
szString[0] == H, szString[1] == e.. and so on, until szString[5] ==
\0. (right?)

But my compiler returns a following error:

"initialize r-string for array of chars is too long"

If i do the declartaion like this

char szString[6] = "Hello";

it compiles correctly. If I choose to write something on the screen
like:

cout << szString[6] << endl;

It outputs a strange symbol that often differs (Probably something in
the memory).

The 'cout << szString << endl;' ouputs Hello.

Is there something wrong with my compiler? Or is my logical talent
really that bad?

(I'm a beginner so bear with me)
Mvh

Tarjei


1. Arrays in C/C++ start at 0, not 1. The 6th element of the array is [5],
not [6].
2. You need to allocate one byte for the null terminator.

"Hello" actually takes up 6 bytes. 'H' 'e' 'l' 'l' 'o' '\0'. In an array
they wold be shown as [0] to [5]
Aug 21 '05 #6

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

Similar topics

5
3082
by: Richard B. Kreckel | last post by:
Hi! I was recently asked what book to recommend for a beginner in C++. I am convinced that you needn't study C in depth before learning C++ (though it helps), but cannot find any beginner's book which isn't aimed at people coming from C/Pascal/Java/Delpi/whatever... However, there seem to be plenty such books for all those other languages. Is there really no literature for people trying to learn programming by starting with C++? ...
7
3486
by: Sonoman | last post by:
I am trying to do this: cin >> temp; if (temp == "n"){ Then do something... } temp was declared as a string and the input I give at the prompt is n, but it skips the condition for the if statement when I think it should go into the if statement. I tried swithching to 'n' for the condition but it gave me
2
5540
by: Riaan C | last post by:
Hi I'm new to C. Here's the problem. I understand the whole concept of pointers and can easily use it with normal non-array variables. I want to declare a array of strings, thus multidimensional character array, in my int main(); Then I want to pass this to a function that will scanf all the values. I also want another function to display all the names but I just can
1
2627
by: Mike Malter | last post by:
I am just starting to work with reflection and I want to create a log that saves relevant information if a method call fails so I can call that method again later using reflection. I am experimenting a bit with what I need to do this and have the following code snippet. But first if I pass the assembly name and type to Activator.CreateInstance() it always fails. However if I walk my assembly and get a type value, the call to...
1
1431
by: Bill Maher | last post by:
I have an array that I use to write to the file on the C:\ drive. I want to print the file. How can I do it. Here is my code for the write to the file: I'm using "writeline". To allow for possibly deleted items, i first check for emptry strings, and then I do datMemory.writeline(eachItem). Here is my code for saving:
33
2426
by: aaron | last post by:
I have a question in my class.. hoping to get some help I need to create a program that will print firstName middleName lastName then their initials User will input: John Smith Doe Output: John
13
1714
by: sathyashrayan | last post by:
Dear group, pls go through the following function definition: function at_show_aux(parent, child) { var p = document.getElementById(parent); var c = document.getElementById(child); var top = (c == "y") ? p.offsetHeight+2 : 0; var left = (c == "x") ? p.offsetWidth +2 : 0;
90
3469
by: John Salerno | last post by:
I'm a little confused. Why doesn't s evaluate to True in the first part, but it does in the second? Is the first statement something different? False print 'hi' hi Thanks.
31
1918
by: mdh | last post by:
I am still having a problem understanding K&RII on p 112. I have looked at the FAQs --which I am sure answer it in a way that I have missed, so here goes. A 2-dim array, (per K&R) is really a 1-dim array, each of whose elements is an array. Looking at the debugger I use, arr is shown as an initial value of "2", but when expanded, there are 2 consecutive arrays of 13 elements. So, may I ask this? Is there anything special that marks the...
0
9531
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
10237
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...
1
10187
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
6795
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
5446
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...
0
5578
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4120
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
3735
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2928
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.