且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用malloc分配字符串

更新时间:2022-06-10 04:51:59

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;
}