Home > OS >  Getting a list of strings from a function without dynamic memory
Getting a list of strings from a function without dynamic memory

Time:11-16

I am writing a C function GetDeviceList() which must return a list of device names found as strings somehow. The number of devices found and of course the device names themselves will vary each time the function is called.

How the function gets the device names is not the scope of this question, but inside the GetDeviceList() function, a char* gets updated in a loop with each new device name found. This char* must then be copied to a list which can be read by the caller.

The function, nor the calling function cannot use dynamic memory.

What would be the best way to get a list of those strings returned from the function. I am thinking of a 2-dimensional char array passed as an output paramater, but not sure.

CodePudding user response:

This is one possibility:

  • you need a static array of chars that is large enough so it can contain all device names
  • The function returns a buffer to this static array which will contain all device names separated by a null character and terminated by two null characters.

Example: for a 3 devices "AA", "BB" and "CC" GetDeviceList() returns a pointer to these bytes:

'A', 'A', 0, 'B', 'B', 0, 'C', 'C', 0, 0

Something like this:

const char *GetDeviceList()
{
  static char devicelist[1000];   // chooses this constant wisely:
                                  // big enough so it can contain the biggest
                                  // possible device list but not too big 
                                  // in order not to waste memory

  // construct your device list somehow ...
}

...
// Display all devices
const char *pdevice = GetDeviceList();

for (int i = 0; *pdevice != 0; i  )
{
  printf("Device #%d: %s\n", i, pdevice);
  pdevice  = strlen(pdevice)   1;
}

However there is one caveat here: you can obviously not get directly get the nth device name, but I'm sure you'll figure this out if you actually need it.

A 2-dimensional char array passed as an output paramater is another possibility, but you'll waste more memory and the code will most likely be more complicated, but on the other hand you'll be able to access the nth device name directly.

CodePudding user response:

Perhaps int GetDeviceList(size_t size, char **dest)?

  1. Pass into GetDeviceList() a pointer to a buffer of memory and its byte size.

  2. Walking from the front of memory, store a pointer to the copied string, which is at the end of available memory.

  3. Repeat for the N devices.

  4. At any time, if insufficient memory, return -1, else return N.

Memory layout in the end.  
[ptr0][ptr1][ptr2].....[string2][string1][string0]

// Usage
char ptrs[100];
int n = GetDeviceList(sizeof ptrs, &ptrs);
if (n >= 0) {
  for (int i = 0; i < n; i  ) {
    printf("<%s>\n", ptrs[i]);
  }
} else {
  puts("Too big");
}
  • Related