AliDeV
AliDeV

Reputation: 213

How to store formatted data to array in C?

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!!

Upvotes: 0

Views: 93

Answers (2)

R Sahu
R Sahu

Reputation: 206667

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++;

}

Upvotes: 1

user3469811
user3469811

Reputation: 678

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

Upvotes: 1

Related Questions