0

Not sure what i'm doing wrong here. I'm trying to circularly shift elements of a char array left by one. It seems to work, but not persist. I assume it's a pointer issue, but I still don't get how pointers work so i'm not sure where to begin. Problem is, it only seems to change the value inside the for loop and reset afterwards.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void ip();

int main(){
    char d[10] = "010";
    char k[10] = "1010000010";
    initialPermutation(d, k);
    return(0);
}

void ip(char * data, char* key){
    int i;

    // P10(k1, k2, k3, k4, k5, k6, k7, k8, k9, k10) = (k3, k5, k2, k7, k4, k10, k1, k9, k8, k6)
    char P10[10] = {key[2],key[4],key[1],key[6],key[3],key[9],key[0],key[8],key[7],key[6]};

    // split P10 into two segments
    char left5[5] = {P10[0],P10[1],P10[2],P10[3],P10[4]};
    char right5[5] = {P10[5],P10[6],P10[7],P10[8],P10[9]};

    // pre shift binary string
    printf("Pre-shift: ");
    for(i=0;i<5;i++)
        printf("%c",left5[i]);
    for(i=0;i<5;i++)
        printf("%c",right5[i]);
    printf("\n");

    // circular shift left one bit (here is where the problem is)
    for(i=0;i<5;i++){
        char templ = left5[4-i];    
        left5[4-i] = left5[i];   
        left5[i] = templ;

        char tempr = right5[4-i];
        right5[4-i] = right5[i];
        right5[i] = tempr;
     }



    printf("Post- (outside for loop): ");

    for(i=0;i<5;i++)
        printf("%c",left5[i]);
    for(i=0;i<5;i++)
        printf("%c",right5[i]);
    printf("\n");
}
1
  • "1010000010" has 11 characters if count the null terminator so the string is not null terminated in initialization of char k[10] Commented Feb 9, 2014 at 22:14

1 Answer 1

1

Your loop is not shifting values, it is reversing the array twice. It swaps index 0 with index 4, then 1 with 3, then 2 with 2, then 3 with 1, and finally 4 with 0. At this point the array is exactly as when you started.

This code does an actual rotary left shift:

char tmp = left5[0];
for(i = 1; i < sizeof(left5); ++i){
    left5[i-1] = left5[i]
}
left5[4] = tmp;

If you actually declare the arrays one element too large you can write:

char left5[6] = {P10[0],P10[1],P10[2],P10[3],P10[4]};
left5[5] = left5[0]
for(i=0; i < 5; ++i){
    left5[i] = left5[i+1];
}
Sign up to request clarification or add additional context in comments.

1 Comment

That was the problem. Thanks

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.