1

XXX----Yep, its a Homework problem, but yea I'm stuck. Why doesn't this print out the elements of the array? Please help---XXX

Ok, we got the printing out part figured out. Thank you so much. Now the problem is the only the first character(s) before the space delimiter gets put into the array. I need all the words or characters to be set into the array.

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);
}
Nu Gnoj Mik
  • 994
  • 3
  • 10
  • 25

2 Answers2

6

This is C. You can't just call printf() and expect it to do the work for you. You need to iterate through the array with a for() or while() loop and print out each element.

Assuming it is an array of strings:

int i;
for (i=0; i<size; i++)
    printf("array[%d] = %s\n", i, array[i]);
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
1

Please check this code. I believe that it does what you are expecting.

#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);
}
CRM
  • 4,569
  • 4
  • 27
  • 33