PS:本文作为个人学习C++的笔记,不能保证内容的准确性。如被网友检索到,答案仅供参考。
//《Introduction to Pragramming with C++ 》第7章:指针和C字符串
Error 7.1:数组使用前未初始化
int * count(const char * const s)
{
int *countNumber = new int[10];
for (int i = 0; i < strlen(s); i++) { if (isdigit(s[i])) { ++countNumber[s[i] - '0']; } } //Wrong: 使用new动态创建数组countNumber,使用前并未初始化。
return countNumber;
}
Error 7.2:数组下标越界访问
void count(const char * const s, int * counts, int size)
{
for (int i = 0; i < size; i++) { counts[i] = 0; }
for (int i = 0; i < strlen(s); i++) { if (isalnum(s[i])) { ++counts[s[i] - '0']; } } //Wrong: 当字符为字母时,数组countNumber下标越界访问。
}
//《Introduction to Pragramming with C++ 》第8章:递归
GoodExercise 8.17 : 用递归打印字符串的所有排列
#include <iostream>
using namespace std;
void displayPermutation(const char * const s); // 构造辅助递归函数
void displayPermutation(const char * const str1, const char * const str2); // 递归函数
int main()
{
char testStr[] = "ABC";
displayPermutation(testStr);
return 0;
}
void displayPermutation(const char * const s)
{
displayPermutation("", s);
}
void displayPermutation(const char * const str1, const char * const str2)
{
if (strlen(str2) == 0)
cout << str1 << " ";
else
{
for (int i = 0; i < strlen(str2); i++)
{
char *newStr1 = new char[strlen(str1) + 1];
strcpy(newStr1, str1);
newStr1[strlen(str1)] = str2[i];
newStr1[strlen(str1) + 1] = '\0';
char *newStr2 = new char[strlen(str2) - 1];
int k = 0;
for (int j = 0; j < strlen(str2); j++)
{
if (j != i) newStr2[k++] = str2[j];
}
newStr2[k] = '\0';
displayPermutation(newStr1, newStr2);
}
}
}
OUTPUT : ABC ACB BAC BCA CAB CBA
19万+

被折叠的 条评论
为什么被折叠?



