With 1d char array you could pass them as string literal like this
#include <stdio.h>
void go(char *a)
{
printf("%s", a);
}
int main()
{
go("Hello");
return 0;
}
But can we do this with 2d char array ? something like this perhaps
void go (int rowSize, int colSize, char a[rowSize][colSize])
{
for (int i = 0; i < rowSize; i) {
printf("%s\n"), a[i]);
}
}
go(2, 16, {"Hello", "Hi"});
CodePudding user response:
You need to use compound literal:
void go (size_t rowSize, size_t colSize, char a[rowSize][colSize])
{
for (size_t i = 0; i < rowSize; i)
{
printf("%s\n", a[i]);
}
}
int main(void)
{
go(2, 16, (char[][16]){"Hello", "Hi"});
return 0;
}
As @Lundin suggested you can also use an array of pointers:
void go (size_t nstrings, char **strings)
{
for (size_t i = 0; i < nstrings; i) {
printf("%s\n", strings[i]);
}
}
int main()
{
go(2, (char *[]){"Hello", "Hi"});
return 0;
}
or more const
correct version:
void go (int nstrings, char *const *strings)
{
for (int i = 0; i < nstrings; i) {
printf("%s\n", strings[i]);
}
}
int main()
{
go(2, (char *const[]){"Hello", "Hi"});
return 0;
}
For sizes, indexes etc is better to use size_t
or ssize_t
.
CodePudding user response:
If you want an array pointing at read-only string literals, it has to be an array of character pointers, char* array[] = {"Hello", "Hi"};
. This type is a completely different one than a 2D array of characters and they aren't compatible.
Which form to use in this case depends on what you want to do. Should these be read/write strings or read-only? Do you plan to resize individual strings? And so on. String literals are always read only so the correct pointer type to use when pointing at them is const char*
. However, if you only use string literals for the purpose of initializing a read/write 2D array, then that doesn't matter.
Assuming that the use case is just to print a bunch of string literals in a function and nothing else, then the most correct form is this:
#include <stdio.h>
void go(size_t n, const char* a[n]) {
for (size_t i = 0; i < n; i) {
puts(a[i]);
}
}
int main() {
go(2, (const char*[]){"Hello", "Hi"});
}
This is functionally almost identical to the 2D array version, but it likely doesn't use any temporary memory for storing the strings, so you save some 2x16 bytes etc (which isn't a big deal).