Not sure if this is possible, but I've tried this about a thousand ways now. I am making something with a lot of arrays. I thought I could put the array names into a separate array and then loop through them to call all of their elements. This is the best I've got so far:
#include <stdio.h>
#include <stdlib.h>
int main() {
char c;
int a [5] = {1,2,3,4,5};
int b [5] = {6,7,8,9,10};
for(c = 'a'; c <= 'b'; ++c) {
for (int j = 0; j < 5; j++){
printf("%d\n", c[j]);
}
}
}
From it I get the following error:
$ gcc canloop.c -o canloop
canloop.c: In function �main':
canloop.c:17:20: error: subscripted value is neither array nor pointer nor vector
printf("%d\n", c[j]);
Oddly enough it still runs despite the error:
$ ./canloop
0
1
2
3
4
0
1
2
3
4
Seems its not incrementing on the first loop with c. I've tried changing ++c to c++, casting, etc, but no change. Anyone know if this is not possible, some way to do this better or what I may be missing?
I did try that with pointers several different ways. Just tried it again and for the first time this compiled with no errors:
#include <stdio.h>
#include <stdlib.h>
int main() {
int c;
int *test;
test = &c;
int a [5] = {1,2,3,4,5};
int b [5] = {6,7,8,9,10};
for(c = 'a'; c <= 'b'; ++c) {
for (int j = 0; j < 5; j++){
printf("%d\n", test[j]);
}
}
}
That it compiled without errors only means your program is correct grammatically, the same way "my hovercraft is full of eels" will pass a grammar check but not help Belgians communicate with foreigners. Your program does not do what you think it does.
for(c = 'a'; c <= 'b'; ++c)
'a' and 'b' are the ASCII integers 91 and 92, respectively. They are not the arrays a and b and cannot be used to retrieve those variables.
How about this?
#include <stdio.h>
int main(int argc, char *argv[])
{
int a [5] = {1,2,3,4,5};
int b [5] = {6,7,8,9,10};
int *c[]={a, b}; // c[0] is effectively a, c[1] is effectively b
int n, m;
for(n=0; n<1; n++)
{
for(m=0; m<5; m++)
{
printf("Array %d[%d] = %d\n", n, m, c[n][m]);
}
}
}
I will agree with what you said. I knew it was a logical error instead of syntactical one when I saw it. I was just happy to have made any progress at that point.
Your code is much better and cleaner, but I did have to edit it. At first it only printed the first array: