2015-03-13 29 views
0
#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 
int main() 
{ 
    char *p; 
    p=calloc(10,sizeof(char)); 
    printf("the address of pointer is %p and size of the string is %d",p,strlen(p)); 
    return 0; 
} 

我使用釋放calloc分配10個字節的存儲器堆,我希望大小的輸出將是10,但輸出是意想不到輸出,同時使用strlen函數

the address of pointer is 0x123e010 and size of the string is 0 

爲什麼大小爲0,而不是10

回答

1

strlen只計算其值不是0x00的字節數(也稱爲NULL,C標準用於字符串終結符)。

由於calloc在分配它之後將存儲器初始化爲0x00,因爲第一個字節已經是NULL,所以strlen返回0。