-1

I am new to C programing. I tried to get the following code work but fails.

#include <iostream>
#include <string>
#include <stdlib.h>
#include <stack>
using namespace std;

int main()
{

  string* ps = (string*) malloc(9*sizeof(string));
  ps[0] = "jasdhk";
  ps[1] ="rty";
  ps[2] = "tyu";
  return 0;
}

Any Suggestions ?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
  • This is *c++* and *not* c. – rootkea Jan 08 '16 at 09:15
  • For one thing, this is a really nasty mix of C and C++. That said, let's suppose this really is what you wanted to do. How is it failing? The real answer is of course, for dynamic arrays in C++, use [`std::vector`](http://en.cppreference.com/w/cpp/container/vector). – BoBTFish Jan 08 '16 at 09:15
  • 1
    use `vector` instead of. – BLUEPIXY Jan 08 '16 at 09:16
  • @BoBTFish: It is C-syle C++, but not a mix (that would imply it compiles with a C compiler). – too honest for this site Jan 08 '16 at 09:16
  • Learn [ask] and take the [tour]. Then learn which language you are actually using. C and C++ are **different** languages! – too honest for this site Jan 08 '16 at 09:17
  • @Olaf Is `` guaranteed to be present in C++? I thought not. Making it not quite C++, definitely not C. – BoBTFish Jan 08 '16 at 09:18
  • @BoBTFish: You can use C libraries in C++ if they are augmented properly (`extern "C" ...`. Anyway, I think we agree this is rubbish code. – too honest for this site Jan 08 '16 at 09:19
  • 1
    or `string* ps = new string[9];` instead of. – BLUEPIXY Jan 08 '16 at 09:22
  • You need to get yourself either a [C book](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) or a [C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), depending on which language you're actually going to learn. – molbdnilo Jan 08 '16 at 09:55

1 Answers1

4

The code is actually a hybrid of C and C++, and is not valid in either language.

The usage of C++ headers (iostream, string, and stack) is not valid in C. Similarly, using namespace std is C++, not C.

The usage of C's malloc() to allocate a C++ type with constructor is invalid, since C library functions do not invoke constructors for C++ objects. std::string (which is what the name string resolves to, thanks to usage of <string> and using namespace std in this case) is a (typedef for a specialiation of a) C++ template class with a constructor.

Either abandon malloc() and use operator new to dynamically allocate C++ objects or, better, use std::vector<std::string> to dynamically manage a collection of std::string.

Peter
  • 35,646
  • 4
  • 32
  • 74