Assigning a char buffer to an array of 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'm trying to do is get input from the user. And assign this char array to an array of pointers. Therefore, my array of pointers will contain all the entered devices. However, I get UB in this line:

**devices = device_buff;

Thanks so much 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++);
    }
}
+3
source share
4 answers

You must use dynamic or predefined allocation for your array buffer. In the example, Endmarker is an empty string, not a NULL pointer.

#define DEVICE_SIZE 80
typedef char DBuff[DEVICE_SIZE];

static void device_input()
{
  #define MAXB 3
  DBuff device_buff[MAXB+1];
  DBuff *devices=device_buff;
  size_t i = 0;

  for(i = 0; i < MAXB; i++,devices++) {
      printf("Enter device name: ");
      fgets(*devices, (size_t)DEVICE_SIZE, stdin);
  }
  **devices=0;
  devices=device_buff;
  printf("Display devices\n");
  while( **devices ) {
    printf("Device [ %s ]\n", *devices++);
  }
}
+1
source

**devicesis a char, device_buffis an array of char. These two types are incompatible.

+3

.

char** devices = NULL;

NULL. , ().

, , , / . , . char, , , char ( ) "" . , , .

,

#define NUM_OF_NAMES 3

char devices[NUM_OF_NAMES][DEVICE_SIZE] = {0};

devices[0], devices[1] devices[2] - char char[DEVICE_SIZE]. , .

+3

Even if you fix compiler errors (as described by others), what you are trying to do will not work. You call fgets()the same device_arrayevery time, so every time it is called, it overwrites what was there before.

Possible solutions include using arrays with multiple characters (e.g. char device_buff[3][DEVICE_SIZE]) or one long array and moving the pointer every time you call fgets().

+3
source

Source: https://habr.com/ru/post/1758621/


All Articles