C - Getting a string from an int
I have a list of all strings of a given length in the format
e.g. length 3
000 100 200 . . 900 A00 B00 . . Z00 a00 b00 . . z00 010 . . . zzz
I am trying to write valueof(int pos, int len)
that takes an int position as a parameter and prints the string at that position (for example, valueof(1,3)
prints 000
and valueof(109,3)
printsk10
This is what I tried and it doesn't work:
void valueof(int pos,int len)
{
int i=0;
char arry[62] = {'0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char * string = malloc(sizeof(char)*(len+1));
for(i=0; i<len; i++)
{
string[i]='0';
}
string[len]='\0';
i=0;
while(pos >= 62)
{
string[i]=arry[(pos%62)-1];
i++;
pos/=62;
}
string[i]=arry[pos];
printf("%s\n",string);
}
+3
source to share
2 answers
Here is the test harness. I would add some bounds checks to the input, otherwise you can intercept the array.
#include <stdio.h>
#include <stdlib.h>
void valueof(int pos,int len)
...
int main (int argc, char **argv) {
valueof(atoi(argv[1]), atoi(argv[2]));
}
To compile gcc vo.c -o vo
./vo 1 3 000 ./vo 109 3 k10
+2
source to share