-3

Just a basic program, written by a newbie. Supposed to read in values into a dynamic array, then print them out in reverse order. You can't input the size of array beforehand, the array's size will adjust as long as inputs aren't terminating characters.

I think I wrote it okay, but there are errors about dereferencing pointers and when I run it in VS, it won't even register inputs. When attempted in other compiler, it does register the input, but doesn't terminate with "-1".

Thinking about it, looking it up, I don't notice my mistake, hope you will help me.

Edit: thanks for pointing out the semicolon after while, but now it's a "Heap Corruption Error" after inputting 2 or 3 inputs. What went wrong?

int i=0;
    int *p, *a;
    int n=1;
    p = (int*)malloc(n * sizeof(int));
    printf("Enter integers here, and input -1 when done:\n");
    while (p[i] != -1);
    {
        scanf_s("%d", &p[i]);
        n = i + 1;
        a= (int*)malloc(n * sizeof(int));
        for (int j = 0; j < n; ++j)
        {
            a[j] = p[j];
        }
        free(p);
        p = NULL;
        p= (int*)malloc(n * sizeof(int));
        for (int k = 0; k < n; ++k)
        {
            p[k] = a[k];
        }
        free(a);
        a = NULL;
        ++i;
    }
    --i;
    if (i <= 0)
    {
        printf("%d", p[i]);
        --i;
    }
    free(p);
    p = NULL;

2 Answers2

4
while (p[i] != -1);

remove the trailing ;.

Also malloc gives you uninitialized memory, so chances are that the condition is not true at the first iteration. You probably want a do { ... } while(...); loop.

mch
  • 9,424
  • 2
  • 28
  • 42
3

Reformatting your code reveals the (or at least a) bug:

int i = 0;
int *p, *a;
int n = 1;
p = (int *)malloc(n * sizeof(int));
printf("Enter integers here, and input -1 when done:\n");
while (p[i] != -1)
  ;
{
  scanf_s("%d", &p[i]);
// ...

There's a stray semicolon after the first while, making it an infinite loop of nothing.

AKX
  • 152,115
  • 15
  • 115
  • 172