打印出位于动态内存中的数组元素

时间:2011-11-22 01:33:44

标签: c arrays dynamic malloc

XXX ----是的,这是一个家庭作业问题,但是我被卡住了。为什么不打印出数组的元素?请帮助--- XXX

好的,我们得到了打印输出部分。非常感谢。现在问题是空格分隔符放入数组之前唯一的第一个字符。我需要将所有单词或字符设置到数组中。

int main(int argc, char** argv) {

    int size = 0;
    char **array = malloc(0); //malloc for dynamic memory since the input size is unknown
    static const char filename[] = "input.txt";
    FILE *file = fopen(filename, "r");
    if (file != NULL) {
        char line [ 128 ]; 

        char delims[] = " ";
        char *result = NULL;
        while (fgets(line, sizeof line, file) != NULL)  {
            result = strtok(line, delims); //separate by space
            size++;
            array = realloc(array, size * sizeof (char*)); //declare array with unknown size
            array[size - 1] = result;

        }
        fclose(file);
    } else {
        perror(filename);
    }
    return 0;
    printf(array); //print array???
    return (EXIT_SUCCESS);
}

2 个答案:

答案 0 :(得分:6)

这是C.您不能只是调用printf()并期望它为您完成工作。您需要使用for()或while()循环遍历数组并打印出每个元素。

假设它是一个字符串数组:

int i;
for (i=0; i<size; i++)
    printf("array[%d] = %s\n", i, array[i]);

答案 1 :(得分:1)

请检查此代码。我相信它能满足您的期望。

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

int main(int argc, char** argv) 
{
    int size = 0;
    int i;
    char **array = malloc(0); //malloc for dynamic memory since the input size is unknown

    static const char filename[] = "input.txt";
    FILE *file = fopen(filename, "r");

    if (file != NULL) 
    {
        char line [ 128 ]; 

        char delims[] = " ";
        char *result = NULL;

        while (fgets(line, sizeof line, file) != NULL)
        {
            result = strtok(line, delims); //separate by space

            while( result != NULL ) 
            {                       
                size++;

                array = realloc(array, size * sizeof (char*)); //declare array with unknown size
                array[size - 1] = malloc(100 * sizeof(char));  // allocate memory for 100 chars
                strcpy(array[size - 1], result);               // copy the result

                result = strtok( NULL, delims );
            }
        }

        fclose(file);
    } 
    else 
    {
        perror(filename);
    }

    // return 0; 

    for (i = 0; i < size; i++)
    {
        printf("array[%d] = %s\n", i, array[i]);
    }

    // printf(array); //print array???

    return (EXIT_SUCCESS);
}