2015-01-02 5 views
0

나는 C의 문자열 .h ++ 을 사용하지 않고 새로운 연산자를 사용하여 동적 배열에 문자열의 배열을 복사하고 싶습니다. 어떻게 배열을 복사 할 수 있습니까?C에서 문자열 배열을 동적 배열에 복사하는 방법

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 

내가이

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

그런 짓을하려고하지만 하나의 시퀀스의 모든 배열을 인쇄, 나는

처리하는 방법을 NULL 종결 에 문제가 전혀 없이도하지 않는 생각
+2

['strcpy를()'] (HTTP : // EN .cppreference.com/w/c/문자열/바이트/strcpy). 그리고 새로운 char [n] [LEN];이 잘못되었습니다. –

+0

'const', 미사용 변수's1', 쓸데없는 코멘트가 누락되었습니다 ... – Jarod42

+1

C++에서'char *'를 사용하지 마십시오. 그냥 아파요. 99 %의 시간, 적당한'std :: string'이 당신이 원하는 것입니다. 또한 좀 더 타이핑을한다는 의미 일지라도'std :: vector' (또는 아마도'std :: array')를 사용하십시오. –

답변

1

당신은 차원을 반전 :

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; 

그러나 코드가 고정 길이 문자열의 동적 배열에 가까운 그러나, 그없이, 순수 C는 종종 동적 문자열의 동적 배열을 사용 str의 시도 :

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

1

vector을보세요.

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

소스에서 here

1

제정신 C++ 코드는 vector 또는 array, 또한 string 사용합니다.

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; 
관련 문제