如何在malloc之后写

如何在malloc之后写

Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        5年前关闭。
                                                                                            
                
        
我正在学习在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 - C编程:如何在malloc之后写char? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21359463/

10-10 07:58