473,672 Members | 2,597 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

help passing pointer to char array as argument

Hello

I need to populate an array of char arrays at run-time. A very
simplifed version of the code is below.

char ** list should contain cnt char arrays. The values of char ** list
are set by the function foo(). A pointer to char ** list is passed to
foo() as an argument.

The problem is that when foo() returns, char ** list contains rubbish
and does not always contain cnt char arrays. Can anyone tell me what
I'm doing wrong? Note that I don't want to use the vector or string for
efficiency. Note that the code that get the time has nothing to do with
the real programme. It's just a simplification for the purpose of this
posting.
(I have noticed that if the values are constant char arrays there is no
problem)

//*************** *************** *************** *************** *************** ******
#include <iostream.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>

void foo(char *** array, int cnt){

char buf[256];

for(int i=0; i<cnt; i++){
long t = time(NULL); // just for demonstration
itoa(t, buf, 10);
(*array)[i] = buf;
cout << i << " " << (*array)[i] << '\n';
}
}

int main(int argc, char ** argv){

int cnt = 10;
char ** list = new char*[10];

foo(&list, cnt);

for(int i=0; i<cnt; i++){
cout << i << " " << list[i] << "\n";
}

delete [] list;

return 0;
}
//*************** *************** *************** *************** *************** ******

Thanks!!!!!

Jul 5 '06 #1
9 7625
ro************* @telefonica.net writes:
>void foo(char *** array, int cnt){
> char buf[256];
This fixes the value of buf for the duration of the function, so
> (*array)[i] = buf;
will set all the elements to the same value - the value of buf.

Also, buf is a local variable, so when foo ends, the space used by buf can be recycled.

The short answer to your question is to reconsider using containers.

Jul 5 '06 #2

ro************* @telefonica.net wrote:
Hello
void foo(char *** array, int cnt){

char buf[256];

for(int i=0; i<cnt; i++){
long t = time(NULL); // just for demonstration
itoa(t, buf, 10);
(*array)[i] = buf;
cout << i << " " << (*array)[i] << '\n';
}
}
For starters, you're assigning the same local buffer 'buf' multiple
times, then that's going out of scope at the end of the function.
No offence mate, but you're clearly struggling juggling three levels of
indirection; you're going to be a lot better off using std::vector and
std::string. They are designed precisely to allow programmers to avoid
these sorts of gymnastics and pitfalls. Your concerns about
"performanc e" are misplaced, get the thing working in a clear and
understandable way and then worry about tweaking it for performance
*if* you need to. Which you won't.

Jul 5 '06 #3
ro************* @telefonica.net wrote:
Hello

I need to populate an array of char arrays at run-time. A very
simplifed version of the code is below.

char ** list should contain cnt char arrays. The values of char ** list
are set by the function foo(). A pointer to char ** list is passed to
foo() as an argument.

The problem is that when foo() returns, char ** list contains rubbish
and does not always contain cnt char arrays. Can anyone tell me what
I'm doing wrong? Note that I don't want to use the vector or string for
efficiency. Note that the code that get the time has nothing to do with
the real programme. It's just a simplification for the purpose of this
posting.
Why not just use std::vector<std ::stringand save yourself a lot of
trouble?

--
Ian Collins.
Jul 5 '06 #4

Tim Love wrote:
ro************* @telefonica.net writes:
void foo(char *** array, int cnt){
char buf[256];
This fixes the value of buf for the duration of the function, so
(*array)[i] = buf;
will set all the elements to the same value - the value of buf.

Also, buf is a local variable, so when foo ends, the space used by buf can be recycled.

The short answer to your question is to reconsider using containers.
Thanks, Tim.
I might be wrong but I'm using a pointer to char ** list and assigning
the value of buf. char ** list's values should persist after foo()
returns. Isn't that right? Thanks!!!

Rob

Jul 5 '06 #5
ro************* @telefonica.net writes:
>Thanks, Tim.
I might be wrong but I'm using a pointer to char ** list and assigning
the value of buf. char ** list's values should persist after foo()
returns. Isn't that right?
But what persists is just a pointer. It's pointing to memory that's being
rewritten then freed, so it's not a useful pointer.

http://burks.bton.ac.uk/burks/langua...t/pointers.htm may help,
but vectors+strings are a safer bet.
Jul 5 '06 #6
TB
ro************* @telefonica.net skrev:
Tim Love wrote:
>ro************* @telefonica.net writes:
>>void foo(char *** array, int cnt){
char buf[256];
This fixes the value of buf for the duration of the function, so
>> (*array)[i] = buf;
will set all the elements to the same value - the value of buf.

Also, buf is a local variable, so when foo ends, the space used by buf can be recycled.

The short answer to your question is to reconsider using containers.

Thanks, Tim.
I might be wrong but I'm using a pointer to char ** list and assigning
the value of buf. char ** list's values should persist after foo()
returns. Isn't that right? Thanks!!!
You're assigning the address of 'buf' to each pointer, and 'buf' only
exists within the scope of 'foo()', not outside in 'main()'. The address
points to some location on the stack, which is recycled and overwritten
by subsequent stack operations, like the following call to
std::basic_ostr eam::operator<< (...).

You need to allocate the buffer with 'new' if you want it to persist,
or dismiss any thoughts of efficiency and do as others have replied,
skip deep indirection and use the provided framework of containers.

For example:

#include <sstream>
#include <vector>
#include <string>
#include <ctime>
#include <ostream>
#include <algorithms>

void foo(std::vector <std::string& v, unsigned cnt) {
std::ostringstr eam strm;
for(unsigned i = 0; i < cnt; ++i) {
strm << std::time(0);
v.push_back(str m.str());
strm.str("");
}
}

int main(int argc, char* argv[])
{
std::vector<std ::stringv;
foo(v,10);
std::copy(v.beg in(),
v.end(),
std::ostream_it erator<std::str ing>(std::cout, "\n"));
return 0;
}

--
TB @ SWEDEN
Jul 5 '06 #7

TB wrote:
>
You're assigning the address of 'buf' to each pointer, and 'buf' only
exists within the scope of 'foo()', not outside in 'main()'. The address
points to some location on the stack, which is recycled and overwritten
by subsequent stack operations, like the following call to
std::basic_ostr eam::operator<< (...).

You need to allocate the buffer with 'new' if you want it to persist,
or dismiss any thoughts of efficiency and do as others have replied,
skip deep indirection and use the provided framework of containers.

TB @ SWEDEN
Thanks to you and others who have got back to me. I'll take this
advice; but I'm still curious as to the following:

Essentially: is it possible to manipulate the values an array of chars
from within the scope of a function so that they persist?

foo(char *** list){
// manipulate list elements
}

I assume if I allocate memory with "new", for example...

(*array)[i] = new char[256];

....how can I then free the memory? I assume "delete [] list" won't do
it.

Thanks!!!
Rob

Jul 5 '06 #8
TB
ro************* @telefonica.net skrev:
TB wrote:
>You're assigning the address of 'buf' to each pointer, and 'buf' only
exists within the scope of 'foo()', not outside in 'main()'. The address
points to some location on the stack, which is recycled and overwritten
by subsequent stack operations, like the following call to
std::basic_ost ream::operator< <(...).

You need to allocate the buffer with 'new' if you want it to persist,
or dismiss any thoughts of efficiency and do as others have replied,
skip deep indirection and use the provided framework of containers.

TB @ SWEDEN

Thanks to you and others who have got back to me. I'll take this
advice; but I'm still curious as to the following:

Essentially: is it possible to manipulate the values an array of chars
from within the scope of a function so that they persist?

foo(char *** list){
// manipulate list elements
}

I assume if I allocate memory with "new", for example...

(*array)[i] = new char[256];

...how can I then free the memory? I assume "delete [] list" won't do
it.
#include <iostream>
#include <ctime>
#include <cstdlib>

void foo(char **& array, unsigned cnt){
for(unsigned i = 0; i < cnt; ++i){
char * buf = new char[256];
long t = std::time(0);
std::itoa(t, buf, 10);
array[i] = buf;
std::cout << i << " " << array[i] << std::endl;
}
}

int main(int argc, char ** argv){
unsigned cnt = 10;
char ** list = new char*[10];

foo(list, cnt);

for(unsigned i = 0; i < cnt; ++i) {
std::cout << i << " " << list[i] << std::endl;
}

for(unsigned i = 0; i < cnt; ++i) {
delete[] list[i];
}
delete[] list;

return 0;
}

--
TB @ SWEDEN
Jul 5 '06 #9
#include <iostream>
#include <ctime>
#include <cstdlib>

void foo(char **& array, unsigned cnt){
for(unsigned i = 0; i < cnt; ++i){
char * buf = new char[256];
long t = std::time(0);
std::itoa(t, buf, 10);
array[i] = buf;
std::cout << i << " " << array[i] << std::endl;
}
}

int main(int argc, char ** argv){
unsigned cnt = 10;
char ** list = new char*[10];

foo(list, cnt);

for(unsigned i = 0; i < cnt; ++i) {
std::cout << i << " " << list[i] << std::endl;
}

for(unsigned i = 0; i < cnt; ++i) {
delete[] list[i];
}
delete[] list;

return 0;
}

--
TB @ SWEDEN
Thanks very much TB!!!

Rob

Jul 5 '06 #10

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

Similar topics

8
3959
by: Alex Vinokur | last post by:
Various forms of argument passing ================================= C/C++ Performance Tests ======================= Using C/C++ Program Perfometer http://sourceforge.net/projects/cpp-perfometer http://alexvn.freeservers.com/s1/perfometer.html
58
10125
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 code... TCHAR myArray; DoStuff(myArray);
17
2257
by: BlindHorse | last post by:
Help!!! I need someone to tell me why I am getting the err msg error C2440: '=' : cannot convert from 'char *' to 'char' //==================== #include <iostream>
5
3017
by: Oeleboele | last post by:
OK, I can't understand this exactly: I have this function: int howdy(void *) I first past this to the function &aCharArray I realized later that this should be aCharArray but... the former version also worked ? I can't understand why that worked. The only thing I can come up with is that the compiler gave me a break (although I did not receive any
7
3016
by: Jeff K | last post by:
Can you pass an int array by reference to a function and modify selective elements? Here is my code: #include <stdio.h> #define COLUMNSIZE 30 #define ASIZE 5 int calcfldpos(int *row, int *column, int *numArray)
8
10707
by: intrepid_dw | last post by:
Hello, all. I've created a C# dll that contains, among other things, two functions dealing with byte arrays. The first is a function that returns a byte array, and the other is intended to receive a byte array as one of its parameters. The project is marked for COM interop, and that all proceeds normally. When I reference the type library in the VB6 project, and write the code to call the function that returns the byte array, it works
33
2853
by: Martin Jørgensen | last post by:
Hi, In continuation of the thread I made "perhaps a stack problem? Long calculations - strange error?", I think I now got a "stable" error, meaning that the error always seem to come here now (tried: visual studio 2005 + linux/macintosh gcc)... That's a pretty good thing. I think the error still appears using both gcc and visual studio 2005. Everything is standard C (ANSI C ?? I don't know the difference) - but since so many functions...
4
2500
by: Christian Maier | last post by:
Hi After surfing a while I have still trouble with this array thing. I have the following function and recive a Segmentation fault, how must I code this right?? Thanks Christian Maier
8
1655
by: cpptutor2000 | last post by:
Could some C guru please help me? I have a function that takes as an argument a pointer to an array of unsigned chars (basically a hex representation of a dotted decimal IP address). When I print out the received values in the receiving function, I get something completely different from what I passed in. The following are the relevant code snippets: In the calling function: unsigned char* TempAddrs = {"0xC0", "0xA8", "0x00", "0x63"};
0
8486
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
8931
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
8828
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
8608
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
8680
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...
1
6238
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
5705
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
2819
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
2063
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.