0

I want to write something of this sort:

(s[i])[i] ,where s[i] is of type char[].

Example:

s[i]="PDGH";
for(i = 0 ; i < strlen(someNumber) ; i=i+3 )
(s[i])[formula]++; // on compile if s[i]='P', then i want to get P[formula]++ .
  • Maybe With a Dictionary? – Adriano Repetti Dec 05 '16 at 11:11
  • `strlen(someNumber)`? `formula`? It is not at all clear to me what you wantto achieve. – M Oehm Dec 05 '16 at 11:13
  • i want my code to substitute s[i] with its value on compile , such as if i have 4 vector: int A[100],B[100],C[100].D[100] , i could do (s[i])[number] ,where s[i] can only get the values A,B,C,D (that's how the input gets parsed) , so,in the end,it's like writing A[number] or B[number] etc..,without explicitily writing the names A[number],B[number],etc. – user5731286 Dec 05 '16 at 11:16
  • The name of a variable is not a value – it only exists during compilation. If you want to map a name to an object you need to maintain your own table. – molbdnilo Dec 05 '16 at 11:17

1 Answers1

1

What you're asking for is to map a string (well, in your case a single character) to a variable in C. This is not directly supported by the language. You could however use your choice of associative array implementation, for which there are tons of choices--see here: Looking for a good hash table implementation in C

Or, since in your example you have only single-character variables (P,D,G,H), you could build a lookup table:

int P=0, D=0, G=0, H=0;
int* targets[256] = {};
targets['P'] = &P;
targets['D'] = &D;
targets['G'] = &G;
targets['H'] = &H;

for (size_t i = 0; i < strlen(s); i += 3) {
    assert(targets[s[i]]);
    (*targets[s[i]])++; /* if s[i] == 'P', increment P */
}
Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436