如何在 c++ 中正确分配 char* ?

发布于 2024-12-03 16:04:25 字数 455 浏览 1 评论 0原文

我的 C++ 代码如下所示:

char* x;
    switch(i){ 
        case 0:
            x = '0';
        case 1:
            x = "1";
        ...}

我无法弄清楚如何使其工作,因为对于第一个 x = '0'; 编译器抱怨:

error: invalid conversion from ‘char’ to ‘char*’

对于第二个 x = "1"; 编译器抱怨:

warning: deprecated conversion from string constant to ‘char*’

我应该在这里做什么?我的想法完全错误吗?

My c++ code looks like this:

char* x;
    switch(i){ 
        case 0:
            x = '0';
        case 1:
            x = "1";
        ...}

I can't figure out how to make this work because for the first x = '0'; the compiler complains with:

error: invalid conversion from ‘char’ to ‘char*’

and for the second x = "1"; the compiler complains with:

warning: deprecated conversion from string constant to ‘char*’

What should I do here? Am I going about this completely wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

羅雙樹 2024-12-10 16:04:25

case 0 中,您尝试将 x 设置为字符(类型为 char),但在 case 1 中> 您正在尝试将 x 设置为 C 字符串(类型为 char const[2])。引言的类型会产生影响;单引号用于字符,双引号用于 C 样式字符串。

如果您打算两次将其设置为字符串,请在 x = '0' 中的 0 两边加上双引号。

如果您要将 x 设置为字符,请两次使用单引号并取消引用指针,例如 *x,以便它变为 *x = '0',或 *x = '1'x 的类型从 char*< 更改/code>(指向字符的指针)到 char (特点)。那么您就不必取消引用它。1

不过,如果您尝试将 x 设置为字符串,最好使用 C++ 字符串而不是一个 C 字符串,带有 std::string。然后,您可以像 C 字符串一样使用双引号来实现,但您会获得一系列额外的功能,例如自动内存管理、边界检查以及它具有的所有成员函数。

1 正如 Nicolas Grebille 指出的:在执行此操作之前,请确保它指向一个有效的 char,可以使用 new:

char* x = new char;

或通过创建 < code>char 在堆栈上:

char c;
char* x = &c;

重要

如果您稍后打算将 char*strcat 一起使用(或与任何需要 C 字符串的函数),您必须正确NULL终止缓冲区。所以你需要这样做:

char x[2] = {}; // on the stack, filled with NULLs
                // use a bigger number if you need more space

或者

char* x = new char[2]; // on the heap, use more than 2 if you're
                       // storing more than 1 character
x[1] = NULL; // set the last char to NULL

如果你不这样做,如果你不幸的话你会得到垃圾,如果你幸运的话你会得到段错误。

然后,在按上述方式声明 x 后,您可以执行 *x = '0' 或其他操作。

如果您决定使用 new[],请确保使用相应的 delete[] 释放内存。

In case 0 you're trying to set x to a character (of type char), but in case 1 you're trying to set x to a C string (of type char const[2]). It's the type of quotes that make a difference; single-quotes are for characters, and double quotes are for C-style strings.

If you're meaning to set it to a string both times, put double quotes around the 0 in x = '0'.

If you're meaning to set x to a character, use single quotes both times and dereference the pointer, like *x, so that it becomes *x = '0', or *x = '1', or change the type of x from char* (pointer to character) to char (character). Then you don't have to dereference it.1

Then again, if you are trying to set x to a string, it would be better to use a C++ string instead of a C string, with std::string. Then you'd do it with double quotes like a C string, but you'd get a bevvy of extra features like automatic memory management, bounds checking, and all the member functions that it has.

1 As Nicolas Grebille pointed out: before doing that, make sure it points to a valid char, either using new:

char* x = new char;

or by creating a char on the stack:

char c;
char* x = &c;

Important:

If you're going to use a char* with strcat later (or with any function expecting a C-string), you must properly NULL terminate your buffer. So you need to do it either this way:

char x[2] = {}; // on the stack, filled with NULLs
                // use a bigger number if you need more space

or

char* x = new char[2]; // on the heap, use more than 2 if you're
                       // storing more than 1 character
x[1] = NULL; // set the last char to NULL

If you don't do that, you'll get garbage if you're unlucky or a segfault if you are lucky.

Then after you declare x as the above, you can do *x = '0' or whatever.

If you decide to use new[], make sure you deallocate the memory with a corresponding delete[].

暮年慕年 2024-12-10 16:04:25

与普遍的看法相反,char* 不是字符串。使用 std::string 代替。

#include <string>

std::string x;
switch(i){ 
    case 0:
        x = "0";
    case 1:
        x = "1";
    ...}

Contrary to popular belief, char* is not a string. Use std::string instead.

#include <string>

std::string x;
switch(i){ 
    case 0:
        x = "0";
    case 1:
        x = "1";
    ...}
青朷 2024-12-10 16:04:25

如果要使用 char *,则需要为要存储的字符串分配空间,方法是将 x 的声明更改为:

char x[10]; // allocate a fixed 10-character buffer

或动态分配堆上的空间:

x = new char[10]; // allocate a buffer that must be deleted later

然后您可以使用:

strcpy(x, "1"); // Copy the character '1' followed by a null terminator
                // into the first two bytes of the buffer pointed to by x.

复制将字符串“1”放入 x 指向的缓冲区中。如果您使用第二个示例,则必须稍后:

delete x;

当然,如果您确实想处理字符串,则有更好的方法,并且也有更好的方法来处理单个字符(请参阅其他答案)。

If you're going to use a char *, you need to allocate space for the string to be stored either by changing the declaration of x to something like:

char x[10]; // allocate a fixed 10-character buffer

or dynamically allocating the space on the heap:

x = new char[10]; // allocate a buffer that must be deleted later

then you can use:

strcpy(x, "1"); // Copy the character '1' followed by a null terminator
                // into the first two bytes of the buffer pointed to by x.

to copy the string "1" into the buffer pointed to by x. If you use the second example, you must later:

delete x;

Of course if you really want to deal with strings there are better ways, and there are better ways to deal with individual characters as well (see other answers).

谎言月老 2024-12-10 16:04:25

这更像是一个评论,而不是一个答案,但是您可以从 int with: 中获取字符 0, 1,... ,

char x = '0' + i;

这将避免您的 switch 语句(使用 0 <= i <= 9 当然)。

It's more a remark that an answer, but you can get the chars 0, 1,... from the int with:

char x = '0' + i;

wich would avoid your switch statement (with 0 <= i <= 9 of course).

没有伤那来痛 2024-12-10 16:04:25

您声明一个 char 指针,不分配任何空间,然后尝试为其分配一个字符。

char x;

会给你一个 char 类型的变量,

char *x = new char[10]; 

会给你一个指向 char 指针指向的 10 个字节内存的指针。

正如上面 André Caron 所指出的,由于您使用的是 c++,所以您确实应该使用实际的字符串来使您的生活更轻松

You're declaring a char pointer, not allocating any space, then trying to assign a character to it.

char x;

Would give you a variable of type char

char *x = new char[10]; 

would give you a pointer to 10 bytes of memory pointed at by a char pointer.

As noted by André Caron above, since you're using c++ you really should be using an actual string to make your life easier

软糖 2024-12-10 16:04:25

首先,请找出一种使用 std::string 的方法。如果您继续沿着您选择的道路前进,您肯定会创建有错误的程序。

话虽如此,这就是您的答案:如何声明 x 以及如何分配它,在很大程度上取决于您以后如何使用它。下面是一个示例:

#include <stdio.h>
int main(int ac, char **av) {
  const char* x;      
  switch(ac) {
  case 0:
    x = "0";
    break;
  case 1:
    x = "1";
    break;
  default:
    x = "DANGER!";
    break;
  }
  printf("%s\n", x);
  return 0;
}

在第一个示例中,我们将指针 x 设置为指向三个可能的 const char 数组之一。我们可以稍后从这些数组中读取(如在 printf 调用中),但我们永远无法写入这些数组。

或者,如果您希望创建一个数组,您可以稍后写入:

#include <stdio.h>
#include <string.h>
int main(int ac, char **av) {
  char x[32]; // make sure this array is big enough!     

  switch(ac) {
  case 0:
    strcpy(x, "0");
    break;
  case 1:
    strcpy(x, "1");
    break;
  default:
    strcpy(x, "NOT 0 nor 1:");
    break;
  }

  strcat(x, ", see?");
  printf("%s\n", x);
  return 0;
}

编辑:从第二个示例中删除不正确的const

First, please figure out a way that you can use std::string. If you continue on the path you have chosen, you will certainly create buggy programs.

Having said that, here is your answer: How you declare x, and how you assign to it, depends in large part upon how you later use it. Here is one example:

#include <stdio.h>
int main(int ac, char **av) {
  const char* x;      
  switch(ac) {
  case 0:
    x = "0";
    break;
  case 1:
    x = "1";
    break;
  default:
    x = "DANGER!";
    break;
  }
  printf("%s\n", x);
  return 0;
}

In this first example, we set the pointer x to point to one of three possible const char arrays. We can read from those arrays later (as in the printf call), but we can never write to those arrays.

Alternatively, if you wish to create an array you can later write to:

#include <stdio.h>
#include <string.h>
int main(int ac, char **av) {
  char x[32]; // make sure this array is big enough!     

  switch(ac) {
  case 0:
    strcpy(x, "0");
    break;
  case 1:
    strcpy(x, "1");
    break;
  default:
    strcpy(x, "NOT 0 nor 1:");
    break;
  }

  strcat(x, ", see?");
  printf("%s\n", x);
  return 0;
}

EDIT: Get rid of incorrect const from 2nd example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文