#Looping over string arrays
34 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.
void foo(const char*const*a,size_t l);// doesn't modify the array nor the strings pointed to in the array
const char*a[]={"abc","def","ghi"};
foo(a,sizeof(a)/sizeof(*a));
something like that?
you could then loop over the array using the size in the function
How does this bind btw? Is this an array of char pointers, or a pointer to char arrays?
In case it wasn't obvious, talking about this: char *a[].
It's more like foo(char ** a) right now, though the strings aren't modified
*a[] is equivalent to *(a[])
And I'm initializing (probably wrongly) the array like char a[][4] = {"abc", "def", "ghi"}
the precedence is equivalent to that of the operators, the expression *a[N] is equivalent to *(a[N])
Size of the strings is known beforehand
alright, so a is a pointer to char arrays? (Just to verify I'm not misunderstanding this here)
a is an array of pointers
the opposite, a pointer to an array
this won't decay to char**, since a isn't an array of pointers here, it is an array of arrays of 4 characters
it would decay to char(*)[4]
when you take a pointer to the first element it is really pointing to the array of 4 characters
Yeah, but I can not create a char(*)[4] type to use in the function argument, can I?
;compile
#include<stdio.h>
void foo(char(*a)[4],size_t l){
for(size_t i=0;i<l;++i){
puts(a[i]);
}
}
int main(void){
char a[][4]={"abc","def","ghi"};
foo(a,sizeof(a)/sizeof(*a));
}
abc
def
ghi
here is an example of passing a char(*)[4] as an argument to a function that iterates over the array
Hmm
And how would that look like as a pointer to pointers **a
Both the initializing and using in func
a pointer to a pointer, points at a pointer
you would need to make a new array that was an array of pointers if you wanted an array of pointers
char ** a;
for(size_t i=0; i<l; ++i){
*a ++;
for(size_t j = 0; j < SIZE; ++j) *a[i] = val;
}```
?
look at my original example:
const char*a[]={"abc","def","ghi"};
a is an array of pointers, so taking the address of the first element will point at the first pointer
if you wanted to make an array of pointers for
char a[][4]={"abc","def","ghi"};
then there would need to be a new array which contained a pointer to the first character of each array
e.g.
char*p[sizeof(a)/sizeof(*a)];
for(size_t i=0;i<sizeof(a)/sizeof(*a);++i){
p[i]=a[i];
}
I'm applying Cunningham's law
Let me try
Great, it works
Hopefully I'm not going into pointer land again
Thanks a lot
!solved