简体   繁体   English

为字符串分配内存

[英]Allocating Memory for a string

I try to allocate memory , store a string then print it but I think it didn't work. 我尝试分配内存,存储一个字符串然后打印它,但是我认为它没有用。

#include<stdio.h>
#include<windows.h>
int main()
{
    char* allochere;
    allochere = malloc(sizeof(char));
    *allochere = "Hello";
    printf("%s",allochere);


    return 0;
}

The assignment to *allochere only assigns a value to the first character of the uninitialized string. *allochere的赋值仅将值分配给未初始化的字符串的第一个字符。 The value assigned is nonsensical to boot, since the right-hand side of the assignment is a pointer. 分配的值对于启动没有意义,因为分配的右侧是指针。 (If you turn on compilation warnings, the compiler will warn you of problems with such an assignment.) (如果打开编译警告,编译器将警告您有关此类分配的问题。)

To correctly initialize the string, you need to call strcpy to copy the string: 要正确初始化字符串,您需要调用strcpy来复制字符串:

strcpy(allochere, "Hello");

Also, you need to allocate allochere with the correct size to hold the string you intend to put there: 另外,您需要以正确的大小分配allochere ,以保存要放置在此处的字符串:

allochere = malloc(strlen("Hello") + 1);

There are several mistakes here. 这里有几个错误。

First of all, you should know that C-strings end with a zero byte . 首先,您应该知道C字符串以零字节结尾。 Thanks to this, you don't have to store string's length, you're just saying "here's the end of my string" using the zero byte. 因此,您不必存储字符串的长度,而只是使用零字节说“我的字符串的结尾”。

Secondly, you call malloc() in a wrong way. 其次,您以错误的方式调用malloc() If you want to allocate memory for an N-letter string, you should write malloc(N + 1); 如果要为N个字母的字符串分配内存,则应写malloc(N + 1); (+1 because the zero byte has to have its cell, too). (+1,因为零字节也必须具有其单元格)。

Lastly, you should use a function like strcpy to copy the string to its destination. 最后,您应该使用诸如strcpy类的函数将字符串复制到其目的地。 In this case, you should call strcpy(allochere, "Hello") . 在这种情况下,您应该调用strcpy(allochere, "Hello")

Your code should look like this: 您的代码应如下所示:

char* allochere;
allochere = malloc(6*sizeof(char));
strcpy(allochere, "Hello");
printf("%s", allochere);

...

// don't forget to deallocate the memory
free(allochere);

That code doesn't make any sense. 该代码没有任何意义。

char *allochere;

'allochere' is a pointer to a char, in other words, a string. “ allochere”是指向char的指针,换句话说,是字符串。

allochere = malloc(sizeof(char));

Now you allocate a single character, and point 'allochere' to that. 现在,您分配一个字符,并将其指向“ allochere”。 BTW, sizeof(char) is always 1. 顺便说一句, sizeof(char)始终为1。

*allochere = "Hello";

Now you set the first char of 'allochere' to a 'const char *', a compiler would barf here. 现在,将“ allochere”的第一个字符设置为“ const char *”,编译器将在此处驳倒。 Now allochere points to random data, not a string. 现在,在这里将指向随机数据而不是字符串。

Let's see some alternatives that work. 让我们看看一些可行的选择。

char *allochere;
allochere = "Hello";
printf("%s", allochere);

char *allochere;
allochere = strdup("Hello");
printf("%s", allochere);

char *allochere;
allochere = malloc(strlen("Hello") + 1);
strcpy(allochere, "Hello");
printf("%s", allochere);

You are not allocating enough memory to hold the word "Hello" - you need to allocate space for 5 chars plus the terminating byte, so you should replace the malloc call with: 您没有分配足够的内存来容纳单词“ Hello”-您需要分配5个字符和终止字节的空间,因此应将malloc调用替换为:

allochere = malloc(6);

You can't assign a string literal to allochere because you will miss the pointer to the allocated memory. 您不能将字符串文字分配给allochere,因为您会错过指向已分配内存的指针。 Instead, after allocating enough space, use strcpy: 相反,分配足够的空间后,使用strcpy:

strcpy(allochere, "Hello");

You need something like this. 您需要这样的东西。

#include<stdio.h>
#include<windows.h>

int main()
{
    char* allochere;

    allochere = malloc(strlen("Hello") + 1);

    strcpy(allochere, "Hello");
    printf("%s\n", allochere);

    return 0;
}

In this case, you need to actually copy the data directly from the string constant "Hello" into your allocated space. 在这种情况下,您实际上需要将数据直接从字符串常量"Hello"直接复制到分配的空间中。 However, before we even get there, there are a couple of issues. 但是,在我们到达那里之前,有两个问题。

  1. Make sure you're allocating enough space. 确保分配了足够的空间。

    You are allocating the sizeof one character, not enough to hold the entire string (5 characters in "Hello" plus one more for the null terminator). 您正在分配一个字符的sizeof ,不足以容纳整个字符串(“ Hello”中的5个字符,再加上一个空终止符,另外一个字符)。 You can do this with 你可以这样做

     allochere = malloc(6); 

    or use the common convention of 或使用以下通用约定

     allochere = malloc(strlen("Hello") + 1); 

    To be more clear about the size and purpose you're allocating the memory for. 为了更清楚地了解其大小和用途,您正在为其分配内存。

  2. You need to copy the data because string assignment doesn't understand exactly what you're trying to do. 您需要复制数据,因为字符串分配无法完全理解您要执行的操作。 By doing 通过做

     *allochere = "Hello"; 

    You're actually assigning the value at allochere to be the address of "Hello" . 您实际上是将allochere的值分配为"Hello"的地址。 If instead you had done this: 相反,如果您这样做:

     allochere = "Hello"; 

    That might actually work (on some systems -- I'm not sure and haven't tested it), but that's because you are assigning and address to an address. 这可能实际上可行(在某些系统上-我不确定并且尚未测试),但这是因为您要分配地址和地址。

    However, you are malloc ing data which means you want to copy the data. 但是,你malloc ING的数据,这意味着你要复制的数据。 Thus, you will want to use something like strcpy to copy from the location into your allocated string. 因此,您将需要使用诸如strcpy东西从该位置复制到您分配的字符串中。 Hence: 因此:

     strcpy(allochere, "Hello"); 
  3. The last problem is going to be actually seeing the output. 最后一个问题将是实际上看到输出。 Because you're using printf , you will need to flush the data to the screen. 由于您使用的是printf ,因此需要将数据刷新到屏幕上。 printf will automatically flush the data if you have a newline ( '\\n' ) character, but you could also use fflush() . 如果您有换行符( '\\n' ), printf将自动刷新数据,但您也可以使用fflush()

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

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