gpt4 book ai didi

C编程: How to write char after malloc?

转载 作者:行者123 更新时间:2023-11-30 20:06:44 25 4
gpt4 key购买 nike

我正在学习在 C 中使用指针,并且正在测试如何在 malloc 之后写入 char ?下面是我的代码,但它不起作用。我在这里寻求帮助:

#include <stdio.h>
#define SIZECHAR 10 // write 10 char starting from the first position of malloc

int main(void)
{
// char *charArray = (char *)malloc(SIZECHAR * sizeof(char));

char *charArray = "helloworld"; // this is a temporary pointer

while (*charArray != '\0')
{
int *currentIndex = (int *) charArray++;
printf("the current pointer is %i\n", *currentIndex); // print out the current pointer
}

return 0;
}

非常感谢您的帮助。

最佳答案

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

#define SIZECHAR 10

int main(void) {
//create array for 10 characters plus null terminator
char *charArray = malloc((SIZECHAR + 1) * sizeof(char));

//fill array with digits
int i;
for(i = 0; i < SIZECHAR; i++) {
charArray[i] = (char)('0' + i % 10);
}
//add null terminator to indicate the end of the string
charArray[SIZECHAR] = '\0';

//print the string, plus a newline
printf("%s\n", charArray);

return 0;
}

关于C编程: How to write char after malloc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21359463/

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