Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning a char buffer to an array of pointers

Tags:

c

pointers

gcc 4.4.4 c89

warning assignment makes integer from pointer without a cast
**devices = device_buff;
warning: value computed is not used
*devices++;

I get the above warnings with the code below. What I am trying to do is get an input from the user. And assign that char array to an array of pointers. So my array of pointers will contain all the devices entered. However, I am getting a UB on this line:

**devices = device_buff;

Many thanks for any advice,

static void device_input()
{
#define DEVICE_SIZE 80
    char device_buff[DEVICE_SIZE] = {0};
    char **devices = NULL;
    size_t i = 0;

    for(i = 0; i < 3; i++) {
        printf("Enter device name: ");
        fgets(device_buff, (size_t)DEVICE_SIZE, stdin);

        **devices = device_buff;
        *devices++;
    }

    /* NULL terminate last element */
    *devices = NULL;

    printf("Display devices\n");
    while(*devices != NULL) {
        printf("Device [ %s ]\n", *devices++);
    }
}
like image 515
ant2009 Avatar asked Apr 09 '26 06:04

ant2009


2 Answers

**devices is a char, device_buff is an array of char. The two types are incompatible.

Even if you fix the compiler errors (as described by others), what you are trying to do won't work. You are calling fgets() on the same device_array each time, so each time it's called, it will overwrite what was stored there previously.

Possible solutions include using multiple character arrays (e.g. char device_buff[3][DEVICE_SIZE]) or one long array, and advancing a pointer each time you call fgets().

like image 20
Oliver Charlesworth Avatar answered Apr 11 '26 19:04

Oliver Charlesworth