#Looping over string arrays

34 messages · Page 1 of 1 (latest)

cunning tree
#

Title. I want to loop over string (char *) arrays. Size is known, but I have to pass them through a function so they will invariable become char** and I wonder how to do that.

odd wadiBOT
#

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.

whole slate
#
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

oblique flare
cunning tree
cunning tree
#

And I'm initializing (probably wrongly) the array like char a[][4] = {"abc", "def", "ghi"}

whole slate
cunning tree
#

Size of the strings is known beforehand

oblique flare
oblique flare
#

ah okay...

#

Sry for the distraction but what would (*a)[] be then?

whole slate
molten warrenBOT
#
int(*a)[]

Declare a as pointer to array of int

whole slate
cunning tree
#

Yeah, but I can not create a char(*)[4] type to use in the function argument, can I?

whole slate
#

;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));
}
frank oakBOT
#
Program Output
abc
def
ghi
whole slate
#

here is an example of passing a char(*)[4] as an argument to a function that iterates over the array

cunning tree
#

Hmm

#

And how would that look like as a pointer to pointers **a

#

Both the initializing and using in func

whole slate
#

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

cunning tree
#
char ** a;
for(size_t i=0; i<l; ++i){
    *a ++;
    for(size_t j = 0; j < SIZE; ++j) *a[i] = val;
}```
#

?

whole slate
#

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];
}
cunning tree
#

I'm applying Cunningham's law

#

Let me try

#

Great, it works

#

Hopefully I'm not going into pointer land again

#

Thanks a lot

cunning tree
#

!solved