2016-11-13 67 views
-2

我有以下兩個C字符串的二維陣列。我正在嘗試使用strcpy()函數將第一個複製到第二個。但是,我不斷收到運行時錯誤。運行時檢查失敗#2 - s的C字符串陣列

#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[] = ""; 

    for (int i = 0; i < 3; i++) { 
     strcpy(temp, word1[i]); 
     strcpy(word1[i], word2[i]); 
     strcpy(word2[i], temp); 
    } 


    for (int i = 0; i < 3; i++) { 
     cout << word2[i] << " "; 
    } 

    cout << endl; 
} 
+0

我相當確定a)如果您提供了實際的運行時錯誤,您會得到更好的幫助,b)您應該爲每個字符串提供足夠的空間。如果考慮終止零,則不存在適合3個字符數組的單個字符串。 –

+0

此外,字符串'temp'甚至比''單詞'短,並且不能容納任何東西。爲什麼不先嚐試一些更簡單的方法,比如使用C++'std :: string'並且稍後將這些東西留下? –

+0

您正在使用兩個「C-strings」的1D **陣列,BTW。您的目標是將「列」(或行)添加到實際的二維數組或覆蓋第一個數組? –

回答

0

在你的代碼中,我發現了幾個錯誤。

  • 您的字符數組word1word2temp沒有初始化properly.you需要增加arraysize
  • 在循環使用3.it會打破你的輸出,如果你的字的長度變得比刨絲4.

所以我在這裏給你一點solution.But其更好地利用user input的大小array,使任何輸入可以正確匹配。

#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 to fit word 
    char word2[10][10] = { "Steve", "Pei", "Frank" };//same here 

    char temp[10] = "";//same here 

    for (int i = 0; i < 10; i++) { 
     strcpy(temp, word1[i]); 
     strcpy(word1[i], word2[i]); 
     strcpy(word2[i], temp); 
    } 


    for (int i = 0; i <10; i++) { 
     cout << word2[i] << " "; 
    } 

    cout << endl; 
} 
相關問題