简体   繁体   中英

adding a 0 char after every even number in an array C

I'm trying to create a program in C which, after every even number, will add a "0". But I have a problem. If I insert for example only even numbers (5 or more numbers) the program crashes.

Below is the program I have right now.

I would like some indications or a code sample to point out what I did wrong and how I can fix it.

void main()
{
    int *a, i, n, m;
    printf("dimensiune=");
    scanf_s("%d", &n);
    a = (int*)malloc(n*sizeof(int));
    for (i = 0; i < n; i++)
    {
        printf("a[%d]=", i + 1);
        scanf_s("%d", &a[i]);
    }
    for (i = 0; i < n; i++)
    {
        if (a[i] % 2 == 0)
        {
            n++;                                        
            a = (int*)realloc(a, n*sizeof(int));        
            for (m = n - 1; m > i;m--)                  
            {       
                a[m + 1] = a[m];                        
            }
            a[i + 1] = 0;                               
            i++;                                        
        }
    }
    printf("\n currently you have %d numbers in this string\n", n);

    printf("your string \n");

    for (i = 0; i < n; i++)
    {
        printf("a[%d]=%d\n", i + 1, a[i]);
    }
}

Change:

for (m = n - 1; m > i;m--)                  
    {       
    a[m + 1] = a[m];                        
    }

to:

for (m = n - 1; m > i;m--)                  
    {       
    a[m] = a[m-1];                        
    }

I've just tested it, it's working for me, should work for you.

I see a problem with this loop:

    for (m = n - 1; m > i;m--)                  
    {       
        a[m + 1] = a[m];                        
    }

When you start the loop, n is the number of element in the loop. During the first iteration, m is the index of the last element of the loop. So, m+1 is after the last element, creating a buffer overflow.

感谢所有评论,我解决了用int main(void)替换void main()和Shady Programmer提供的解决方案的错误。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM