Say I have a 3-dimensional char array
char strList[CONST_A][CONST_B][CONST_C];
And an array pointer (changed after comments pointed out the error):
char * args[CONST_C];
I want to pick a part of strList
and make args
to be that value. For example, if strList
representing something like
{{"Your", "question", "is", "ready", "to", "publish!"},
{"Our", "automated", "system", "checked", "for", "ways", "to", "improve", "your", "question"},
{"and", "found", "none."}}
and I want args to be
{"and", "found", "none."}
how should I do it?
I've tried to use args = strlist[someIndex];
but got an error saying incompatible types when assigning to type 'char *[100]' from type 'char (*)[100]'
, strcpy
also seems to fail (probably due to args
was not allocated with enough space?), what should I do to properly assign args
?
edit: args
has been used prior to the assignment, so changing the type of args
, while plausible, does require a lot of extra work on other parts of the code.
You could use a pointer to an array:
char (*args)[CONST_C] = strList[2];
Now code:
puts(args[0]);
puts(args[1]);
puts(args[2]);
will produce:
and
found
none.
What you have now is an array of pointers, a better option would be a pointer to array:
#include <stdio.h>
#define CONST_A 5
#define CONST_B 10
#define CONST_C 15
int main(void) {
char strList[CONST_A][CONST_B][CONST_C] = {
{"Your", "question", "is", "ready", "to", "publish!"},
{"Our", "automated", "system", "checked", "for", "ways", "to", "improve",
"your", "question"},
{"and", "found", "none."}};
char(*args)[CONST_C] = strList[2];
for (size_t i = 0; i < 3; i++) {
printf("%s ", args[i]);
}
}
Output:
and found none.
If you want to use your original array of pointers, you can also do it, but the assignments would also have to be manual sort of speak, you would need to iterate over the arrays to make the assigments, something like:
char *args[3];
for (int i = 0; i < 3; i++)
{
args[i] = strList[2][i];
}
Like you asked in the comments, you can have a single char
pointer pointing to one of the strings, like for instance:
char *args = strList[2][0]; // and
args = strList[2][1]; // found
...
But iterating over the pointer like in the first example is not possible, the dimension of the array is necessary for a correct iteration, hence the need for a pointer to array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.