473,756 Members | 2,703 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Iterating through an array whose size is unknown?

I need to send just an array to a function which then needs to go
through each element in the array. I tried using sizeof(array) /
sizeof(array[0]) but since the array is passed into the function,
sizeof(array) is really sizeof(pointer to first element in array) and
therefore doesn't solve my problem. If I can't calculate the size of
the array, can I go through the elements without knowing the size and
somehow test whether I'm off the end of the array?
Jul 22 '05 #1
9 10705
On 14 Jul 2004 21:30:03 -0700, ma***********@y ahoo.com (matthurne)
wrote in comp.lang.c++:
I need to send just an array to a function which then needs to go
through each element in the array. I tried using sizeof(array) /
sizeof(array[0]) but since the array is passed into the function,
sizeof(array) is really sizeof(pointer to first element in array) and
therefore doesn't solve my problem. If I can't calculate the size of
the array, can I go through the elements without knowing the size and
somehow test whether I'm off the end of the array?


But you do know the size of the array, after all you created the
array.

There are two possibilities if you insist using an array instead of a
std::vector:

1. Pass the size of the array as an additional parameter to the
function.

2. If the data in the array permits, have a dummy sentinel value that
tells the called function that it has reached the end of the array.
That is how the C library string functions work, a '\0' marks the end
of the string.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Jul 22 '05 #2
On 14 Jul 2004 21:30:03 -0700, matthurne <ma***********@ yahoo.com> wrote:
I need to send just an array to a function which then needs to go
through each element in the array. I tried using sizeof(array) /
sizeof(array[0]) but since the array is passed into the function,
sizeof(array) is really sizeof(pointer to first element in array) and
therefore doesn't solve my problem. If I can't calculate the size of
the array, can I go through the elements without knowing the size and
somehow test whether I'm off the end of the array?


No you cannot, you have two options

1) The poor mans option, pass the size of the array into the original
function, so you can pass it on to the later function.

2) The proper C++ option, use a vector instead of an array. Vectors carry
their size with them at all times. In others words vectors do what you are
hoping that arrays do. They also have lots of other useful features like
being able to grow dynamically. You haven't really learnt C++ programming
if you haven't learned about vectors. Read a decent C++ book.

john
Jul 22 '05 #3
"Jack Klein" <ja*******@spam cop.net> wrote in message
1. Pass the size of the array as an additional parameter to the
function.

2. If the data in the array permits, have a dummy sentinel value that
tells the called function that it has reached the end of the array.
That is how the C library string functions work, a '\0' marks the end
of the string.


Also argv[argc] is valid and points to NULL.

int main(int argc, char * * argv) {
char * * iter = argv;
while (*iter) ++iter;
assert(iter-argv == argc); // should be true
argv[argc]; // ok, returns NULL
argv[argc+1]; // memory access violation!
}

Same holds for the extension char * * env extension many compilers support.

int main(int argc, char * * argv, char * * env);

A combination of methods (1) and (2) is to have the first element in the
array denote the number of elements following. Thus one would have { 3, 7,
2, 4 } for an array of 3 elements. This first element in the array is like
a sentinel saying the number of elements in the array. But of course, this
approach may not always be feasible, but it is something to consider.
Jul 22 '05 #4
All of your suggestions were helpful, however they aren't a solution
to my problem. It seems there ISN'T a solution to my problem! See, I
was attempting to code a solution to an archived TopCoder problem
question. To answer the question I had to have a method with the
prototype:

int sum(string s[])

So I couldn't pass in the size as another parameter. In addition, the
problem gave examples of what would be passed in and it was simply
arrays of strings, without any kind of sentinel value/string to tell
the size of the array. Therefore, that idea is a no-no. I know if I
were using this in my own program I would take one of your
suggestions, but I'm assuming if I were actually answering this
problem during a TopCoder competition, I would have to use the above
prototype or I would get the problem wrong.

So here's my thought...maybe the problem was directed/meant to be
answered in Java. That's the first language I really learned anything
in and I know that Strings in Java have a size() function, so there
goes the problem.

By the way, I have used vectors, my friend. I would prefer them over
an array but like I've already said, I was given the above prototype
for the problem. I'm actually almost finished with Accelerated
C++...the chapter I just finished describes writing your OWN
vector-like class. Please don't assume that just because I asked a
specific question about arrays that means I don't know anything else
about C++.
Jul 22 '05 #5
> Please don't assume that just because I asked a
specific question about arrays that means I don't know anything else
about C++.


OK, point taken. I find it very easy to slip into a slightly sarcastic tone
when replying on c.l.c++, it's something I shouldn't do. In my defence I'd
say that most of the time there is helpful advice behind the sarcasm.

john
Jul 22 '05 #6
"John Harrison" <jo************ *@hotmail.com> wrote in message news:<2l******* *****@uni-berlin.de>...
Please don't assume that just because I asked a
specific question about arrays that means I don't know anything else
about C++.


OK, point taken. I find it very easy to slip into a slightly sarcastic tone
when replying on c.l.c++, it's something I shouldn't do. In my defence I'd
say that most of the time there is helpful advice behind the sarcasm.

john


That's ok, I don't actually know TOO much about C++. Just more than
you assumed. ;-) No sweat though.

Oh, and I realized after my last post that I meant to say...perhaps
the problem was written for Java because ARRAYS in Java have the
length constant. What I actually wrote was that Strings in Java have
the size() method, which I believe they actually have the length()
method, but either way it wasn't the strings I was worried about
anyway (that and strings in C++ have a size() method too, so no
difference there). Doh. So yeah, this is just me correcting myself.
Jul 22 '05 #7
Can't you use a global variable to record the size, or at least a global
file variable?

Anil Mamede

matthurne wrote:
I need to send just an array to a function which then needs to go
through each element in the array. I tried using sizeof(array) /
sizeof(array[0]) but since the array is passed into the function,
sizeof(array) is really sizeof(pointer to first element in array) and
therefore doesn't solve my problem. If I can't calculate the size of
the array, can I go through the elements without knowing the size and
somehow test whether I'm off the end of the array?

Jul 22 '05 #8
Anil Mamede wrote:

Can't you use a global variable to record the size, or at least a global
file variable?
1: Please dont't top post.
2: The proposed solution is one, that one wants to avoid at all costs.

Anil Mamede

matthurne wrote:
I need to send just an array to a function which then needs to go
through each element in the array. I tried using sizeof(array) /
sizeof(array[0]) but since the array is passed into the function,
sizeof(array) is really sizeof(pointer to first element in array) and
therefore doesn't solve my problem. If I can't calculate the size of
the array, can I go through the elements without knowing the size and
somehow test whether I'm off the end of the array?

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #9
"Anil Mamede" <am**@mega.ist. utl.pt> wrote in message news:40f7ba0b$0 $1773
Can't you use a global variable to record the size, or at least a global
file variable?


What if there are 2 arrays?

Then probably a map<address of array, size of array> would work, though if
two threads insert or remove from the array at once, or one inserts or
removes and the other just reads, then we have to guard these insertions,
removals, and reads with mutex locks -- so that only one thread can do
anything with the global map at one time. Some implementations do in fact
do it this way, because when you say delete[] array they need to know the
number of elements in the array in order to call destructor on each one,
then release the memory of the array.

Other implementations might prepend the number of elements in the array in
the -1 slot. So for an array of length 3 arr[0] = 7, arr[1] = 1, arr[2] =
9, the compiler would insert an arr[-1]=3.

The global map approach seems to have the advantage that realloc is easier
as you can see how much the current array can grow before it collides with
the next one.
Jul 22 '05 #10

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

Similar topics

9
3969
by: pvinodhkumar | last post by:
The number of elemets of the array, the array bound must be constant expression?Why is this restriction? Vinodh
2
2099
by: Salman Khilji | last post by:
After reading all the FAQs, I cannot solve the following problem: I have a pointer of type double. I am supposed to 1) Allocate memory for it assuming that the pointer will be pointing to a multi-dimensional array whose dimensions will be specified at run-time. 2) Set the individual elements of the array using pointer-arithmetic.
9
1512
by: Rob Thorpe | last post by:
I have a set of data structures that are collected together in array. This array is in turn packaged in a struct itself. The structs look like this:- struct index_entry_t { char *id; char *description; }; typedef struct index_entry_t index_entry_t;
11
4468
by: truckaxle | last post by:
I am trying to pass a slice from a larger 2-dimensional array to a function that will work on a smaller region of the array space. The code below is a distillation of what I am trying to accomplish. // - - - - - - - - begin code - - - - - - - typedef int sm_t; typedef int bg_t; sm_t sm; bg_t bg;
14
2211
by: blue | last post by:
Hi, all: Recently I found this comment on comp.lang.c "Answers to FAQ" (6.13): If you really need to declare a pointer to an entire array, use something like "int (*ap);" where N is the size of the array. (See also question 1.21.) If the size of the array is unknown, N can in principle be omitted, but the resulting type, "pointer to array of unknown size," is useless. However, when I try to write a sample program like:
19
3154
by: Tom Jastrzebski | last post by:
Hello, I was just testing VB.Net on Framework.Net 2.0 performance when I run into the this problem. This trivial code attached below executed hundreds, if not thousand times faster in VB 6.0 than in .Net environment, under VS 2005 Beta 2. Does anyone have any idea whether this will be addressed in the final release? Thanks, Tomasz
104
16999
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from that array Could you show me a little example how to do this? Thanks.
4
2822
RMWChaos
by: RMWChaos | last post by:
The next episode in the continuing saga of trying to develop a modular, automated DOM create and remove script asks the question, "Where should I put this code?" Alright, here's the story: with a great deal of help from gits, I've developed a DOM creation and deletion script, which can be used in multiple applications. You simply feed the script a JSON list of any size, and the script will create multiple DOM elements with as many attributes...
33
7177
by: Adam Chapman | last post by:
Hi, Im trying to migrate from programming in Matlab over to C. Im trying to make a simple function to multiply one matrix by the other. I've realised that C can't determine the size of a 2d array, so im inputting the dimensions of those myself. The problem is that the output array (C=A*B) has as many rows as A and as many columns as B. I would think of initialising C with:
0
9431
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9255
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
10014
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
9844
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
9819
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
8688
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
6514
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();...
1
3780
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
3
2647
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.