我写了这个函数来计算NULL终止的char指针的长度
size_t strlen(char* char_ptr) {
size_t len = 0;
while (*(char_ptr++) != '\0') {
++len;
}
return len;
}
并且它工作正常,但与strlen()相比它非常慢,有没有其他方法可以做到这一点?
注意: <string.h>不可用
下面是我为了解类型转换而编写的一些代码,但我不明白为什么浮点数或双精度值的值打印为"0.000000",即使我从整数数组中输入或尝试从联合的地址解释.
#include <stdio.h>
union test1
{
int x;
float y;
double z;
};
int main()
{
int x[2]={200,300};
float *f;
f=(float*)(x);
printf("%f\n",*f); /*(1)why is this value 0.0*/
*f=(float)(x[0]); /*(2)this works as expected and prints 200.00000*/
printf("%f\n",*f);
union test1 u;
u.x=200;
/*(3)this line give compilation error why*/
//printf ("sizeof(test1) = %d \n", sizeof(test1));
/*(4) this line also prints the value of float and double as 0.0000 why*/
printf ("sizeof(test1) = %lu u.x:%d u.y:%f u.z:%lf \n", sizeof(u), u.x, u.y, u.z);
return 0; …Run Code Online (Sandbox Code Playgroud) 这里我们有sizeof运营商C.它返回数据类型的大小,
printf("%d",sizeof(some datatype));
Run Code Online (Sandbox Code Playgroud)
结果是4(取决于OS).
我想知道它是如何计算的.这个运营商背后的逻辑是什么?如果我请你为sizeof运营商编写代码.你的答案是什么?
注意:我想知道如何sizeof编写代码,以便能够计算大小.
我可能无法正确地提出我的问题,我在这里再试一次.
Write one function which we can use instead of sizeof operator.
在阵列有四个元件,因此大小应4BIT*4 = 16(int数据类型采取在我的系统4位以存储该值.)但是,当我跑这个代码我只得到8位为的大小dynamicArray.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
//Dynamic arrays save memory by creating a pointer that stores
//the beginning of the array
int *dynamicArray = malloc(20 * sizeof(int));
*dynamicArray = 10;
printf("Address %x stores value %d\n", dynamicArray, *dynamicArray);
dynamicArray[1] = 20;
printf("dynamicArray[1] stores value %d\n", dynamicArray[1]);
dynamicArray[2] = 45;
printf("dynamicArray[2] stores value %d\n", dynamicArray[2]);
dynamicArray[3] = 34;
printf("dynamicArray[3] stores value %d\n", dynamicArray[3]);
printf("The size of dynamicArray is %d\n", sizeof(dynamicArray));
// Release unused memory:
free(dynamicArray);
return …Run Code Online (Sandbox Code Playgroud) 在C99中,§6.5.3.4:
2
sizeof运算符产生其操作数的大小(以字节为单位),该操作数可以是表达式或类型的带括号的名称....4结果的值是实现定义的,其类型(无符号整数类型)
size_t在<stddef.h>(和其他头文件)中定义.
在C++ 14中,§5.3.3:
1
sizeof运算符产生其操作数的对象表示中的字节数....应用于任何其他基本类型(3.9.1)的sizeof的结果是实现定义的.
唯一保证的值是sizeof(char),sizeof(unsigned char)而且sizeof(signed char)是一个.
但是,"对象表示中的字节数"对我来说似乎很不错.例如,在C99§6.2.6.1中:
4存储在任何其他对象类型的非位字段对象中的值由n × CHAR_BIT位组成,其中n是该类型对象的大小(以字节为单位)....
那么为什么它是实现定义的,如果看起来很明确?
你们当中许多人似乎误解了我的问题.我从未声称:
A)类型的大小在所有系统上定义或相同,
B)实现定义意味着它可以返回"随机值"
我在这里得到的n * CHAR_BITS是一个固定的公式.公式本身不能在实现之间改变.是的,一个int可能是4个字节或8个字节.我明白了.但是在所有实现之间,值必须n * CHAR_BITS.
可能重复:
如何查找sizeof(指向数组的指针)
我正在使用以下代码创建一个数组
float *A;
A = (float *) malloc(100*sizeof(float));
float *B;
B = (float *) malloc(100*sizeof(float));
Run Code Online (Sandbox Code Playgroud)
但在这些之后,当我按下面的方式键入A和B的大小时,我得到2,因为我希望看到100.
sizeof(A)/sizeof(float)
Run Code Online (Sandbox Code Playgroud) 在接受C/C++职位的采访时,我遇到了一个问题:写ac程序来实现sizeof运算符,我已经编写了代码,然后他让我使用按位运算实现.我尝试用int ....但是我很好, ,,,任何人都可以发布代码,如何实施,,,