mbae059
mbae059

Reputation: 9

Dynamic Memory Allocation acting weird

I just found out that I can't write code like this

#include <iostream>

using namespace std;

int main() 
{
  int* a, b;
  int N;
  cin >> N;

  a = new int[N];
  b = new int[N];
}

But I can't understand why:

  int*a, b;

is wrong, What is b's type?

Upvotes: 0

Views: 89

Answers (2)

Ashhar Shah
Ashhar Shah

Reputation: 94

This is because of the first line:

  int* a, b; 

It declared "a" as a pointer variable and "b" as an integer so you can write this in two ways:

  int* a, *b;

OR

  int* a;
  int* b;

Upvotes: 0

Mestkon
Mestkon

Reputation: 4071

To put my comment as an answer:

bs type is int, not int* as you expect. That is a good reason to not declare several variables on the same line. The correct way to do it on a single line is int *a, *b;

If you want to know more, the rules are listed here. In your example int is in the decl-specifier-seq category and *a, *b is in the init-declarator-list category.

The best is of course to initialize your variables as you declare them to avoid potential bugs:

int main() {
    int N = 0;
    std::cin >> N;
    int* a = new int[N];
    int* b = new int[N];

    //dont forget to delete
    delete[] a;
    delete[] b;
    return 0;
}

Upvotes: 3

Related Questions