?
Solved

C++ string array assignment

Posted on 2011-10-18
10
Medium Priority
?
252 Views
Last Modified: 2012-05-12
I am doing C++ after a long time.  I am getting a little trouble in lines with comment of NEED HELP.
#include<iostream>
#include<string>
#include<cassert>

using namespace std;

struct Delims
{
    string start[];
    string end[];
    int tok_len[];
    Delims(string s[], string e[])
    {
        assert ( sizeof(s) == sizeof(e) );
        start = s;       // NEED HELP
        end   = e;       // NEED HELP
        //Check the lengths
        for (int i=0 ; i < sizeof(s)/sizeof(string) ; i++)
        {
            tok_len[i] = start[i].size();
        }
    }
};

int main()
{
    string x[] = {"ABC","XYZ"};
    string y[] =  {",", ","};
    Delims a(x,y);
    return 0;
}

Open in new window

0
Comment
Question by:farzanj
  • 4
  • 2
  • 2
  • +2
10 Comments
 
LVL 31

Assisted Solution

by:Zoppo
Zoppo earned 600 total points
ID: 36986889
HI farzanj,

I would suggest to use a STL container for strings instead of a C-style array - you could i.e. do something like this:
...
#include <vector>
typedef vector< string > tStringVector;
typedef vector< int >      tIntVector;

struct Delims
{
    stringVector start;
    stringVector end;
    intVector tok_len;
    Delims(stringVector s, stringVector e)
    {
        assert ( s.size() == e.size() );
        start = s;
        end = e;
        //Check the lengths
        tok_len.resize( s.size() );
        for (int i=0 ; i < s.size() ; i++)
        {
            tok_len[i] = start[i].size();
        }
    }
};
...

Open in new window

(I hope I understood the code correctly, I didn't test this one).

Hope that helps,

ZOPPO
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 600 total points
ID: 36986911
Well, first of all, you should forget about string arrays - C++ would use std::vectors for that, i.e.
#include<iostream>
#include<string>
#include<cassert>

using namespace std;

struct Delims
{
    vector<string> start;
    vector<string> end;
    int tok_len;
    Delims(const vector<string>& s, const vector<string>& e)
    {
        assert ( s.size() == e.size() );
        start = s;       // will be don seamlessly
        end   = e;       // will be don seamlessly
        //Check the lengths
        // this loop seems quite pointless, since 'sizeof(string)' is a meaningless constant expression.
        for (int i=0 ; i < sizeof(s)/sizeof(string) ; i++) 
        {
            tok_len[i] = start[i].size();
        }
    }
};

int main()
{
    string x[] = {"ABC","XYZ"};
    string y[] =  {",", ","};
    vector<string> v1(x, x + 1);
    vector<string> v2(y, y + 1);
    Delims a(v1,v2);
    return 0;
}

Open in new window

0
 
LVL 31

Author Comment

by:farzanj
ID: 36986928
Hi Zoppo,

This is certainly good help.  However, since I am a very old time C++ programmer, I want to recall it too.  Could you please tell why my previous program did not compile?
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 31

Author Comment

by:farzanj
ID: 36986964
Hi JKR,

sizeof(s)/sizeof(string) tells the number of elements in an array.  Sorry, I still have old touch in my code since I have not touched C++ for more than a decade now.
0
 
LVL 86

Expert Comment

by:jkr
ID: 36986971
Well, then you can just make that
for (int i=0 ; i < s.size(); i++) 
        {
            tok_len[i] = start[i].size();
        }

Open in new window

0
 
LVL 31

Author Comment

by:farzanj
ID: 36987017
Well, your suggestions are great and I would certainly incorporate it.  But, please also tell me why my original code did not compile.  How should I fix that, just for academic reason.  You guys are thinking at an advanced level and since I have been out of touch for a very long time, so I am struggling with basic assignments of arrays & pointers syntax.
0
 
LVL 31

Expert Comment

by:Zoppo
ID: 36987024
Hm - I'm not sure if I can phrase it correctly (some others here do this better), but I'll try: IMO it's not possible to implement a C-style array as member in the form of '<type> <name>[]' (so without knowing the size of the C-style array at compile time). you could re-write the code using pointers as members in the form '<type>* <name>' - in this case you have to take care to allocate and free memory needed for the array. Further it's not possible to use '=' to assign data to a C-style array after it was created. So i.e. it's possible to do something like 'int n[] = { 1, 2, 3 };', but it's not possible to do something like
int n[] = { 1, 2, 3 };
int m[];
m = n

Open in new window

Unfortunateley I have not really enough time just now to find some good resources since I have to catch my train, but I guess anyone else here will give better explanation soon :o)

ZOPPO
0
 
LVL 9

Expert Comment

by:user_n
ID: 36987029

http://pw1.netcom.com/~tjensen/ptr/pointers.htm

Because  this
 start = s;       // NEED HELP Here you are trying to assign to the constant pointer start a pointer s. S points the first element of array s;
 end   = e;       // NEED HELP
is not correct.

in C++ the name of a string is a constant pointer to the first element of the string. You should use http://www.cplusplus.com/reference/clibrary/cstring/strcpy/.


 string start[];
    string end[];
    int tok_len[];
    Delims(string s[], string e[])
0
 
LVL 35

Accepted Solution

by:
sarabande earned 800 total points
ID: 36987696
there are multiple errors in your original code

string s[];

Open in new window


a member in a struct or class needs to be sized. you cannot have variable size array for member, so you would need to have fixed-size arrays or pointer members like

struct st
{
   string s[10];
   string* e;

Open in new window



the Delims(string s[], string e[])

is correct but the string s[] as argument is not an array but a pointer to the first array element. in c and c++ arrays always were passed as pointers. because of that the s passed as argument has pointer size what is 4 or 8 on nowadays compilers. that means you cannot calculate the size of the array from that after you passed it to a function. you either need to use fixed-size arrays (then you know the size) or pass the number of elements as additional argument.

in any case you can't copy the arrays by simply assigning them. you would need a loop and assign each element. note, you can't use memcpy cause string objects have internal pointers. if you copy them those pointers will get invalid when the elements of one of the arrays (one is the array you passed in and the other is the member of the struct object) were deleted. then all elements of the second array were invalid as well and it most likely crashes.

Sara

0
 
LVL 31

Author Closing Comment

by:farzanj
ID: 37028070
Thanks everyone.  But Sara said what I was actually looking for and had forgotten.
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question