Dave
Dave

Reputation: 421

Trouble with pointers in C and using them in functions

I basically wrote a simple Caesar cipher program (simply shifting characters in ASCII with hardcoded key 12) but I am new to C so having trouble with pointers and accepting char arrays as input and returning them as output.

Here is what I got so far. Can you help me figure out what is wrong?

Thanks in advance.

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

int main() {

    char hello[50][50] = {{'h','e','l','l','o'}, {'h','r','u','\0'}};
    hello = encrypt(hello);

    printf("%s", hello[50][50]);

}

char** encrypt(char text[50][50]) {
    int i,j;
    for(i=0; i<50; i++) {
        for(j=0; j<50; j++) {
            if (text[i][j]!='\0') {
                text[i][j] = (char)((int)text[i][j]+12)%256;
            } else {
                break;
            }
        }
    }
    return text[50][50];

}

char** decrypt(char text[50][50]) {
    int i,j;
    for(i=0; i<50; i++) {
        for(j=0; j<50; j++) {
            if (text[i]!='\0') {
                text[i][j] = (char)((int)text[i][j]-12)%256;
            } else {
                break;
            }
        }
    }
    return text[50][50];
}

Upvotes: 1

Views: 490

Answers (2)

Martin Beckett
Martin Beckett

Reputation: 96139

Your main problem seems to be understanding what hello[50][50] means

In char hello[50][50] it allocates 50 sets of 50 character blocks. But on it's own hello[50][50] refers to a single character, to 51st position in the 51st b lock - since C counts form 0 your blocks are number [0] to [49] so [50] isn't valid.

Passing 2 dimensional arrays to C isn't done how you think it is.

I would recommend using a 1 dimensional array as a long string with the words simply broken by spaces - this will be a lot clearer and easier to understand.

If you allocate a 1d array as char hello[50]; You can pass it to a function as func(char hello[]) or func(char *hello) and still use the hello[i] notation inside the function

Upvotes: 1

shenles
shenles

Reputation: 582

Your code that is performing the cipher has a bit of an issue in some cases. You are adding 12 to the value of the character, then performing a mod 256. If you passed in a higher value letter, it would not do what you were hoping.

Example:

('A' + 12) % 256 => (65 + 12) % 256 = 77 => 'M' // This works as expected

('X' + 12) % 256 => (88 + 12) % 255 = 100 => 'd' // This should have been 'J'

The solution is to modify the function to make sure it wraps correctly. Since your example only uses lower-case letters, I will only cover that case.

text[i][j] = (((text[i][j] - 'a') + 12) % 26) + 'a';

Upvotes: 0

Related Questions