c++ - Run-Time Check Failure #2 - s for array of C-Strings -
i have following 2 2d arrays of c-strings. trying copy first 1 onto second using strcpy() function. however, keep getting runtime error.
#define _crt_secure_no_warnings #include <cstring> #include <iostream> using namespace std; int main() { char word1[3][3] = { "hello", "bonjour", "ni hao" }; char word2[3][3] = { "steve", "pei", "frank" }; char temp[] = ""; (int = 0; < 3; i++) { strcpy(temp, word1[i]); strcpy(word1[i], word2[i]); strcpy(word2[i], temp); } (int = 0; < 3; i++) { cout << word2[i] << " "; } cout << endl; }
in code find several mistake.
- your char array
word1
,word2
,temp
isn't initialize properly.you need increasesize
ofarray
. - in loop use 3.it break output if word's length become grater 4.
so here give little solution.but better use user input
size of array
input can match properly.
#define _crt_secure_no_warnings #include <cstring> #include <iostream> using namespace std; int main() { char word1[10][10] = { "hello", "bonjour", "ni hao" };//increase array size fit word char word2[10][10] = { "steve", "pei", "frank" };//same here char temp[10] = "";//same here (int = 0; < 10; i++) { strcpy(temp, word1[i]); strcpy(word1[i], word2[i]); strcpy(word2[i], temp); } (int = 0; <10; i++) { cout << word2[i] << " "; } cout << endl; }
Comments
Post a Comment