3

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) which accepts a position int as parameter and prints the String at that position (e.g valueof(1,3) prints 000 and valueof(109,3) prints k10

This is what I tried and it is not working:

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
  • 2
    How is it not working? For example, if we call valueOf(109, 3) what currently is reported? Commented Oct 1, 2014 at 17:02
  • Read about snprintf(3) & strdup(3) and perhaps (on Linux) asprintf(3) Commented Oct 1, 2014 at 17:11
  • 1
    @BasileStarynkevitch: I'm not sure that's helpful here. Commented Oct 1, 2014 at 17:12

2 Answers 2

5

So, pos % 62 returns a number between [0, 61]. So when you do (pos%62)-1, you get a number between [-1, 60]. Which you likely don't want.

You should probably rewrite this line:

string[i]=arry[(pos%62)-1];

as:

string[i] = arry[pos % 62];
Sign up to request clarification or add additional context in comments.

Comments

2

Here's a test harness. I would add some bounds checking to the input otherwise you can overrun 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.