2013-05-06 72 views
1

我遇到了char数组大小的问题。我将一个char数组传递给函数,并且在运行该函数后,我仍然希望使用sizeof来检查数组的大小,它不会给我数组的新大小,而是旧大小?我想知道为什么?非常感谢你!为什么字符数组的大小相同使用sizeof()

#include<iostream> 
using namespace std; 

void replacement(char* arr, int len){ 
    int count=0; 
    for(int i=0; i<len; i++){ 
    if(arr[i]==' '){ 
     count++; 
    } 
    } 
    int newlen=count*2+len; 
    //arr[newlen]='\0'; 
    int k=newlen-1; 
    for(int i=len-1; i>=0; i--){ 
    if(arr[i]!=' '){ 
     arr[k--]=arr[i]; 
    } 
    else{ 
     arr[k--]='0'; 
     arr[k--]='2'; 
     arr[k--]='%'; 
    } 
    } 
} 


int main(){ 
    char arr[]="ab c d e g "; 
    cout<<sizeof(arr)<<endl; 
    replacement(arr, sizeof(arr)); 
int i=0; 
    while(arr[i]!=NULL) cout<<arr[i]; 

} 
+1

可能重复[Sizeof数组作为参数传递](http://stackoverflow.com/questions/1328223/sizeof-array-passed-as-parameter) – 2013-05-06 23:34:22

+1

@MatsPetersson不,这是不同的,他没有使用参数上的'sizeof'。 – Barmar 2013-05-06 23:35:06

+0

'while(arr [i]!= NULL)cout << arr [i]; '是一个无限循环。 – 0x499602D2 2013-05-06 23:35:33

回答

3

您不能更改数组的大小。如果您想知道数组中字符串的长度,请使用strlen() - 这将计算空终止符之前的字符数。

更好的是使用C++ std::string类。

+0

你的意思是'std :: string' – 2013-05-06 23:38:35

+0

是的,而且由于他使用的是iostream,他肯定是在C++领域。 – 2013-05-06 23:40:21

+1

@CsabaToth他也有'使用命名空间std'。 – Barmar 2013-05-06 23:41:02

0

当编译时已知大小时,可以使用sizeof()来查找仅静态数组的大小。因此它总会返回在编译时确定的数组大小。

0

程序在技术上具有未定义的行为,因为您使用sizeof会返回您的char阵列的字节大小。但是char隐含地包含空字节\0。这意味着for循环迭代1超过数组的长度。

建议您使用std::string以及size成员函数。

+0

我需要使用c字符串。谢谢。 – diane 2013-05-06 23:51:49

+0

@dianedan对不起,我的意思是'sizeof(arr)/ sizeof(char)'。 – 0x499602D2 2013-05-07 11:27:55

2

对,所以你试图用“%20”替换空格,对吧?

由于C++(或C)不允许调整现有数组的大小,因此您需要首先拥有足够的空间,或者使用在堆上分配的数组。然后在replacement函数中分配一个新的“替换”字符串并返回该字符串。

这样做的正确的C++方法当然是使用std::string,在这种情况下,你可以只通过它作为一个参考,而不要在现有的变量替换:

void replacement(std::string* str, int len){ 
    std::string perc20 = "%20"; 
    std::string space = " "; 
    while((pos = str.find(space, pos)) != std::string::npos) 
    { 
    str.replace(pos, space.length(), perc20); 
    pos += perc20.length(); 
    } 
} 

容易得多。 ..

相关问题