Search code examples
carraysstringgets

C Programming : gets() and Char String Array Issue - strcpy() copying into other strings in the Array


I am using the function gets() to retrieve string input from the user. I then store that string into a char array, char transdestmp[DESMAX], where DESMAX is 31. If the variable_name is greater than 30 chars, then ask the user to renter another string. Else, copy the string using strcpy(), into a 2 dimensional array char - acctdes[31][20].

accttitle recieves transdestmp[DESMAX]

void accttitle(char descr[DESMAX])
{
    printf("\nEnter title for new account %d: ", transinpt);
    gets(descr);
    while(strlen(descr)>DESMAX){
        printf(" **Title entered is longer than 30 characters\n");
        printf(" Please reenter : ");
        gets(descr);
    }
    strcpy(acctdes[transcntr],descr);
    printf("---->vacctdes[transcntr]: %s\n", acctdes[transcntr]);
    printf("---->vacctdes[transcntr-1]: %s\n", acctdes[transcntr-1]);
}

For some reason when I input a long string, and then enter another string, apart of the second string acctdes[1] overwrites the other string stored in acctdes[0].

for example,

First input: acctdes[0] = "This is a long string"

It works...

Second input acctdes[1] = "monkey"

It works...

but then, it seems that when I output acctdes[0], acctdes[0] has some of the value from acctdes[1]... like output - This is a long monk...

Please let me know if you would like more information. Thanks in advance.


Solution

  • You have the dimensions on your array reversed. Try acctdes[20][31].

    The reason the strings bleed into each other is because C lays out a two-dimensional array as one long block of memory. When you do acctdes[2] its really doing pointer arithmetic under the hood like *(acctdes + (31 * 2)) to skip over the first part of the memory block to get to your third element. So if one string writes past its bounds, it will end up in the next string.