Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cpp empty array declaration

Tags:

c++

Hello I have the following test code and I am confused about cpp.

  1. If you declare in library.h an array with an empty element clause .. what will the compiler pick? It does also not complain, I use Cygwin.

  2. In library.cpp I assign values to two elements, is the compiler assuming an array with one element and I write the second element outside the scope of the array?

library.h

#ifndef LIBRARY_H
#define LIBRARY_H

class library {

public:
    void print();
    char a[];
};

#endif

library.cpp

#include <stdio.h>
#include "library.h"

void library::print() {
    a[0] = 'a';
    printf("1. element: %d\n", a[0]);
    a[1] = 'b';
    printf("2. element: %d\n", a[1]);
}

client.cpp

#include <stdio.h>
#include "library.h"

void execute();
library l;

int main() {
    l = library();
    l.print();
    return 0;
}

Makefile

OPTIONS=-Wall

all: main

run: main
        ./main.exe

main: client.o library.o
        g++ $(OPTIONS) -o main $^

library.o: library.cpp library.h
        g++ $(OPTIONS) -c $<

.cpp.o:
        g++ $(OPTIONS) -c $<

clean:
        rm -r *.o
like image 254
user2050516 Avatar asked Mar 19 '13 08:03

user2050516


1 Answers

  1. There is no language called C/C++, So your Q cannot be tagged with both.
  2. Since you are using classes, Your program can only be C++ and not C.

public:
     void print();
     char a[];

This code is simply illegal in C++. Array size in C++ needs to be positive compile time constant. Solution is to replace it by:

public:
      void print();
      std::string a;

Note that the declaration,

char a[];

is valid in c99 and it is known as Incomplete array type, the C standard guarantees that a can store atleast one element of the type char. This is not valid in C++. C++ standard does not allow these. Simply because both are different languages.

like image 101
Alok Save Avatar answered Oct 29 '22 14:10

Alok Save