2010-06-02 73 views
0

我可以以char数据类型存储少量长度的字符串。以字符数据类型C语言存储字符

但是,当它超过它的容量时,可以用什么方法来存储字符串。

我正在使用char数据类型。

void setString(char* inPoints) 
{ 
if (strcmp(mPoints, inPoints)!= ZERO) { 

    if (mPoints) { 

     free(mPoints); 
    } 

    mPoints = (char*)malloc((strlen(inPoints) + 1) * sizeof(char)); 

    strcpy(mPoints, inPoints); 
} 
} 
+0

你可以在'char'变量中存储单个字符 - 对于字符串,你需要一个恰当的malloced'char *' – Amarghosh 2010-06-02 13:54:03

+1

为什么你会有一个叫做ZERO的符号常量?这比文字0好吗?如果它将是符号的,它应该有意义,例如在这种情况下STRCMP_EQUAL。 – unwind 2010-06-02 14:25:18

+0

不需要在if语句中包装'free'。 'free'接受(并忽略)NULL指针。 – tomlogic 2010-06-02 15:27:33

回答

0

用strncpy代替strcpy的是通常比较安全,但在这里你的Alloc eachtime到入点存储到M点所需的内存适量,所以我看不到有什么意义。您可以在mPoint中存储的字符串的最大长度受malloc-able内存量的限制。

添加:您可以realloc的建议,并有可能你可以在长度增加一个检查,以避免realloc的-ING如果字符串较短;所以M点就能够保持始终为字符串小于最长的字符串到目前为止满足,或等于:


// somewhere altogether with mPoints 
size_t mPointsCurrenStorage = INITVAL; 
// e.g. INITVAL is 256, and you pre-malloc-ate mPoints to 256 chars 
// ... in the func 
size_t cl = strlen(inPoints); 
if (cl >= mPointsCurrentStorage) { 
    mPoints = realloc(mPoints, cl+1); 
    mPointsCurrentStorage = cl+1; 
} 
strcpy(mPoints, inPoints);

这样的存储只生长...

+0

当然我错过了测试,以避免重新分配复制,如果字符串与已存储的字符串相同。你可以在做任何事之前添加它。 – ShinTakezou 2010-06-02 14:16:40

+0

避免'p = realloc(p,size)'。如果'realloc'失败,则泄露了原始指针。 – jamesdlin 2010-06-02 18:00:28

+0

是的,它不是很好的编码,但我用它只是为了表明这一点;所以'char * temp = realloc(mPoints,cl + 1);断言(临时!= NULL);可以使用mPoints = temp'; (如果不喜欢断言,则将断言改为任何需要的检查代码) – ShinTakezou 2010-06-02 18:22:57

3

您可以分配一个新的,更大的阵列和旧的字符串复制到它(并删除旧的,以防止内存泄漏),追加更多字符。或者(如果可能)切换到C++字符串类,这使得这个过程更容易。

+0

这是他的代码已经做了什么,即使他可以使用realloc来代替。 – ShinTakezou 2010-06-02 14:10:07

2

的realloc()应该调整你的字符串

+0

这是他已经做了,即使“手工”,而不是使用realloc(这是无论如何更好的解决方案)。 – ShinTakezou 2010-06-02 14:10:50

0
  • STRCMP与M点= NULL是不允许。
  • ZERO作为一个常量?
  • free()接受NULL指针。
  • 的malloc()不需要在C.
  • 的sizeof(char)的铸造为1
  • 一定要检查的malloc()的返回。

修改的版本:

void setString(char* inPoints) 
{ 
    if ((mPoints == NULL) || (strcmp(mPoints, inPoints) != 0)) 
    { 
     free(mPoints); 

     mPoints = malloc(strlen(inPoints) + 1); 

     if (mPoints != NULL) 
     { 
      strcpy(mPoints, inPoints); 
     } 
    } 
} 

而且你使用一个全局变量M点,有更好的解决方案。但是,这和malloc()= NULL的错误处理不在一边,你总是分配所需的数量,那么“超过它的容量”是什么意思?

+0

mPoints是私人会员。 – boom 2010-06-03 04:37:20

+0

C中没有私人成员。你在说什么? – Secure 2010-06-03 06:35:31