LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to fill-up an pointer to an array of char in C (https://www.linuxquestions.org/questions/programming-9/how-to-fill-up-an-pointer-to-an-array-of-char-in-c-4175577347/)

robertjinx 04-13-2016 07:08 AM

How to fill-up an pointer to an array of char in C
 
I'm writing a little code, nothing fancy, which gets the open file from /proc/<pid>/maps:

Code:

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

int main()
{
        FILE *file;
        char filename[1024];
        char input[4096];

        snprintf(filename, sizeof(filename), "/proc/1/maps");
        file = fopen(filename, "re");
        if (file) {
                while (fgets(input, 4096, file) != NULL) {
                        char *pos;

                        pos = strstr(input, "/");
                        if (pos != NULL) {
                                size_t len = strlen(pos);
                                if (pos[len - 1] == '\n')
                                        pos[len - 1] = '\0';
                        }
                }
        }

        return 0;
}

I would like to put all 'pos' into an char array or point char array, as you wish. I've tried some 'ideas', but all end-up with segfault or errors.

Never used a proper char array, so really not sure how to. Can anyone show me how or point me in the right direction?

when I've tried my luck, I've used something like:

Code:

char **s_array;
int count = 0;

s_array = calloc(1, sizeof(char *));
...
strcpy(s_array[count], pos);
count++;
s_array = realloc(s_array, (count + 1) * sizeof(char *);
...

but this didn't really work.

smallpond 04-13-2016 09:58 AM

You need an array of pointers to arrays of characters (C strings). The outer array is of unknown length, so you can either read the file twice: once to determine the number of lines and then to read each line, or you can create an array that is "big enough"

Code:

char **s_array = calloc(4096, sizeof(char *));  // enough for 4096 strings
Then as you read in each string, allocate space for it and add it to the array.

Code:

size_t len = strlen(pos);
if (pos[len - 1] == '\n') {
    pos[len - 1] = '\0';
    len--;
}
if (count >= 4096)
    return EOVERFLOW;
s_array[count] = calloc(len + 1, sizeof(char));
strcpy(s_array[count], pos);
count++;


robertjinx 04-13-2016 10:44 AM

Sorry, but in calloc isn't the fist argument no_of_elements? Or am I reading wrong the documentation?

NevemTeve 04-13-2016 12:05 PM

Never mind it simply takes the product of the two values
Also sizeof(char)==1. Plus there is a handy function called 'strdup'

robertjinx 04-14-2016 06:00 AM

Thanks guys, all worked.


All times are GMT -5. The time now is 09:49 PM.