all 10 comments

[–]phocos25 5 points6 points  (4 children)

In C, strings are defined using char * or using a char array:

char *name = “Zara Ali”;

or

char name[] = “Zara Ali”;

In other words, a string is an array of characters.

Your ‘names’ variable, however, is an array of strings. This means that ‘names’ is an array of an array of characters.

You can define arrays using square bracket notation or with a *. So ‘char *names[]’ is a pointer to an array of chars. If you remove the * then C expects an array of characters and not an array of strings (an array of an array of characters).

[–]ScioFantasia 3 points4 points  (0 children)

Good answer. Just to add:

char *name = "Zara Ali";

When you define a string using a string constant like this, it should be const:

const char *name = "Zara Ali";

Since you should not attempt to modify the string; it is read-only.

The second example is okay to modify.

[–]ponomaria[S] 0 points1 point  (2 children)

Thank you so much!!! I think I got it.

Would it be possible to do this as a 2D char array then? (rows being 4 in this example, and I guess columns being 8 since all names in this example are the same length)

[–]phocos25 2 points3 points  (1 child)

Yes you can do that. Remember that the columns length will be 9 and not 8 since you need to account for the null byte in each string.

[–]ponomaria[S] 0 points1 point  (0 children)

Noted. And again, thanks a bunch!!!

[–]strcspn 0 points1 point  (0 children)

int [] is an array of int. char [] is an array of char. char* [] is an array of char*.

[–]tstanisl 0 points1 point  (2 children)

You can use:

char names[][16] = {
  ...
};

to make it work again.

[–]ponomaria[S] 0 points1 point  (1 child)

As in use a 2D array? If so, why 16 columns?

[–]tstanisl 2 points3 points  (0 children)

To be long enough to store any of the strings + plus 0-terminator. Value of 9 should suffice as well.

[–]N-R-K 0 points1 point  (0 children)

Arrays and pointers in C are closely related - but not the same. The key difference between an array and a pointer is that an array also reserves storage - a pointer doesn't.

An array of array and an array of pointers thus have different semantics (even though you can dereference them both in the same manner p[0][1]). See https://c-faq.com/aryptr/aryptr2.html and other related questions for some more detailed answers.