以下是程序的文本:
#include <stdio.h>
int f(int x){
return x+1;
}
int main() {
int (*p)(int) = f;
printf( "%d\n", sizeof(p) );
printf( "%d\n", sizeof(f) );
}
Run Code Online (Sandbox Code Playgroud)
该图像与 C 代码相关,我的问题仅针对 C。
这f是函数的名称,并且p是指向该函数的指针f。
由于p最终是一个地址,因此根据地址总线的大小,输出结果sizeof(p)为真,这完全没问题。
这里f也是指向函数f。所以最终f也是一个地址。
我的主要问题是为什么 的输出sizeof(f)不是8,为什么是1以及如何是1?
char* s =(char*) "sss";
int j = -1;
printf("%d", j < strlen(s));
Run Code Online (Sandbox Code Playgroud)
j < 3主要是关于和之间的区别j < strlen(s)。
在上面的代码中,printf()函数打印0,但是如果我改为strlen(s)3,结果就变成1(正如我所期望的那样)。
原因是什么?
我有以下简单的程序:
#include <iostream>
#include <stdio.h>
void SomeFunction(int a)
{
std::cout<<"Value in function: a = "<<a<<std::endl;
}
int main(){
size_t a(0);
std::cout<<"Value in main: "<<a-1<<std::endl;
SomeFunction(a-1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
执行此操作后,我得到:
主要价值:18446744073709551615
函数值:a = -1
我想我大致理解为什么函数获得-1的'正确'值:存在从无符号类型到有符号类型的隐式转换,即18446744073709551615(无符号)= -1(有符号).
是否存在函数无法获得"正确"值的情况?
为什么C++ 在编写代码时没有隐式转换为bool定义for std::string和STL容器
if (!x.empty()) { ... }
Run Code Online (Sandbox Code Playgroud)
而不是更短
if (x) { ... }
Run Code Online (Sandbox Code Playgroud)
当x类型是std::string或例如std::vector?
我也对std::string(在C++ 03中)没有隐式转换为const char*STL示例的事实感到困惑
std::string s("filename");
std::ofstream(s.c_str();
Run Code Online (Sandbox Code Playgroud) /**** Program to find the sizeof string literal ****/
#include<stdio.h>
int main(void)
{
printf("%d\n",sizeof("a"));
/***The string literal here consist of a character and null character,
so in memory the ascii values of both the characters (0 and 97) will be
stored respectively which are found to be in integer datatype each
occupying 4 bytes. why is the compiler returning me 2 bytes instead of 8 bytes?***/
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
2
Run Code Online (Sandbox Code Playgroud) c sizeof type-conversion string-literals implicit-conversion