简体   繁体   English

在编译时将const char *转换为char *

[英]Converting a const char* to char* at compile-time

In my project, I need the user to input a string, and the string that is typed is const char* by default (with using quotation marks). 在我的项目中,我需要用户输入一个字符串,并且键入的字符串默认情况下为const char* (使用引号)。 In my project, I also need to modify these strings, so I cannot really use const . 在我的项目中,我还需要修改这些字符串,因此我不能真正使用const

So I thought about transforming the const char* into a char* with the following function: 因此,我考虑使用以下功能将const char*转换为char*

Not 100% sure this is the problem (since it crashes for me) but I believe the problem is that the New string does not have enough memory to store the whole string. 不能100%地确定这是问题所在(因为它对我来说崩溃了),但是我相信问题是New字符串没有足够的内存来存储整个字符串。 I tried sort of allocating it memory by writing like this: 我尝试通过如下方式分配内存:

const char* szOldString = "Test";
char* szNewString[0x1024];
noconst(&szOldString, &szNewString, 5);

This also did not work considering my parameters and the constexpr. 考虑到我的参数和constexpr,这也不起作用。


I am wondering if anybody knows any cool hacks I can use to make this work. 我想知道是否有人知道我可以使用它来完成这项工作。 I have been working on this for some time so the solution might be an obvious one and I just cannot see it. 我已经为此工作了一段时间,因此解决方案可能是显而易见的解决方案,但我只是看不到它。 If that's the case, my bad :D 如果是这样,我的坏:D

The easier way is to use the function strncpy (which is more secure than just using strcpy). 更简单的方法是使用函数strncpy(比仅使用strcpy更安全)。

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
  //char oldString[]= "Hello World!";
  const char* oldString = "Hello World!";
  char newString[40];

  /* copy to sized buffer (overflow safe): */
  strncpy ( newString, oldString, sizeof(newString) );

  cout << newString;  

    return 0;
}

Another way is to allocate with malloc space for where you wish to copy the string. 另一种方法是使用malloc空间分配您想要复制字符串的位置。 After, you can modify it at your please. 之后,您可以根据需要对其进行修改。

Let me know if this helped you out. 让我知道这是否对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM