2016-02-05 36 views
-1
char *foo(char *dest, const char *src) { 
    size_t i;      
    for (i = 0; dest[i] != '\0'; i++); 

在这里,我重复获取dest的大小。 在这种情况下,我会在dest中输入“hello”,它的大小为6.当我尝试使用sizeof(dest)时,我得到4作为返回值。我希望能够在不使用for循环的情况下获取dest内的内容大小。如何在不使用for循环的情况下获取char *变量的大小?

char *foo(char *dest, const char *src) { 
    while (*dest != '\0') dest++;   /* increment the length of dest's pointer*/ 

编辑:: 我想花一点时间来证明我是能够得到直接周围发现的长度。

这是一个strcat程序的所有部分。要求是而不是使用[]方括号来访问或在内存中移动。

char *strcat(char *dest, const char *src) { 
    while (*dest != '\0') dest++;   /* increment the length of dest's pointer*/ 
    while (*src != '\0')     /* we will be incrementing up through src*/ 
     *dest++ = *src++;     /* while this is happening we are appending 
              * letter by letter onto the variable dest 
              */ 
    *(dest++) = ' ';      /* increment up one in memory and add a space */ 
    *(dest++) = '\0';      /* increment up one in memory and add a null 
              * termination at the end of our variable dest 
              */ 
    return dest;       /* return the final output */ 
} 
+1

是否使用'strlen'? –

+0

也见http://stackoverflow.com/questions/492384/how-to-find-the-sizeofa-pointer-pointing-to-array – Lundin

回答

6

对于以空字符结尾的字符串,您必须遍历每个字符来计算长度。即使你使用strlen(),它也会做你的循环。

0

您正在寻找strlen()。但请注意,这可能是用相同的循环来实现的。

0

由于函数中dest的类型为char const*sizeof(dest)sizeof(char const*)相同,即指针的大小。当您使用sizeof(dest)时得到4这一事实表明您的平台中的指针的sizeof为4.

获取字符串长度的唯一方法是对字符进行计数,直到遇到空字符。这很可能是strlen所做的。

0

在C中,字符串存储为字符数组,终止于\0

如果你想获得数组中的字符数,你必须遍历这个数组,你无法绕过它。

但是,您可以将尺寸存储在一个结构,

typedef struct 
{ 
    int size; 
    char *data; 
}String; 

然后,你必须做出包装函数来写这个String,从这个String读取和更新数据。

如果您有大量的读取大小和没有更新或写入很多(或者为常量写入零),这可能很有用。

但通常,for循环是更好的解决方案。

-1

是啊!你可以在不使用循环的情况下获得大小。介绍库和 strlen(dest)+1将你的array.cout的大小< < dest;肯定会给你的数组,但sizeof(dest)不会给出数组的大小。我也很困惑为什么发生这种情况。

+0

'sizeof(dest)'不会给你一个大小的数组,因为它给你'dest'(duh)的大小,'dest'不是数组。 – immibis

+0

但为什么cout << dest;给数组? –

+0

这个问题甚至没有意义。 – immibis

相关问题