0

I am trying to implement a columnar transposition cipher in C and was doing the encryption part but I am facing an issue with the 2d part you can see in the output image.

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

int main()
{
int arr[10];
int key;
printf("Enter size of key: ");
scanf("%d",&key);

for (int i = 0; i < key; i++)
{
    printf("Enter the value of key at pos %d: ",i+1);
    scanf("%d",&arr[i]);
}

printf("key is: ");
for (int i = 0; i < key; i++)
{
    printf("%d",arr[i]);
}

printf("\n");
char msg[20];
printf("Enter your msg: ");
fflush(stdin);
scanf("%s",&msg);
printf("message is : %s\n",msg);

int msg_len = strlen(msg),row;
printf("Enter number of rows: ");
scanf("%d",&row);
printf("msg size: %d\n",msg_len);
char rect[row][msg_len];

for (int j = 0; j < row; j++)
{
    for (int k = 0; k < msg_len; k++)
    {
        rect[j][k]=msg[k];
        //rect[row][msg_len]='\0';
    }
    
}
rect[row][msg_len]='\0';
printf("%s",rect);

return 0;

This is the o/p I am getting

Expected output is : stackoverflow

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
TechM
  • 1
  • 2
  • 1
    This: `rect[row][msg_len]='\0';` should be `rect[j][msg_len-1]='\0';` , and should be inside the out loop above, but just after the nested `i` loop. Notable:`strlen(msg),row;` is *not* doing what you think it is, and should be issuing compiler warnings saying as much, and `char rect[row][msg_len];` is near assuredly undersized in the inferior dimension by 1. Also, I don't know what rubbish reference told you to use `fflush(stdin);`, but whatever it was, it's wrong. – WhozCraig Feb 10 '22 at 17:54
  • oh about flush(stdin); i was using gets0 thats why i used it and then forgot to remove it. – TechM Feb 10 '22 at 18:01
  • 2
    See [this question](https://stackoverflow.com/q/2979209/12149471) on why not to use `fflush(stdin)`. – Andreas Wenzel Feb 10 '22 at 18:02
  • 1
    Don't use images of plain text — embed the plain text in the question, with one line containing `\`\`\`none` before it and one line containing just `\`\`\`` after it. – Jonathan Leffler Feb 10 '22 at 18:04

0 Answers0