473,324 Members | 2,246 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,324 software developers and data experts.

Array of Strings

Ben
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
Jul 22 '05 #1
7 10904
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
Jul 22 '05 #2
"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?
Jul 22 '05 #3

"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.
Jul 22 '05 #4
Ben
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
Jul 22 '05 #5

"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
Jul 22 '05 #6
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


Jul 22 '05 #7
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
Jul 22 '05 #8

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

Similar topics

7
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 Fixed(local4 = AddressOf dest(offset)) ...
3
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 array. Here is what I have for now: #include...
4
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 function that will split it up (on every location where...
7
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"}; this is a common data structure used to store...
12
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 paraphrase my problem below. consider the...
24
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 individual characters of one of the strings. I have...
2
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 C; I know the exact nature of the strings to be...
14
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 this issue. Thanx in Advance.
11
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 binary search algo. What I came up with is the...
3
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: Array.IndexOf(clmns,"InvoiceDate") I get 0 (zero) as...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.