【发布时间】:2011-04-19 00:44:15
【问题描述】:
我编写了一个小程序来查找既是质数又是特定数 n 的因数的数。我从一个文件中获取数字 n 并将其打印到另一个文件中。
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
#include <cstring>
#include <iostream>
#include <fstream>
using namespace std;
bool PrimeFactor(int );
int countSize(int);
char * p_str = "";//store result of prime factor
int size = 0;//length of p_str
int main(int argc, char** argv) {
std::ifstream fin;
fin.open("input.txt");
std::ofstream fout;
fout.open("output.txt", std::ios::app);
int N;//number to factor
while (fin >> N){
//Find prime factor
PrimeFactor(N);
fout << p_str;// print string storing result
fout << endl;
}
fin.close();
fout.close();
return 0;
}
bool PrimeFactor( int n ){
int count = 0;// count divisors
for (int i = 2 ; i < n; i++){
if ( n % i == 0 ){
// convert integer to string
char * tmpstr = new char[ countSize(i) ] ;// allocate according to size of integer (not waste memory)
sprintf( tmpstr, "%d ", i); // NOTE : if not have the blank after %d -> no space
// condition : prime and not duplicate existing number in global string
if ( PrimeFactor(i) && !strstr( p_str, tmpstr ) ){
char * new_p = new char [ size + countSize(i) ];
strcpy( new_p, p_str );// copy the global string to new place
strcat( new_p, tmpstr );// append new integer value
p_str = new_p ; // let glocal string be renewed with appending new result
size = size + countSize(i);
cout << size << endl;
}
count ++;
}
}
if (count > 0)//not prime
return false;
return true;
}
//counting the number of digit of an integer
int countSize(int n){
int count = 0;
if (n < 10)
return 1;
while ( n >= 10 ){
count++;
n = n/10;
}
return count + 1;
}
使用这种方法,如果我不将创建的数字存储在 C 字符串中并检查下一个数字是否已经是字符串中的数字,则结果可能会重复。我选择 C-string 因为它比 std::string 更具挑战性。 所以问题是关于操纵字符串以最小化内存使用。我必须使用指向字符的全局指针(因为不必定义字符数组的大小)。 似乎 func CountSize() 虽然返回了所需的内容(字符串中数字的长度),但字符串仍然浪费了一些内存,并且 size 变量不是我的意思。此外,我无法通过使用 sizeof() 和指向字符的指针来获取大小。 任何人都可以帮助我吗?
【问题讨论】:
-
我会说浪费内存是您最不担心的事情。我会使用删除来查看内存管理。您必须计算字符数,并确保记住最后为 null 的 +1。
-
我会使用 std::string 并专注于查找您正在寻找的数字。为什么要最小化小字符串的内存使用量?为什么你认为你比标准库做得更好?
-
一个 char* 字符串而不是一个 std::string 来存储你的数字列表? std::vector 怎么样?
-
我曾考虑过 std::string 和 vector,但让我们假设我们正在处理 C,而不是 C++。我想把自己放在一个 C 程序员的位置上考虑一下。
-
然后把你问题上的标签改成C。
标签: c++ memory-management