为什么我不能这样做:
char* p = new char[10];
void SetString(char * const str)
{
p = str;
}
SetString("Hello");
Run Code Online (Sandbox Code Playgroud)
我有一个指向char的const指针,为什么我不能将const指针指向另一个指针?
这似乎是不合逻辑的,因为通过将其分配给另一个指针,您基本上不会违反char指针的常量.或者是你?
编辑:当我编译它时,它说"错误C2440:'=':无法从'char*const*__ w64'转换为'char*'"
(我试图从我正在阅读的书中理解一个概念.只是无法获得编译的代码.
码:
int _tmain(int argc, _TCHAR* argv[])
{
MyString *strg = new MyString(10);
strg->SetString("Hello, ");
MyString *secondstr = new MyString(7);
secondstr->SetString("Tony");
strg->concat(*secondstr, *strg);
}
Run Code Online (Sandbox Code Playgroud)
CPP文件:
#include "MyStringClass.h"
#include <string.h>
#include "stdafx.h"
#include "MyStringClass.h"
void MyString::concat(MyString& a, MyString& b)
{
len = a.len + b.len;
s = new char[len + 1];
strcpy(s, a.s);
strcat(s, b.s);
delete [] s;
}
void …Run Code Online (Sandbox Code Playgroud) 我试图将命令的参数与argv []进行比较,但它不起作用.这是我的代码.
./a.out -d 1
Run Code Online (Sandbox Code Playgroud)
在主要功能
int main (int argc, char * const argv[]) {
if (argv[1] == "-d")
// call some function here
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用......我不知道为什么这种比较不起作用.
我有一个字符数组,我试图找出它是否匹配字符串文字,例如:
char value[] = "yes";
if(value == "yes") {
// code block
} else {
// code block
}
Run Code Online (Sandbox Code Playgroud)
这导致以下错误:与字符串文字比较导致未指定的行为.我也试过类似的东西:
char value[] = "yes";
if(strcmp(value, "yes")) {
// code block
} else {
// code block
}
Run Code Online (Sandbox Code Playgroud)
这不会产生任何编译器错误,但它的行为不符合预期.