-2

I want to know whether is there a direct way of addressing a 2D char array and store strings on it.

And I know that by using malloc, I could dynamically allocate memory to strings for example for char * names[number] I can malloc (char *)malloc(50*sizeof(char)) and get it done.

And also I know that by using a for loop and assigning each and every element you can achieve the same. I found it through this similar question here .

but my case is ,Is there a way to use array name and indexes to store strings directly.It should look something like this. down here is not a popper code and I just wanted to show how it should look like (from the link I mentioned above)

char arrayOfWords[NUMBER_OF_WORDS][MAX_SIZE_OF_WORD];

int i;`
for (i=0; i<NUMBER_OF_WORDS; i++) {
    arrayOfWords[i] = "laksith"; //here I need to use a way like arrayOfWords+1 etc.
}

I think you may have got the idea of what I'm saying.

Community
  • 1
  • 1
Laksith
  • 354
  • 3
  • 20

1 Answers1

3

Sure you can. But in this case you need to use strcpy instead of the assignment operator:

for (i=0; i<NUMBER_OF_WORDS; i++) {
    strcpy(arrayOfWords[i], "laksith"); //here I need to use a way like arrayOfWords+1 etc.
}

UPD: As @PaulR noted in the comment above, strncpy is a way better option. But first you need to read notes in this link (how to properly handle the missing null byte).

Eldar Dordzhiev
  • 5,105
  • 2
  • 22
  • 26
  • 1
    Why strncpy is better than strcpy ? – vinay hunachyal Sep 14 '15 at 06:33
  • 1
    Because it checks for overrun situations. – Rudi Sep 14 '15 at 06:39
  • @Rudi Not really because No null-character is implicitly appended at the end of destination if source is longer than `size_t n`. Thus, in this case, destination shall not be considered a null terminated C string (reading it as such would overflow). – LPs Sep 14 '15 at 06:51
  • 1
    But if you think ahead and initialize your array when you declare it, the null-terminating character isn't an issue. (e.g. `char array[6][60] = {{0}};`). You now have the entire array filled with null-terminating chars. As long as you limit your copy to 59 chars, your fine. – David C. Rankin Sep 14 '15 at 06:55
  • 1
    strncpy is not better than strcpy, in fact it is far more dangerous and was [never intended to be a safe version of strcpy](http://stackoverflow.com/questions/2114896/why-is-strlcpy-and-strlcat-considered-to-be-insecure). Don't listen to brainwashed people telling you to use strncpy. – Lundin Sep 14 '15 at 07:05
  • @Lundin yeah the articles says so. – Laksith Sep 14 '15 at 07:49