用malloc分配字符串 [英] Allocating string with malloc

查看:45
本文介绍了用malloc分配字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言编程的新手,现在我正在研究字符串.我的问题是:如果我使用 malloc 分配字符串(如下面的代码所示),是否在字符串末尾自动插入NULL字符?我在这里的另一个问题中找到了答案,似乎没有自动包含NULL字符.但是问题来了:我知道 strlen 之类的功能如果没有NULL字符就不起作用,并且在此代码中我使用了它并且起作用了.因此,我认为字符串的末尾有 \ 0 ,即使我没有在任何地方写它也是如此.答案是什么?

I'm new in programming in C and now I'm studying strings. My question is: if I allocate a string using malloc (as in the code below), is the NULL character automatically inserted at the end of the string? I find an answer in another question here, and it seems that the NULL character is not automatically included. But here comes the problem: I know functions like strlen don't work if there isn't the NULL character, and in this code I use it and it works. So I think there is \0 at the end of my string, even if I don't write it anywhere. What's the answer?

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv) {
    char *stringa1;
    int n;
    int i;

    printf("How many characters in the string? ");
    scanf("%d", &n);

    stringa1 = (char*) malloc(n*sizeof(char));

    printf("Insert the string: ");
    scanf("%s", stringa1);

    free(stringa1);

    return 0;
}

推荐答案

malloc()返回 void * 指针,该指针指向存储在堆中的内存块.使用 malloc()分配不会初始化任何字符串,仅等待空间被占用.要添加以空字符结尾的字符,您必须自己执行此操作,或使用类似 scanf的函数(),它会为您添加此字符.话虽如此,您需要为此 \ 0 字符预先分配空间.

malloc() returns a void* pointer to a block of memory stored in the heap. Allocating with malloc() does not initialize any string, only space waiting to be occupied.To add a null-terminating character, you either have to do this yourself, or use a function like scanf(), which adds this character for you. Having said this, you need to allocate space for this \0 character beforehand.

您的 malloc()调用应改为:

stringa1 = (char*) malloc((n+1)*sizeof(char)); /*+1 for '\0' character */

注意:您不需要强制返回malloc.如需了解详情,请阅读.

Note: You don't need to cast return of malloc. For more information, read this.

要指出的另一件事是 sizeof(char) 1 ,因此不必在您的 malloc()调用中将其相乘.

Another thing to point out is sizeof(char) is 1, so multiplying this in your malloc() call is not necessary.

您还需要检查 malloc()是否返回 NULL .可以这样完成:

You also need to check if malloc() returns NULL. This can be done like this:

if (stringa1 == NULL) {
    /* handle exit */

此外,您只能在以null终止的字符串上使用 strlen(),否则最终将是

Also, you can only use strlen() on a null-terminated string, otherwise this ends up being undefined behaviour.

一旦调用 scanf(),并且 stringa1 包含一些字符,就可以在其上调用 strlen().

Once scanf() is called, and the stringa1 contains some characters, you can call strlen() on it.

此外,检查 scanf()的返回也是一个好主意.您可以像这样检查它:

Additionally, checking return of scanf() is also a good idea. You can check it like this:

if (scanf("%d", &n) != 1) {
    /* handle exit */

您的代码具有以下更改:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    char *stringa1 = NULL;
    size_t n, slen;

    printf("How many characters in the string? ");
    if (scanf("%zu", &n) != 1) {
        printf("Invalid input\n");
        exit(EXIT_FAILURE);
    }

    stringa1 = malloc(n+1);
    if (stringa1 == NULL) {
        printf("Cannot allocate %zu bytes for string\n", n+1);
        exit(EXIT_FAILURE);
    }

    printf("Insert the string: ");
    scanf("%s", stringa1);

    slen = strlen(stringa1);
    printf("String: %s Length: %zu\n", stringa1, slen);

    free(stringa1);
    stringa1 = NULL;

    return 0;
}

这篇关于用malloc分配字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆