0

i just want to copy array of string to dynamical array(using new operator) without using string.h of c++ how can i copying the array?

enter code here
const int LEN=3;
int n=15;
char*s1 ;
char *s[LEN]={"music","disc","soft"};
char (*str)[LEN]=new char[n][LEN];   //i want to copy s to  this array  

i try to do something like this

for(int i=0; i<LEN ;i++){
     strcpy(str[i],s[i]);
}
for(int i=0; i<LEN ;i++)
      cout<<str[i]<<endl;

but it printing all the array in one Sequence, i think a problem with NULL terminator i don't no how to deal with

6
  • 2
    strcpy(). And new char[n][LEN]; is wrong. Commented Jan 2, 2015 at 23:13
  • Missing const, unused variable s1, and obsolete comment... Commented Jan 2, 2015 at 23:15
  • 1
    Don’t use char* in C++, please. It just hurts, and 99% of the time, proper std::string is what you want. Also, please use std::vector (or maybe std::array), even if it means typing a little more. Commented Jan 2, 2015 at 23:17
  • The requirement is to do without using standard string class Commented Jan 2, 2015 at 23:31
  • 1
    @DanielHailemichael: Then change the requirement. Writing C++ in the style of C is a recipe for heartache and pain. Commented Jan 2, 2015 at 23:56

3 Answers 3

1

You invert the dimension of str, try:

const int LEN = 3;
const int n = 15;
const char *s[LEN] = {"music", "disc", "soft"};
char (*str)[n] = new char[LEN][n];

for(int i = 0; i < LEN ; i++) {
    strncpy(str[i], s[i], n);
}
for(int i = 0; i < LEN ; i++)
    std::cout << str[i] << std::endl;

delete []str;

Live example

Sign up to request clarification or add additional context in comments.

Comments

1

Look at vector.

string sArray[3] = {"aaa", "bbb", "ccc"};
vector<string> sVector;
sVector.assign(sArray, sArray+3);

Source from here

Comments

1

Sane C++ code would use vector or array, and also string. However, without those, pure C would often use a dynamic array of dynamic strings:

char** strs = new char*[LEN];  //a dynamic array of dynamic strings
//Alternatively, char* (*strs)[LEN]
for(int i=0; i<LEN; ++i) {
    strs[i] = new char[strlen(s[i])];
    strcpy(strs[i], s[i]);
}
//code goes here
for(int i=0; i<LEN; ++i) 
    delete[] strs[i];
delete[] strs;
strs = NULL;

However, your code is closer to a dynamic array of fixed length strings:

char **strs = new char[n][LEN];  //a dynamic array of dynamic strings
//Alternatively, char(*strs)[LEN][n], or is it char(*strs)[n][LEN]?
for(int i=0; i<LEN; ++i) 
    strcpy(strs[i], s[i]);
//code goes here
delete[] strs;
strs = NULL;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.