Hey everybody,
I'm working on a program in c++, and I've come up against a problem
that I can't figure out. I don't imagine that it's too difficult to
solve, but it has been giving me trouble.
What I would like to do is create an array of strings. More
specifically, I would like to create an array of char* 's. And the
only catch is that I will need to pass the array by reference to
several methods. Although from my understanding of pointers, I
imagine that this is how things are done inherently in c++.
I would really appreciate if somebody could give me a snippet of code
where an array of char* is declared and assignments are made. I've
looked all over, but haven't had any success in finding anything.
Thanks,
Ben 7 10805
In article <da**************************@posting.google.com >,
Ben <bw****@gmail.com> wrote: What I would like to do is create an array of strings. More specifically, I would like to create an array of char* 's.
Are you really sure you want to do that? This would be a lot easier to do
with a vector of real honest-to-gosh C++ style strings. Then you don't
have to mess with pointers, which are easy to make mistakes with (as I'm
sure you're aware ;-).
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// pass the vector of strings by reference (note the &)
// so no copying is needed
void Display (const vector<string>& v)
{
// Vectors "know" how big they are, so you don't have to
// pass the size separately.
for (int k = 0; k < v.size(); ++k)
{
cout << "String #" << k << ": " << v[k] << endl;
}
}
int main ()
{
// Create this vector with a specific size
vector<string> myStrings(7);
// Each string automatically expands to accommodate its characters
myStrings[0] = "Hi";
myStrings[1] = "I";
myStrings[2] = "am";
myStrings[3] = "a";
myStrings[4] = "vector";
myStrings[5] = "of";
myStrings[6] = "strings";
Display (myStrings);
// Create this vector with size zero, and let it grow to
// accommodate the data
vector<string> moreStrings;
moreStrings.push_back("I");
moreStrings.push_back("am");
moreStrings.push_back("another");
moreStrings.push_back("vector");
Display (moreStrings);
return 0;
}
And the only catch is that I will need to pass the array by reference to several methods. Although from my understanding of pointers, I imagine that this is how things are done inherently in c++.
You can use pointers to pass data to functions in C++, but I personally
prefer to use references, as in the example above.
--
Jon Bell <jt*******@presby.edu> Presbyterian College
Dept. of Physics and Computer Science Clinton, South Carolina USA
"Ben" <bw****@gmail.com> wrote in message
news:da**************************@posting.google.c om... Hey everybody,
I'm working on a program in c++, and I've come up against a problem that I can't figure out. I don't imagine that it's too difficult to solve, but it has been giving me trouble.
What I would like to do is create an array of strings. More specifically, I would like to create an array of char* 's. And the only catch is that I will need to pass the array by reference to several methods. Although from my understanding of pointers, I imagine that this is how things are done inherently in c++.
I would really appreciate if somebody could give me a snippet of code where an array of char* is declared and assignments are made. I've looked all over, but haven't had any success in finding anything.
Thanks, Ben
You can do it in the most obvious way. Here is some code:
void print_strings(const char *arr[], const int arr_sz)
{
for (int i=0; i < arr_sz; i++)
std::cout << arr[i] << std::endl;
}
const int arr_sz = 3;
const char *arr[sz] = { "first", "second", "third" };
print_strings(arr);
arr[0] = "first modified";
print_strings(arr);
Is this what you were looking for?
"Ben" <bw****@gmail.com> wrote in message
news:da**************************@posting.google.c om... Hey everybody,
I'm working on a program in c++, and I've come up against a problem that I can't figure out. I don't imagine that it's too difficult to solve, but it has been giving me trouble.
What I would like to do is create an array of strings. More specifically, I would like to create an array of char* 's. And the only catch is that I will need to pass the array by reference to several methods. Although from my understanding of pointers, I imagine that this is how things are done inherently in c++.
That's a very strange set of requirements, are you sure that is what you
want?
I would really appreciate if somebody could give me a snippet of code where an array of char* is declared and assignments are made. I've looked all over, but haven't had any success in finding anything.
No one has given you exactly what you have asked for so here it is, it might
be what you want, but I doubt it.
void func(char* (&array)[3]);
int main()
{
char* array[3] = { "apple", "pear", "orange" };
func(array);
}
void func(char* (&array)[3])
{
for (int i = 0; i < 3; ++i)
cout << array[i] << '\n';
}
The strange syntax for the parameter of func is how you pass an array by
reference.
I think that in the context of my program, what makes the most sense
is to use char**'s. The problem is that I'm not exactly how to use
them. Basically, I am writing a program with threading, and would
like to insert char* 's into an array within each thread. I *think*
that I can declare the array of char*'s globally, then would be able
to insert the 'strings' based on a type of hashing. The problem is
that I'm not sure how to insert char*'s into the array. Here's my
best guess:
//Allocate memory for the char**
char** myCache = (char**)malloc(10000);
//Attempt to put 'a' at position 0,0
myCache[0][0] = (char*) 'a';
This will compile, but gives me a seg fault whenever I try to run it.
Is there an easier way to insert strings into a char** array?
Thanks again,
Ben
"Ben" <bw****@gmail.com> wrote in message
news:da**************************@posting.google.c om... I think that in the context of my program, what makes the most sense is to use char**'s. The problem is that I'm not exactly how to use them. Basically, I am writing a program with threading, and would like to insert char* 's into an array within each thread. I *think* that I can declare the array of char*'s globally, then would be able to insert the 'strings' based on a type of hashing. The problem is that I'm not sure how to insert char*'s into the array. Here's my best guess:
//Allocate memory for the char** char** myCache = (char**)malloc(10000);
//Attempt to put 'a' at position 0,0 myCache[0][0] = (char*) 'a';
This will compile,
Actually it won't because of the cast. But I guess that's a typo.
but gives me a seg fault whenever I try to run it. Is there an easier way to insert strings into a char** array?
You are allocating memory for the array but not for the strings.
//Allocate memory for the char**
char** myCache = (char**)malloc(10000);
//Allocate memory for the char*
myCache[0] = (char*)malloc(100);
//Attempt to put 'a' at position 0,0
myCache[0][0] = 'a';
Another question. How big do you think your array is in the first example?
10000 strings? That's wrong, its 10000 bytes big, which is not the same as
10000 strings. If you want 10000 strings then it has to be
char** myCache = (char**)malloc(10000*sizeof(char*));
Everything about your problem screams vector and strings to me, but you are
using arrays and char pointers. Look at Jon Bell's post if you want to know
how this is normally done in C++. All the code above is typical C not C++.
john
Ben wrote: I think that in the context of my program, what makes the most sense is to use char**'s. The problem is that I'm not exactly how to use them. Basically, I am writing a program with threading, and would like to insert char* 's into an array within each thread. I *think* that I can declare the array of char*'s globally, then would be able to insert the 'strings' based on a type of hashing.
But remember synchronizing your threads.
The problem is that I'm not sure how to insert char*'s into the array.
You should really consider using a vector, which hides all the nasty details
from you.
Here's my best guess:
//Allocate memory for the char** char** myCache = (char**)malloc(10000);
Why malloc and not new? Also, if you want to allocate 10000 pointers, it
would have to be:
char** myCache = (char**)malloc(10000 * sizeof(*myCache));
With new, it looks a bit simpler:
char** myCache = new char*[10000];
But remember: If you use new[] for allocation, you need delete[] for
deallocation.
If the number of pointers is fixed, like in your example, it would actually
be better to avoid the dynamic memory allocation and instead write:
char* myCache[10000];
and you get an array of 10000 pointers to char.
//Attempt to put 'a' at position 0,0 myCache[0][0] = (char*) 'a';
That won't work. First of all, myCache[0] is a pointer to char that isn't
yet initialized, i.e. doesn't point anywere. You must not dereference that
pointer as long as it's not yet initialized to point somewhere. So you
cannot access myCache[0][0] because it simply doesn't exist. Further,
casting 'a' into a char* doesn't make sense. What happens is that the value
that is equivalent to 'a' (in Ascii, it would be 0x61) is interpreted as a
pointer value. So the result of that conversion might be a pointer that
points to address 0x61 (if that is a valid address at all on your system).
This is a good example for why you should not use C style casts.
You should have written:
myCache[0] = "a";
This will compile, but gives me a seg fault whenever I try to run it. Is there an easier way to insert strings into a char** array?
Thanks again, Ben
Ben wrote: I think that in the context of my program, what makes the most sense is to use char**'s. The problem is that I'm not exactly how to use them. Basically, I am writing a program with threading, and would like to insert char* 's into an array within each thread. I *think* that I can declare the array of char*'s globally, then would be able to insert the 'strings' based on a type of hashing.
In this case, I would strongly suggest to figure out the container
classes. If you need some 'sort of hashing', then std::map might
be the thing you really want instead of an std::vector.
The problem is that I'm not sure how to insert char*'s into the array.
If you are not sure, then don't do it. You don't have to. C++
has predefined things you can use out of the box, which help you
in storing strings in a container. You simply decide which container
is the best for your needs (eg. std::vector or std::list or std::map
or std::multimap or ...) and can start immediatly caring about
your real problem instead of doing all those error prone low
level stuff with allocating memory and sticking pointers into
arrays and taking care that everything continues to work when
you pass things around.
--
Karl Heinz Buchegger kb******@gascad.at This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Federico G. Babelis |
last post by:
Hi All:
I have this line of code, but the syntax check in VB.NET 2003 and also in
VB.NET 2005 Beta 2 shows as unknown:
Dim local4 As Byte
...
|
by: SilverWolf |
last post by:
I need some help with sorting and shuffling array of strings. I can't
seem to get qsort working, and I don't even know how to start to shuffle
the...
|
by: Simon Schaap |
last post by:
Hello,
I have encountered a strange problem and I hope you can help me to
understand it. What I want to do is to pass an array of chars to a...
|
by: arkobose |
last post by:
hey everyone!
i have this little problem. consider the following declaration:
char *array = {"wilson", "string of any size", "etc", "input"};
...
|
by: arkobose |
last post by:
my earlier post titled:
"How to input strings of any lengths into arrays of type: char
*array ?"
seems to have created a confusion. therefore i...
|
by: Michael |
last post by:
Hi,
I am trying to pass a function an array of strings, but I am having trouble
getting the indexing to index the strings rather than the...
|
by: Potiuper |
last post by:
Question: Is it possible to use a char pointer array ( char *<name> ) to read an array of strings from a file in C?
Given: code is written in ANSI...
|
by: Shhnwz.a |
last post by:
Hi,
I am in confusion regarding jargons.
When it is technically correct to say.. String or Character Array.in c.
just give me your perspectives in...
|
by: Bob Rock |
last post by:
Hello,
I have an array of strings and need to find the matching one with the
fastest possible code. I decided to order the array and then write a...
|
by: Morten71 |
last post by:
I have a strange problem.
I have a local string() var I populate this way:
clmns() As String = {"InvoiceNo", "InvoiceDate"}
When I call:...
|
by: concettolabs |
last post by:
In today's business world, businesses are increasingly turning to PowerApps to develop custom business applications. PowerApps is a powerful tool...
|
by: better678 |
last post by:
Question:
Discuss your understanding of the Java platform. Is the statement "Java is interpreted" correct?
Answer:
Java is an object-oriented...
|
by: Kemmylinns12 |
last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
|
by: jalbright99669 |
last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
|
by: antdb |
last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine
In the overall architecture, a new "hyper-convergence" concept was...
|
by: Arjunsri |
last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...
|
by: WisdomUfot |
last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...
|
by: Matthew3360 |
last post by:
Hi,
I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web...
|
by: Oralloy |
last post by:
Hello Folks,
I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA.
My problem (spelled failure) is with the...
| |