473,387 Members | 1,481 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

array size


Hello

why am I getting 6 outputs instead of just 5 from this code?

thanks

#include <iostream>
#include <string>

using namespace std;

int main(){
string a[]=
{
"blue", "green", "red", "black", "white"
};
for(int i=0; i< (sizeof(a)-1); ++i)
cout << "item [" << i << "]= " << a[i] << endl;
}

item [0]= blue
item [1]= green
item [2]= red
item [3]= black
item [4]= white
item [5]=

Program received signal SIGSEGV, Segmentation fault.
0x40095847 in std::operator<< <char, std::char_traits<char>, std::allocator<char> > () from /usr/lib/libstdc++.so.5
(gdb)
Aug 2 '05 #1
11 54839

Baloff wrote:

int main(){
string a[]=
{
"blue", "green", "red", "black", "white"
};
for(int i=0; i< (sizeof(a)-1); ++i)

Sizeof(a) returns the *size* of the array, not the number of elements
in the array. For example, if the size of std::string is 4 bytes, then
sizeof(a) above would be 4*5 = 20.

So you are looping from 0 to 19, but once you hit i = 5, you are
already past the array (this is why it segfaults).

What you want is the number of elements, not the size of the array.
You can get this by dividing the sizeof the array by the sizeof each
element.

Change your loop condition to:

for(int i=0; i< sizeof a/sizeof *a; ++i)
Hope this helps,
-shez-

Aug 2 '05 #2
> Hello

why am I getting 6 outputs instead of just 5 from this code?

thanks

#include <iostream>
#include <string>

using namespace std;

int main(){
string a[]=
{
"blue", "green", "red", "black", "white"
};
for(int i=0; i< (sizeof(a)-1); ++i)
cout << "item [" << i << "]= " << a[i] << endl;

}

item [0]= blue
item [1]= green
item [2]= red
item [3]= black
item [4]= white
item [5]=

Program received signal SIGSEGV, Segmentation fault.
0x40095847 in std::operator<< <char, std::char_traits<char>, std::allocator<char> > > () from /usr/lib/libstdc++.so.5


Ever tried printing the value of sizeof(a)?? Its 20. No wonder you're
getting a segfault. Learn what sizeof means and learn to use STL
iterators.

Srini

Aug 2 '05 #3
> why am I getting 6 outputs instead of just 5 from this code?

thanks

#include <iostream>
#include <string>

using namespace std;

int main(){
string a[]=
{
"blue", "green", "red", "black", "white"
};
for(int i=0; i< (sizeof(a)-1); ++i)
cout << "item [" << i << "]= " << a[i] << endl;
}

item [0]= blue
item [1]= green
item [2]= red
item [3]= black
item [4]= white
item [5]=

Program received signal SIGSEGV, Segmentation fault.
0x40095847 in std::operator<< <char, std::char_traits<char>, std::allocator<char> > () from /usr/lib/libstdc++.so.5


You get only 6 outputs since the program crashes (if it wouldn't do
that you'd get least 5 * sizeof(std::string) values of garbage.
The problem is that when you do sizeof(a) you get back the total size
of the array in bytes. a simple addition of
std::cout << sizeof(a)<< std::endl;
before the loop should confirm this.

The for loop is best rewritten to
for(int i=0; i< (sizeof(a)/sizeof(*a) -1); ++i)

Aug 2 '05 #4
ve*********@hotmail.com wrote:
The for loop is best rewritten to
for(int i=0; i< (sizeof(a)/sizeof(*a) -1); ++i)

You need to drop the "-1" (otherwise you will not include the last
element).

-shez-

Aug 2 '05 #5
Baloff wrote:
Hello

why am I getting 6 outputs instead of just 5 from this code? .... for(int i=0; i< (sizeof(a)-1); ++i)

....

sizeof(a)/sizeof(*a) is what you need instead of sizeof(a)-1.

This is commonly written into a macro like ...

#define Nelem( A ) (sizeof(A)/sizeof(*A))

.... which gives you the number of elements in the array, however it may
be interpretted incorrectly so it's much better to use a template that
will never be interpreted incorrectly.

const char * x = "The size of this string is unimportant";

Nelem( x ) will more than likely not be what you think it is and there
will be no error emitted by the compiler.
A better practice to get into it to is this:

template <typename T, unsigned N>
char ( & NelemArrayFunc( T ( & )[ N ] ) )[ N ];

#define Nelem( A ) (sizeof( NelemArrayFunc( A ) ))

In this case Nelem( x ) will be a compile-time error.

Aug 2 '05 #6
I don't even understand this mix with macroses and strange templates.
isn't better to simplify everything:

template<class T, size_t N>inline unsigned int size_of(const T (&)[N]){
return N;
}

and then for the OP's code:
...
for(int i=0; i< size_of(a); ++i)
cout << "item [" << i << "]= " << a[i] << endl;
...

or a pointer version:
template<class T, size_t N>inline const T* last_of(const T (&x)[N]){
return &x[N+1];
}

std::string *i = &a[0];
while(i!=last_of(a)){
cout << *i++ << endl;
}

Aug 2 '05 #7
__PPS__ wrote:
I don't even understand this mix with macroses and strange templates.
isn't better to simplify everything:

template<class T, size_t N>inline unsigned int size_of(const T (&)[N]){
return N;
}

and then for the OP's code:
...
for(int i=0; i< size_of(a); ++i)
cout << "item [" << i << "]= " << a[i] << endl;
...

or a pointer version:
template<class T, size_t N>inline const T* last_of(const T (&x)[N]){
return &x[N+1];
Should probably be

return &x[N];

or

return x + N;
}

std::string *i = &a[0];
while(i!=last_of(a)){
cout << *i++ << endl;
}


V
Aug 2 '05 #8
probably I chose a wrong name :)
should have been something like template<...> ... end(...)

Aug 2 '05 #9
__PPS__ wrote:
probably I chose a wrong name :)
should have been something like template<...> ... end(...)


It doesn't matter what the name is. The last element's index is
N-1. When you want "one-past-the-end" you should use N. N+1 is
simply _wrong_. Just think about it a bit.

V
Aug 2 '05 #10
yes, you are right!
my error

Aug 2 '05 #11
__PPS__ wrote:
I don't even understand this mix with macroses and strange templates.
isn't better to simplify everything:

template<class T, size_t N>inline unsigned int size_of(const T (&)[N]){
return N;
}


int x[5];

int y[ size_of( x ) ];

?
Aug 3 '05 #12

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

Similar topics

13
by: Noah Spitzer-Williams | last post by:
Hello guys, I would like to do something seemingly simple: find out if an element in an array that is passed to my function exists. I used to think I could just do: if (arr) ... However, if...
58
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of...
3
by: ritchie | last post by:
Hi all! Still working on this program! Just to recap, I am writing a program to sort an array with four different sort algorythms. I am having a little trouble at the moment though! Now, I...
8
by: Gerald | last post by:
I have a problem with an array of pointers. In a program I'm writing, I have to read a file, containing thousands of short lines. The content of another file will be compared against each line...
6
by: Herrcho | last post by:
in K&R Chapter 6.3 it mentions two methods to calculate NKEYS. and points out the first one which is to terminate the list of initializers with a null pointer, then loop along keytab until the...
22
by: Wynand Winterbach | last post by:
I think every C programmer can relate to the frustrations that malloc allocated arrays bring. In particular, I've always found the fact that the size of an array must be stored separately to be a...
7
by: simkn | last post by:
Hello, I'm writing a function that updates an array. That is, given an array, change each element. The trick is this: I can't change any elements until I've processed the entire array. For...
12
by: manochavishal | last post by:
Hi, I have a question. How can i know the size of array when it is passed to a function. For Example i have this code: #include <stdio.h> #include <stdlib.h>
20
by: Cyn | last post by:
Hi, I want to create a general array structure which can hold all types. Something like this: struct ARRAY { void **array; size_t size; };
28
Nepomuk
by: Nepomuk | last post by:
Hi! I've read, that in C++ there's no predefined method, to calculate the size of an array. However, it's supposed to work withsizeof(array)/sizeof(array)Now, this does work in some situations, but...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...

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.