C string array

Asked

Viewed 506 times

0

I know that to define a word (string) in C, it is necessary to use a vector of characters, with a defined number of characters that will be used. However, how can I use a multi-word vector, that is, a string vector? The reason for my question is an exercise in which I must create an array that stores the name of 10 products. Thanks in advance!

1 answer

1


There are several ways to do this. I’ll tell you the ones I find simpler.

If you don’t want to change the strings, you can just do:

const char *a[2];
a[0] = "blah";
a[1] = "hmm";

When you do so, you will be allocated a two pointer array to const char. These pointers point to static strings “blah” and “hmm”.

If you want to be able to change the content of the strings, do something like this:

char a[2][14];
strcpy(a[0], "blah");
strcpy(a[1], "hmm");

This way two consecutive arrays of 14 chars each will be allocated. Then just copy the contents of the static strings into them.

Translated from the original in English: https://stackoverflow.com/a/1088667

  • Another possibility is to use dynamic memory allocation by declaring a pointer to char and using the malloc function with the desired size.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.