我写了一个简单的C++程序来反转一个字符串.我在字符数组中存储一个字符串.要反转字符串,我使用相同的字符数组和临时变量来交换数组的字符.
#include<iostream>
#include<string>
using namespace std;
void reverseChar(char* str);
char str[50],rstr[50];
int i,n;
int main()
{
cout<<"Please Enter the String: ";
cin.getline(str,50);
reverseChar(str);
cout<<str;
return 0;
}
void reverseChar(char* str)
{
for(i=0;i<sizeof(str)/2;i++)
{
char temp=str[i];
str[i]=str[sizeof(str)-i-1];
str[sizeof(str)-i-1]=temp;
}
}
Run Code Online (Sandbox Code Playgroud)
现在这个方法不起作用,我在程序执行后获得NULL String作为结果.
所以我想知道为什么我不能将字符数组等同,为什么这个程序不起作用.我可以使用什么解决方案或技巧来使相同的程序工作?
我试图计算一个数组中的元素数量,并被告知该行
int r = sizeof(array) / sizeof(array[0])
Run Code Online (Sandbox Code Playgroud)
会给我数组中的元素数量.我发现该方法确实有效,至少对于int数组.然而,当我尝试这段代码时,事情就会破裂.
#include <iostream>
#include <Windows.h>
using namespace std;
int main() {
char binaryPath[MAX_PATH];
GetModuleFileName(NULL, binaryPath, MAX_PATH);
cout << "binaryPath: " << binaryPath << endl;
cout << "sizeof(binaryPath): " << sizeof(binaryPath) << endl;
cout << "sizeof(binaryPath[0]: " << sizeof(binaryPath[0]) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当这个程序运行时,binaryPath的值是
C:\Users\Anish\workspace\CppSync\Debug\CppSync.exe
Run Code Online (Sandbox Code Playgroud)
这似乎有一个sizeof返回的大小(以字节为单位?位?idk,有人可以解释这个吗?)260.该行
sizeof(binaryPath[0]);
Run Code Online (Sandbox Code Playgroud)
给出值1.
显然然后将260除以1会得到260的结果,这不是数组中元素的数量(据我所知它是42左右).有人可以解释我做错了吗?
我有一个潜行的怀疑,实际上并不是我想到的阵列(我来自Java和python),但我不确定所以我问你们.
谢谢!
在sizeof()
用C经营者给其操作数在编译时的大小.它不评估其操作数.例如,
int ar1[10];
sizeof(ar1) // output 40=10*4
sizeof(ar1[-1]) // output 4
int ar2[ sizeof(ar1) ]; // generate an array of 40 ints.
Run Code Online (Sandbox Code Playgroud)
谈到C++模板类,我发现了一些奇怪的结果.
template<typename T>
struct S{
T a;
};
sizeof( S<int> ) // output 4
sizeof( S<bool> ) // output 1
sizeof( vector<int> ) // output 24
sizeof( vector<char> ) // output 24
sizeof( vector<bool> ) // output 40
Run Code Online (Sandbox Code Playgroud)
我猜sizeof
on vector或其他STL容器取决于特定的环境.
问题1.如何sizeof
在C/C++中实现?它不能是运行时功能.这是一个宏吗?(我在在线教程vedio中学到的东西).如果它是一个宏,#define
它看起来像什么?什么时候sizeof()
执行?
问题2.如果我将成员方法添加void f(){}
到定义中struct …
鉴于以下内容,您将看到x和y的大小相同,但y具有附加功能.sizeof中包含哪些内容,哪些内容不包含在内?
struct x
{
double a;
double b;
double c;
double d;
};
struct y
{
double a;
double b;
double c;
double d;
y(double q, double r, double s, double t) : a(q), b(r), c(s), d(t) {};
};
std::cout << sizeof(x)-sizeof(y) <<std::endl;
Run Code Online (Sandbox Code Playgroud)