gpt4 book ai didi

c - 给定一个使用 malloc 创建的字符串,如何向其中添加一个整数?

转载 作者:行者123 更新时间:2023-11-30 17:36:13 25 4
gpt4 key购买 nike

为什么在字符串中添加整数时,打印时不显示?这是代码:

char *newStr = NULL;
char *backedUpPtr = NULL;

newStr = (char *) malloc ((4) * sizeof(char));
backedUpPtr = newStr;

*newStr = 'a';
newStr++;
*newStr = 4;

printf("%s", backedupPtr);

打印此内容时,数字 4 将不会显示。这是为什么?我需要将其转换为字符吗?如果是这样,怎么办?

最佳答案

首先,您不会以 NUL 字符终止字符串(因此从技术上讲,它不是 C 字符串)。从 malloc 返回的内存包含任意字节,不一定是零。

换句话说,该代码可能会给您带来麻烦,因为您没有正确终止字符串 - printf 很可能因此崩溃在尖叫堆中。

最重要的是,您将存储代码点 4,即 ASCII 中的 CTRL-D。如果您想要可打印 4,则需要使用'4'

而且,虽然我们列出了一长串问题,但变量 backedUpPtrbackedupPtr 之间存在巨大差异(即 u 的大小写) ),这是释放分配的内存的好形式,并且您不应该在 C 中强制转换 malloc 的返回值,这可能会导致某些微妙的错误。此外,不需要乘以 sizeof(char),因为它始终为一。

底线,我将从这段代码开始,然后从那里继续:

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

int main (void) {
char *newStr = NULL;
char *backedUpPtr = NULL;

newStr = malloc (4); // no need for cast or multiply
if (newStr == NULL) { // and ALWAYS check
printf ("No memory available\n");
return 1;
}
backedUpPtr = newStr;

*newStr = 'a'; // store the a
newStr++;
*newStr = '4'; // store the character 4
newStr++;
*newStr = '\0'; // make into C string

printf ("%s", backedUpPtr);

free (backedUpPtr); // also good form
return 0;
}

虽然它可以写得更简单:

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

int main (void) {
char *newStr = malloc (4);
char *backedUpPtr = newStr;

if (newStr == NULL) {
printf ("No memory available\n");
return 1;
}

*newStr++ = 'a';
*newStr++ = '4';
*newStr = '\0';

printf("%s", backedUpPtr);

free (backedUpPtr);

return 0;
}

或者,由于四个字节的数量相当小,因此根本没有必要使用malloc(除了可能需要了解动态内存分配之外):

#include <stdio.h>

int main (void) {
char backedUpPtr[4], *newStr = backedUpPtr;

*newStr++ = 'a';
*newStr++ = '4';
*newStr = '\0';

printf("%s", backedUpPtr);

return 0;
}

或者,甚至更简单,尽管没有那么有教育意义:-)

#include <stdio.h>
int main (void) {
printf ("a4");
return 0;
}

关于c - 给定一个使用 malloc 创建的字符串,如何向其中添加一个整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22752456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com