0

I currently have an array of char*'s. I am trying to use strcpy to assign each element in this array the current string being processed. I have managed to do this with a 2D array of chars (char[][]). However, I want to accomplish this with an array of character pointers because I don't want to define the size of the array at compile time. Is there anyway to have something like the following code?

n = 5;
char* test[n];
strcpy(test[0], "random string");

I understand that strcpy does not work with character pointers which are uninitialised and have looked into using memset. However, I'm hoping for a more elegant solution.

Oliver James
  • 63
  • 1
  • 6
  • 1
    *I understand that strcpy does not work with character pointers which are uninitialised and have looked into using memset. However, I'm hoping for a more elegant solution.* Unfortunately, allocating a pointer is mandatory. There's nothing more elegant to get around that, at least not in C. You don't need `memset`, though. You need `malloc`. – lurker May 04 '20 at 14:41
  • ...or strdup()... – Martin James May 04 '20 at 16:18

2 Answers2

0

You say you don't want to define the size of the array at compile time. Well, at some point you you will have to do it. If it's not at compile time, it's at runtime. And during run time, you can do it with malloc (found in <malloc.h>):

n = 5;
char* test[n];

test[0] = malloc(sizeof(char) * 14); // 14 is the length of the string bellow, plus a terminator
strcpy(test[0], "random string");

If you want it to be cleaner, you can encapsulate it in a function (so you don't have to write malloc many times):

#include <string.h>
#include <malloc.h>

void store(char * storage[], int pos, char const * sentence)
{
  int len = strlen(sentence);
  storage[pos] = malloc(sizeof(char) * (len + 1));
  strcpy(storage[pos], sentence);
}

int main()
{
  int n = 5;
  char * test[n];
  store(test, 0, "random string");
  store(test, 1, "another string");

  return 0;
}
Alejandro De Cicco
  • 1,216
  • 3
  • 17
-1

Please consider using strncpy() instead of strcpy() to avoid writing data outside destination buffer. https://linux.die.net/man/3/strncpy

mar
  • 154
  • 7