0

I have this code to substring the array src into 4 characters and save each substring into char dest[5]; array. It works fine. Now, I want to store every 4 characters into another format - unsigned int- %u in another array unsigned long k[4] ; I've been trying to store the formatted input in k using sprintf(), but it does not giving me the conversion of each element in array dest. So, I could have k[0] = dest[0], k[1]= dest[1], and so on!

        unsigned int k [4];
        char dest[5] ; // 4 chars + terminator */
        char src [] = "123456789abcdefg"
        int len = strlen(src);
        int b = 0;
        int bb=1;
        while (b*4 < len) {
            strncpy(dest, src+(b*4), 4);

            printf("loop %s\n",dest);

           sprintf(&k, "%u",dest);
            puts(k);                
            b++;

        }

I just got the solution,

unsigned long *k = (unsigned long *) dest;

Anyways, Thank you guys!!

1
  • I think an nested loop could help for (i=0;i <5;i++) k [i]=dest [i]; Commented Mar 20, 2015 at 17:37

2 Answers 2

1

sprintf() and puts() expect pointer to chars, k is a pointer to unsigned int array. proper casts should solve your problem

Sign up to request clarification or add additional context in comments.

Comments

1

You have a few errors. Here are my suggestions to fix them.

while (b*4 < len) {
    strncpy(dest, src+(b*4), 4);
    dest[4] = '\0';    // Make sure to null terminate dest

    printf("loop %s\n",dest);

    // Need sscanf, not sprintf
    // sprintf(&k, "%u",dest); 
    sscanf(dest, "%u", &k[b] );

    // Need printf, not puts, 
    // puts(k);
    printf("%u", k[b]);

    b++;

}

2 Comments

it is returning 0 values in every k elements.
I can see how you would get 0 in k[3] -- can't convert "defg" to a number but that shouldn't be the case for the other elements of k. See working code at ideone.com/AnZofC.

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.