1

I'm trying to read data from a file. I have the following loop. The data in the file is a matrix. The problem I'm having is I'd like to access each element, but &line[0] does not index by character in the line, it prints the whole thing. So the whole row of the matrix is stored in the first index somehow...

I'm having trouble getting it out. I tried copying it to m, but that seems to only give me the first element only.

Lets say for example, &line[0] is "1 2 3", how do I loop through this so I can store it in an array?

    FILE *fptr;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;
    int linenum = 1;
    while ((read = getline(&line, &len, fptr)) != -1) {
        printf("Retrieved line of length %zu:\n", read);
        printf("%s", line);

        //matrix size information
        if (linenum==1){
            char m[100];
            char n[100];

            printf("------\n");
            printf("%s", &line[0]);
            //strcpy(m, &line[0]);

        }

        linenum++;
    }

user267298
  • 129
  • 9
  • the first line is the matrix size information. So a 2 element array with 3 4 for example – user267298 Feb 08 '21 at 06:56
  • If you know the size of the matrix and it is constant, I would suggest your to use `fscanf()` to read the file data than `getline()`. That way you would be having more control over each line. – Arun123 Feb 08 '21 at 07:03
  • Use `strtol()`, `strtoul()` or `strtod()` as appropriate to convert each value in `line` to a value for your matrix. See [How to use `strtol()`](https://stackoverflow.com/a/53800654/3422102) – David C. Rankin Feb 08 '21 at 07:07

1 Answers1

1

&line[0] means no line element by index 0, it's the pointer to char data from zero offset. So if you want to get separate elements from a line you should parse the line using sscanf for example something like this

sscanf("1 2 3", "%d %d %d", &i1, &i2, &i3);
Alexander Egorov
  • 593
  • 10
  • 14
  • Your solution worked, thank you so much. I understand it's the pointer to the first element in char, but I'm confused why printing &line[0], prints the whole array of chars... – user267298 Feb 08 '21 at 17:25
  • Sure in C pointer to a char (&line[0] in your case) in an array by index mean pointer to the string started from this char for example if you write &line[1] you'll get string without first char and so on – Alexander Egorov Feb 08 '21 at 18:21