2016-11-13 36 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; 
} 
相关问题