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 */
}
是否使用'strlen'? –
也见http://stackoverflow.com/questions/492384/how-to-find-the-sizeofa-pointer-pointing-to-array – Lundin