nitin1 15 Master Poster
#include<iostream>

using namespace std;

class Singleton {

static Singleton * s;
    Singleton() {

    }

public:

    ~Singleton() {
        s = NULL;
    }
    static Singleton * getInstance();
    void print() {
        cout<<this<<endl;
    }
};

Singleton* Singleton::s=NULL;
Singleton* Singleton::getInstance() {

        if(s == NULL) {
            s = new Singleton();
        }
        return s;
}


int main()
{
    Singleton * s = Singleton::getInstance();
    s->print();
    Singleton * s2 = Singleton::getInstance();
    s2->print();
    return 0;
}

Singleton* Singleton::s=NULL;
(line 23)

When I am not putting this line, it is saying that undefined reference to 's'. By default static members are NULL only. then why does it need me to put this line? Please explain. Thanks a lot in advance.

nitin1 15 Master Poster

@James Sir, You know my answer. :)

nitin1 15 Master Poster

@rubberman, you told me about vijayan121 code. I want to discuss about the code which I posted in the beginning only. That is fine which you told me for Vijayan's code. Please discuss about my code also.

nitin1 15 Master Poster

@rubberman, so what's the problem with my code? How can I correct my code? I got whatever you said in the post. Can you mark the points where my program might be going wrong which is resulting in wrong answers for some cases? Thanks

nitin1 15 Master Poster
#include<iostream>

using namespace std;

int add(int x,int y)
{
    int ans=0;
    int carry=0;

    for(int i=0;i<=31;i++)
    {
        int p = (1<<i)&x;
        int q = (1<<i)&y;

        int r = p ^ q;
        r = r^(carry<<i);

        ans = r | ans;

        if(p&q || p&(carry<<i) || q&(carry<<i))
            carry = 1;
        else
            carry =0;

    }

    return (ans);
}

int main()
{
    int x,y;

    x=-2;y=6;
//add(4,6);
    cout<<endl<<add(x,y)<<endl;

   return 0;
}

Actually, I am trying to add bit by bit. When number is negative, it is represented by 2's compliment. But, here I am using the 32th leftmost bit. Isn't it wrong?

It is giving corrent for small numbers but for large numbers like (-2222222,6) giving wrong answer. Can anyone explain why?

Thanks a lot in advance.

nitin1 15 Master Poster

I have come across one question:

find the size of two 2-D arrays when double pointers are given for them.Then find, if we can muliply these two matrices(those mathematics rules). finally we have to multiply the matrices.

I have asked this question(small part of this question) earlier also. someone answered that it is not possible to get the size like this. I aksed for the single-D array. I know same would be applied for the 2D arrays also. but, what might he be expecting from the person who is going to answer this? How can we find the sizes using double pointers passed to one function? Thanks in advance.

P.S This is not a homework. I don't want any code or link. I know how to multiply matrices and maths behind all this. :)

nitin1 15 Master Poster

Why can we virtual destructors but can't have virtual constructors? I have searched like anything. I got confused a lot after reading few articles on web. Please explain with some good example. Thanks in advance.

nitin1 15 Master Poster

I am working on a project and I need one CmakeList.txt file, Config file, spec file. I searched a lot. tutorials are telling how to make these files and all. Please tell me from scratch what they are and what is the use of these files? Please provide links also where I can learn about these files. Any help would be appreciated. Thanks in advance.

nitin1 15 Master Poster

SO, accessing non-constant global variables makes the function non-rentrant? Can I say that? If yes, then in your second example, it is accessing a variable which is global but non-const. Please clarify this also.

Secondly, malloc() is a function in C. How will you explain re-entrancy and thread-safe using malloc()? Can malloc be thread-safe or re-entrant? Actually, I want to know how malloc() will react when ut would be called by many threads at the more or less same time?

nitin1 15 Master Poster

@rubberman, :p I am not a school guy now. :) I thought of hashmaps. I don't know how to use them in this case as I want O(1), so hashmap is the good way but dont know how to use them. If you can help anyway, that would be good. Actually, somebody asked me this question long back but now I want how to solve this one.

I dont want any code or like that. I want algorithm or some hints or some source where I can start from.

P.S In my school, college, even company they dont expect me to solve this type of problems. :-D

nitin1 15 Master Poster

This problem is troubling me from so long time.
There are N scientists, K black holes, and any scientist can query about radius, size and temperature of any blackhole.

You have to answer three kinds of query basically:

1)Given Scientist queried for which blackholes,Given scientist queried for which attributes
2) Given blackhole, who all scientist had quaried on it, which attributes of it had been queried upon
3) Given attribute which scientist has queried upon it and which blackhole has it been queried upon
All should be in O(1) time complexity.

Which data structure will you use for this?

nitin1 15 Master Poster

@mike Thanks for such a great answer. But, I want to ask one question in "thread-safe but not reentrant" example , that when it is not giving me correct behaviour in multi-threaded environment, then how you can say that it is still thread-safe?

Please explain when you said "has a well-defined outcome (which is not necessarily the "desired" outcome, but a well-defined outcome nonetheless)." in your last post. I mean if it is not gviging correct answer, then how it is still thread-safe?

Thirdly, you said, reentrant are functions when they're not using global variables and all. but in all your example, you make functions which are using global variables things. Please clarify once. Thanks in advance Mike.

nitin1 15 Master Poster

BAsically, I was asked to decrease the complexity of the first code from O(n). Then I wrote second. Then he told me decrease it further from O(n/2).Then, I wrote third and he didn't say anything.

Was I correct at that time as he told me to decrease the complexity?
Secondly, in the link also, it is written that manually we can unroll it. So, why are you saying first is still fastest according to you? Thanks Sir James.

nitin1 15 Master Poster
int find(int x)
    {
          for(int i=0;i < n; i++)
          {
                  if(a[i]==x)
                     return i;
          }

          return -1;
    }


int find(int x)
{
          for(int i=0;i < n/2; i+=2)
          {
                  if(a[i]==x)
                     return i;

                     if(i+1 < n && a[i+1]==x) 
                     return i+1;
          }

          return -1;
}



int find(int x)
{
          for(int i=0;i < n/3; i+=3)
          {
                  if(a[i]==x)
                     return i;

                     if(i+1 < n && a[i+1]==x)return i+1;
                     if(i+2<n && a[i+2]==x)return i+2;
          }

          return -1;
}

Which is faster and why? Also, what if I increase the k in n/k in the loop ? Will it make it more faster or slower? What is concept behind this? Thanks in advance.

nitin1 15 Master Poster

@Mike, Thanks for this great answer. Really. Can you please give one example to tell that it is thread-safe but not reentrant, which is not thread-safe but reentrant? I am clear after your post but want to make it clearer with a simple example. Please mike. Thanks a lot in advance.

nitin1 15 Master Poster

I am damn confused between these two terms. Can anyone explain this using some example? Thanks in advance.

nitin1 15 Master Poster

@Maritimo I think you are wrong in your explanation when you are making my statement corerct. I think statement written by me was correct. How comes 4Gb thing? Please explain.

nitin1 15 Master Poster

With a 2^32 address space and 4K ( 2^12 ) page sizes, this leave 2^20 entries in the page table. At 4 bytes per entry, this amounts to a 4 MB page table, which is too large to reasonably keep in contiguous memory. ( And to swap in and out of memory with each process switch. ) Note that with 4K pages, this would take 1024 pages just to hold the page table!

Please explain me how they are calculating 1024 pages at the end? what is 4bytes per entry in this? Thanks in advance.

nitin1 15 Master Poster

I am very confused with static functions. Can I override them? If no, then why? I searched web a lot but i am still not clear. Please tell with one example if possible. Thanks a lot.

nitin1 15 Master Poster

Please tell me the difference between these three. I know the basic meaning but don't know exact meaning of all of them. Please explain a very good example if possible. Thanks in advance.

nitin1 15 Master Poster

Yeah. That is true. But I want some small apps which use all these things and I have told you that I have read about all these things and developed examples based on them. I want to start one app in which I can use all these things and can improve myself. That's my aim.

nitin1 15 Master Poster

I have learnt basic android in the last month. I have learnt about fragments, listview, adapters, acitivties, intents, content providers, databases, animations. I want some basic apps' ideas in which I can implement these things and can improve my learning? I am not too good in Java also. I know C/C++ at advanced level. Some good apps example where I can have mixture of many things and app should have some sense, obviously. Thanks in advance.

nitin1 15 Master Poster

@mike, now Can I say that a library is an API? Basically, API is a set of functions/classes which you showcase to users for their use. Library includes many headers including private and public headers. Still, Can I say that a library is an API for the programmers?

nitin1 15 Master Poster

@mike Hats off to you. Great answer. One , the length of your answer, secondly your way of explanation. +1. :)

nitin1 15 Master Poster

Yup. Thanks. It helped. :) Love you Daniweb.

nitin1 15 Master Poster

Thanks. But, can you explain it with my example. It is my first code in Java. I dnt have much idea about Java.

nitin1 15 Master Poster
/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

class Test{
   public static void main(String args[]){
      String Str = new String("WelcometoTutorialspoint.com-");
      int i=0;

      System.out.println("Return Value :" );
      for (String retval: Str.split("-", 2)){
         System.out.println(retval);
         System.out.println(i);
         i++;
      }
      i=0;

      System.out.println("");
      System.out.println("Return Value :" );
      for (String retval: Str.split("-", 3)){
         System.out.println(retval);
          System.out.println(i);
         i++;
      }

      i=0;
      System.out.println("");
      System.out.println("Return Value :" );
      for (String retval: Str.split("-", 0)){
         System.out.println(retval);
          System.out.println(i);
         i++;
      }
      System.out.println("");
      i=0;

      System.out.println("Return Value :" );
      for (String retval: Str.split("-")){
         System.out.println(retval);
          System.out.println(i);
         i++;
      }
   }
}

In this, my delimiter is at the end. In last two cases , loop is running only for 1 time but in first 2 cases it is running for 2 times each. Why is it so??

Secondly, what is the measning of passing value zero to the second field of spilt function? Thanks.

nitin1 15 Master Poster

{"title":"iamtitle","icon":"","urlHistory":["http://google.com"],"lastUsed":123}

I have tried in c++ and using json-glib. I have tried using this:

                g_type_init();

                JsonParser *parser = json_parser_new();
                json_parser_load_from_data(parser, temp.c_str(), -1, NULL);

                JsonReader *reader = json_reader_new(json_parser_get_root(parser));

                json_reader_read_member(reader,"urlHistory");
                JsonNode * value = json_reader_get_value(reader);
                JsonArray * value1 = json_node_get_array(value);
                const char * urlhistory = json_array_get_string_element(value1,0);
                tab.history = urlhistory;
                json_reader_end_element(reader);
                cout << endl << "correct URL-->: " << tab.history << endl;

                json_reader_read_member(reader, "title");
                const char * title = json_reader_get_string_value(reader);
                json_reader_end_member(reader);
                tab.title = string(title);

                json_reader_read_member(reader, "lastUsed");
                int lastUsed = json_reader_get_int_value(reader);
                json_reader_end_member(reader);

                tab.lastUsed = lastUsed * 1000L;

                json_reader_read_member(reader, "icon");
                gboolean checker = json_reader_get_null_value(reader);
                const char * icon = "";

                if (!checker) {
                    cout << "I am not null in icon tabs" << endl;
                    icon = json_reader_get_string_value(reader);
                    tab.icon = icon;
                    json_reader_end_member(reader);
                } else {
                    cout << "I am in icon null" << endl;
                    tab.icon = "";
                    json_reader_end_member(reader);
                }

                g_object_unref(reader);
                g_object_unref(parser);

It is giving error whiel reading urlhistory. Please tell why it is. I am able to get the nomrla string values but don't know how I can take values like arrays from json like this. Please tell. Thanks.

nitin1 15 Master Poster

@mike. Thanks mike. but please tell me this thing that I have one string say :

"nitinkdjdhdgshs/djjkdkd"

mark that slash in it. Now when I add it into json string then it should be like this:

"cipher": "nitinkdjdhdgshs\/djjkdkd"

then: when i put that again in one json string, it should be like this:

"payload" : {"cipher": "nitinkdjdhdgshs\\/djjkdkd"}

Is it correct as per the json-glib? How should I achieve this?

nitin1 15 Master Poster

Does C++ consider \/ as an escape character?
And does Java consider it? I am talking about forward and backslashes. Please tell. How does Java and C++ considers them differently? I mean :

in C++: this '/' works fine without escape.
in Java: this '\/' will result in '/'.

Is it correct or wrong?

Please clarify.

nitin1 15 Master Poster

I know there is validator. But I want to know it is the correct json that should be made from that data. I am confused about those slashes. How they are added by Json and how they are removed.Please explain little bit.

nitin1 15 Master Poster

I am creating one json array using Json-glib using c++. Here is the data:

title="Daniweb"         (string)
last= 1234              (long)
icon="icons"            (string)
url = "[\"dani.com\"]"   (json array)

After making one json array using exsiting APIs of json-glib library, I got this:

{"id":"Nitin1","clientName":"Gourav_first_task","tabs":"[{\"title\":\"Daniweb\",\"icon\":\"icons\",\"urlHistory\":\"[\\\"Dani.com\\\"]\",\"lastUsed\":1234}]"}

Is it the correct json string made? It has added those escape characters to it. I have declared those variables like that only which I have written above and got json as given. Please tell is it the correct json made out of it? Thanks.

nitin1 15 Master Poster

But the way I am doing is correct or not?

nitin1 15 Master Poster

array is a pre-defined class in a library. What can I do for that? thanks.

nitin1 15 Master Poster

bytearray is this:

typedef array<byte> bytearray;

and byte is this:

typedef uint8_t byte;

Now, please tell. "array" is just a class which show a array of something; basically a template for array of some type.

nitin1 15 Master Poster

Can anyone give me an idea how to do this? I have a list(C++) of bytearray and I want to fire a post request to the server using CURL library?
I have searched a lot and they say to set the CURL_POSTFIELDS but that requires a char * field. I need to send a list of bytearrays.
Please help. Thanks.

nitin1 15 Master Poster
void func(void * ptr)
{
          bytearray temp(10);
          *((bytearray*) ptr ) = temp; 
}

This code is not going ahead if the third line while executing while this coding is working fine.

void func(void * ptr)
{
        const char * temp = "decept";
        *((char*)ptr) = temp[0];
}

Why is it happening? First code is kind of "hanged" at the assigning line. It is not going ahead as Working on eclipse. Please tell how I can solve the problem and why it is happening. Thanks.

nitin1 15 Master Poster

I am using Eclipse and there is one strange error coming while building. In files, it is not showing any error but when I build it, it says

**Description Resource Path Location Type
Program "g++ -std=c++0x" not found in PATH test [Discovery Options] page in project properties C/C++ Problem
**

I am not getting how to solve this problem. Please help. Any help would be appreciated. Thanks.

nitin1 15 Master Poster

@moschops That's ok. This might be typo nothing else.

If I have to use Instance of B in A.h rather than pointer then? I know we cant define any instance for the forward declaration, but what is the solution in that case? Thanks.

nitin1 15 Master Poster

Today, I faced very weird problem. I have 2 classes say class A and B. Both have one .h and .cpp files. 4 files(A.cpp,B.cpp,A.h,B.h). A class is base class of B and we are using instance of B in class A. It was saying "not a type" error while compiling. How can I solve the error? Google was saying "it is a kind of cyclic dependency" in the code that's why it was giving error. Please help. Thanks.

nitin1 15 Master Poster

I am using LINUX system 64 bit OS for this purpose.

nitin1 15 Master Poster

For my project, I need to learn multithreading in C++. I have read 4-5 articles on Google, and have searched for more but they all are more or less similar. I want to learn it in depth. Can you provide me some links/source/anything for learning mutilthreading in C++? I am clear with the basics and want to explore more.

All links have how to create thread, how to wait for threads to complete, how to syncronize but they just have the overview. I want some explanations with examples and in detail.

Any help would be appreciated. Thanks.

nitin1 15 Master Poster

Hehe. You calling me sir. :-p I can't be your sir in this generation. :)

I think double representation in binary is compilcated. When I will add them, it might truncate some digits in binary representation of the resultant answer. And, when I will again substract the number, that might now give me the exact number which I expect.

For 6.13425 , it might give 6.13426 or like that. I am not sure with my explanation, but now want you to make me correct if I am wrong sir!. :)

nitin1 15 Master Poster

Firstly, In case, if I write all the implementations directly in the header and use it in my project. for example, if I write the <stdio.h> in all my files and if standard committee decides to change thing, then my source would be intact, just I need to change the header file as defintions are there in it only. right? So, why are we dividing the thing in headers(declarations) & cpp (defintions) ? We can write defintions in headers also.

Secondly, In your example, as printf defintions is changed, then we need to change all the usages of the printf() also as you do. In that case also, my code will crash because I am using the old format only. If we can change all the lines where printf is used so as to make our code compatiable, then we can change the declartion also. what's the major use? Thanks.

nitin1 15 Master Poster

@James sir,

You catch it. I have also thought the same when he said "number". The solution I gave will work for the int surely but it might give wrong for the double. Am I right? Thanks.

nitin1 15 Master Poster

Actually, I am confused that what the problem was there in C and how c++ has solved it. Having namespace solves our problem by resolving the names.

For ex: if I say 'string' that means diffferent if I say std::string. Right? Here, names are resolved because everything is defined in std namespace? So is this what you are telling?

Headers has just the declarations as I already know. namespaces include all the definitons? right? Please make me correct if I am wrong at any place. Thanks a lot, James Sir.

nitin1 15 Master Poster

I have updated my comment. I have added one problem in the last comment. Please see that also.

Secondly, why don't we have namespce thing in C? Why do we need it in C++? When namespaces are resolved in the cycle of compilation to execution? Thanks.

nitin1 15 Master Poster

but how is it resolved by compiler that which function to call? Who resolves this thing from the code compilation to source execution cycle? Thanks.

nitin1 15 Master Poster

But, when I use using namespace std, then I also have to use "string" header file. So what is the difference between them?

If everything is defined in namespace, then we need header and cpp files? Can you please clear the difference between all of them?

Also,
I have written this temporary code which as one error:

#include<iostream>
#include<cstring>

using namespace std;

namespace  temp
{
           class string
           {
                 public:
                        void foo()
                        {
                             std::cout<<"hello in namespace foo()"<<std::endl;
                        }
           };
}

int main()
{
       temp::string str;
       std::string g ="string.h wala string";

       std::cout<<g.find("wala")<<std::endl;
       std::cout<<str.foo()<<std::endl;

    system("pause");

}

it is showing one error on second last line. Why is it not working? It says

24 C:\Users\gourav.si\Desktop\beecrypt-4.2.1\Untitled1.cpp no match for 'operator<<' in 'std::cout << (&str)->temp::string::foo()' 

Thanks.

nitin1 15 Master Poster
#include <iostream>
using namespace std;

class Time
{
   private:
      int hours;             // 0 to 23
      int minutes;           // 0 to 59
   public:
      // required constructors
      Time(){
         hours = 0;
         minutes = 0;
      }
      Time(int h, int m){
         hours = h;
         minutes = m;
      }
      // method to display time
      void displayTime()
      {
         cout << "H: " << hours << " M:" << minutes <<endl;
      }
      // overloaded prefix ++ operator
      Time operator++ ()  
      {
         ++minutes;          // increment this object
         if(minutes >= 60)  
         {
            ++hours;
            minutes -= 60;
         }
         return Time(hours, minutes);
      }
      // overloaded postfix ++ operator
      Time operator++( int)         
      {
         // save the orignal value
         Time T(hours, minutes);
         // increment this object
         ++minutes;                    
         if(minutes >= 60)
         {
            ++hours;
            minutes -= 60;
         }
         // return old original value
         return T; 
      }
};
int main()
{
   Time T1(11, 59), T2(10,40);

   ++T1;                    // increment T1
   T1.displayTime();        // display T1
   ++T1;                    // increment T1 again
   T1.displayTime();        // display T1

   T2++;                    // increment T2
   T2.displayTime();        // display T2
   T2++;                    // increment T2 again
   T2.displayTime();        // display T2

   system("pause");
   return 0;
}

Why does it need int in postfix and not in prefix? .I don't know why? I know when I do :

int a =1;
a++;

Then, it wants a as the parameter to increment it. But why is it taking in one case and not in other case? How compiler is passing the T1 argument to that overloaded function to increment the T1? Please explain. Thanks.