-1

In the first for loop I am trying to add an offset to a char array and am not able to do so.

I also wanted input from the terminal so I wrote code that is a ** to argv[2] and used atoi() to convert a char from argv[1] to an int.

int main(int argc, char *argv[]) {

    if(argc != 3) {
        printf("Enter an integer followed by a string \n\n");
        return 1;
    }

int i;
int offset = atoi(argv[1]);
char **p_message;
p_message = &argv[2];
char encrypt[strlen(*p_message)];

printf("You Entered: %d, %s \n", offset, *p_message);

for(i = 0; i < strlen(*p_message); i++)
    {
        encrypt[i] = ((*p_message[i] + offset) % 26);
    }

for(i = 0; i < strlen(*p_message); i++)
{
    printf("%c", encrypt[i]);
}


return 0;

}
Anthony O
  • 622
  • 7
  • 26

1 Answers1

0

The main problem is that you are not making an alphabet adjustment before, and after, the modulus operation. I added the variable letter as an int so that the arithmetic won't overflow.

You could simplify the program by dropping one of the stars for **p_message. Also, you would normally allocate an array 1 longer than the string, to allow for a nul terminator, but here, you are not treating the char array as a string, so no need.

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

int main(int argc, char *argv[]) {

    if(argc != 3) {
        printf("Enter an integer followed by a string \n\n");
        return 1;
    }

    int i;
    int offset = atoi(argv[1]);
    char *p_message;                                        // remove a *
    p_message = argv[2];                                    // remove &
    char encrypt[strlen(p_message)];                        // remove *
    int letter;                                             // added 

    printf("You Entered: %d, %s \n", offset, p_message);    // remove *

    for(i = 0; i < strlen(p_message); i++) {                // remove *
        letter = p_message[i];                              // remove *
        if(letter >= 'a' && letter <= 'z') {                // if lower case
            letter = 'a' + ((letter - 'a') + offset) % 26;
        }
        else if(letter >= 'A' && letter <= 'Z') {           // if upper case
            letter = 'A' + ((letter - 'A') + offset) % 26;
        }
        encrypt[i] = letter;
    }

    for(i = 0; i < strlen(p_message); i++) {                // remove *
        printf("%c", encrypt[i]);
    }

return 0;
}
Weather Vane
  • 33,872
  • 7
  • 36
  • 56