hey im trying to iterate throughout the entire array of adresses to strings here is what i got so far :
int main()
{
char arr1[]="hello";
char arr2[]="ok";
char arr3[]="goodbye";
char arr4[] ="memo";
char *sumOfAdresses[]={arr1,arr2,arr3,arr4};
for(char**r=sumOfAdresses;*r!='\0';r ){
printf("fadixa");
printf("\n");
}
}
in this case im trying to print 4 times "fadixa" but this method doesnt seem to work, i cant put the size of the array as part of the assignment, this is only half part of my homework and its only a test in main(this should be a method that accepts only **char and no size)
CodePudding user response:
You can use the sizeof operator to get the number of items in the sumOfAdresses array. You can also print the elements using the number of elements in the array.
Method 1
#include <stdio.h>
int main()
{
char arr1[] = "hello", arr2[] = "ok", arr3[] = "goodbye", arr4[] = "memo";
char *sumOfAdresses[] = { arr1, arr2, arr3, arr4 };
for(char **pointer = sumOfAdresses; **pointer != '\0' ; pointer )
printf("%s\n", *pointer);
return 0;
}
Method 2
#include <stdio.h>
int main()
{
char arr1[] = "hello", arr2[] = "ok", arr3[] = "goodbye", arr4[] = "memo";
char *sumOfAdresses[] = { arr1, arr2, arr3, arr4 };
size_t i = 0;
for(char *pointer = *sumOfAdresses; *pointer != '\0' ; pointer )
printf("%s\n", sumOfAdresses[i ]);
return 0;
}
Method 3
#include <stdio.h>
int main()
{
char arr1[] = "hello", arr2[] = "ok", arr3[] = "goodbye", arr4[] = "memo";
char *sumOfAdresses[] = { arr1, arr2, arr3, arr4 };
size_t size = sizeof(sumOfAdresses) / sizeof(sumOfAdresses[0]);
for(size_t i = 0 ; i < size ; i)
printf("%s\n", sumOfAdresses[i]);
return 0;
}
This program produces the following output:
hello
ok
goodbye
memo
CodePudding user response:
*r
is type of char * not char, you can not compare it with char '\0'
CodePudding user response:
method that accepts only
**char
The common solution is to have the last element of the array as a sentinel, some known value not used elsewhere - like a null pointer to signify the end.
void method(char **r) {
while (*r) {
printf("<%s>", *r);
r ;
}
printf("\n");
}
Call with
// char *sumOfAdresses[]={arr1,arr2,arr3,arr4};
char *sumOfAdresses[] = {arr1, arr2, arr3, arr4, NULL};
method(sumOfAdresses);
