pdk123 15 Light Poster

Thankyou for the reply and help. Btw, i already got this working.

#include <iostream>
#include "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\include\Python.h"
#include "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\Lib\site-packages\numpy\core\include\numpy\arrayobject.h"
#include <vector>
using namespace std;

int main(int)
{

    Py_Initialize();//-Initialize python interpreter
    if (!Py_IsInitialized())
    {
        PyRun_SimpleString("print 'inital error!' ");
        return -1;
    }
    import_array();
    //PyRun_SimpleString("print 'inital ok! ");
    PyRun_SimpleString("import sys");//--It is equivalent to the import sys statement in python, sys is to deal with the interpreter
    PyRun_SimpleString("sys.path.append('./')"); //Specify the directory where pytest.py is located
    PyRun_SimpleString("sys.argv = ['python.py']");

    int fArray1[5] = { 5, 2, 9, 4, 7 };
    npy_intp m[1] = { 5 };// Initialize the Python Interpreter

    PyObject* c1 = PyArray_SimpleNewFromData(1, m, NPY_INT, fArray1);

    int fArray2[5] = { 10, 5, 8, 4, 2 };
    PyObject* c2 = PyArray_SimpleNewFromData(1, m, NPY_INT, fArray2);

    // Create Tupe of size 2 to pass two arguements
    PyObject* pArgs = PyTuple_New(2);
    PyTuple_SetItem(pArgs, 0, c1);
    PyTuple_SetItem(pArgs, 1, c2);

    PyObject* pName = NULL;
    PyObject* pMoudle = NULL;//---Store the python module to be called
    PyObject* pFunc = NULL;//---Store the function to be called
    PyObject* pArgTuple = NULL;
    pName = PyUnicode_FromString("Sample"); //Specify the file name to be imported
    pMoudle = PyImport_Import(pName);//--Using the import file function to import the helloWorld.py function
    if (pMoudle == NULL)
    {
        PyRun_SimpleString("print 'PyImport_Import error!' ");
        return -1;
    }
    pFunc = PyObject_GetAttrString(pMoudle, "fun");//--Find the hello function in the python reference module helloWorld.py
    PyObject_CallObject(pFunc, pArgs);//---Call hello function

    Py_Finalize();//---Clean up the python environment and release resources
    return 0;
}

Python Script in Sample.py file:

import matplotlib.pyplot as plt
import numpy as np
def fun(x,y):

    plt.plot(x, …
rproffitt commented: Thanks for the update. I see a lot more work than up top. Good going. Also, mark as solve if you can. +15
pdk123 15 Light Poster

Hello,
I want to call the function from a python file.
By googling, it looks like I need to use the following function.
I added a "Sample.py" in the same place where the exe is stored for the c++ .

int main()
{
    Py_Initialize();
    // Create some Python objects that will later be assigned values.

    PyObject* pName, * pModule, * pFunc, * pArgs = nullptr, * pValue; 
    pName = PyUnicode_FromString((char*)"Sample"); 
    pModule = PyImport_Import(pName); 
    pFunc = PyObject_GetAttrString(pModule, (char*)"fun"); 
    pValue = PyObject_CallObject(pFunc, pArgs);
}

In the "Sample.py"

import matplotlib.pyplot as plt

def fun(): x = [1,2,3]
y = [2,4,1]
plt.plot(1, 2)

And when i run the c++ code, it throws an exception at PyObject_CallObject(pFunc, pArgs); saying "v was nullptr"

I just want to know if im missing any thing in my visual studio setup

Because when i change the sample.py to just following without the #import, it works fine

def fun():  print("Hello from a function")

works fine

thanks a lot

pdk123 15 Light Poster

Any input or help is greatly appreciated.

I was mostly working on legacy c++..now trying to implement my own small part of module. Getting difficult to integrate. time is critical, so help will be appreciated from experts.

pdk123 15 Light Poster

Hi,

I have the following map :

    listOfPolicyRuleInfo CPCRF::m_mlistOfCliConfiguredPolicyRules;

where typedef map<string, PolicyRuleInfo> listOfPolicyRuleInfo;

where PolicyRuleInfo is a struct 

struct PolicyRuleInfo{
    BearerQoSInfo stBearerQoS;
    TFTInfo stTFTInfo;
    PolicyRuleInfo(){};
    PolicyRuleInfo( BearerQoSInfo const& qos, TFTInfo const& tft)
       : stBearerQoS(qos), stTFTInfo(tft)
    { }
};

listOfPolicyRuleInfo m_mlistOfCliConfiguredPolicyRules = 
boost::assign::map_list_of("PolicyRule_Fred", PolicyRuleInfo( BearerQoSInfo(9), TFTInfo()))
                           ("PolicyRule_Voice_C", PolicyRuleInfo( BearerQoSInfo(5), TFTInfo()))
                            ("PolicyRule_Voice_U", PolicyRuleInfo( BearerQoSInfo(1), TFTInfo()));

Above are the data strutures. Now within the code somewhere ,

    listOfPolicyRuleInfo::iterator it = m_mlistOfCliConfiguredPolicyRules.find("PolicyRule_Fred");

I get error when i try to print the contents of it.

on gdb i see the list

(gdb)p m_mlistOfCliConfiguredPolicyRules

  ["PolicyRule_Fred"] = {stBearerQoS = {nQCI = 9, nMaxUlBitRate = 0, nMaxDlBitRate = 0,
      nGuarUlBitRate = 0, nGuarDlBitRate = 0, nPriorityLevel = 15,
      bPreEmptionCapabilityEnabled = false, bPreEmptionVulnerabilityEnabled = true,
      bQoSModified = false}, stTFTInfo = {static IPV4CompLen = 9 '\t',
      static PiNhCompLen = 2 '\002', static SinglePortCompLen = 3 '\003',
      static PortRangeCompLen = 5 '\005', static TypeOfServiceCompLen = 3 '\003',
      static FilterHdrLen = 3 '\003', nTFTLen = 0, eOpCode = 3653872, bEBit = false,
      nNumPktFilters = 0 '\000', mFilterId2TFTFilters = std::map with 0 elements,
      vTFTParams = std::vector of length 0, capacity 0}},
  ["PolicyRule_Voice_C"] = {stBearerQoS = {nQCI = 5, nMaxUlBitRate = 0, nMaxDlBitRate = 0,
      nGuarUlBitRate = 0, nGuarDlBitRate = 0, nPriorityLevel = 15,
      bPreEmptionCapabilityEnabled = false, bPreEmptionVulnerabilityEnabled = true,
      bQoSModified = false}, stTFTInfo = {static IPV4CompLen = 9 '\t',
      static PiNhCompLen = 2 '\002', static SinglePortCompLen = 3 '\003',
      static PortRangeCompLen = 5 '\005', static TypeOfServiceCompLen = 3 '\003',
      static FilterHdrLen = 3 …
pdk123 15 Light Poster

Hello,

I have a basic c++ STL question. I have an octet array class (legacy).

Now lets say the octet array has the following contents:
array[0]=00
array[1]=01
array[2]=30
array[3]=01
array[4]=114

The key we need to generate from the above array should match ["00130-1-114"]

Whats the best way to get this from the above array.

In the legacy code, there is way to convert, but is using lot of magic numbers everywhere, it is quite not readable..

~pdk

pdk123 15 Light Poster

It was my mistake, just to reconfirm that now issue is solved, after defining the map in the .cpp file.

pdk123 15 Light Poster

Thanks a lot Nathan and Phorce. This issue is solved now

pdk123 15 Light Poster

I have a approximate following class

class ClassA : public ClassB
{
    void                        HandleMessages(const u8 *pP, const u16 nMsgBodyLen);

    static std::map<std::pair<u32, u32>, CreateSessInfo> m_mSessionId2CCRNum2DefaultBearerId;

};

When trying to access the map from the HandleMessage, I am getting the linker error, saying the
undefined reference to m_mSessionId2CCRNum2DefaultBearerId;

Could some c++ experts help me

pdk123 15 Light Poster

Thanks a lot for the reply.

Yes, i.e true. I found later, it is good to have "set" rather than "vector" for the list of users. Where i can add , remove the users from the set, corresponding to a lets say "user group id". I think it was wrong for me to use the term key.

pdk123 15 Light Poster

Thanks a lot for the reply.

Yes, i.e true. I found later, it is good to have "set" rather than "vector" for the list of users. Where i can add , remove the users from the set, corresponding to a lets say "user group id". I think it was wrong for me to use the term key.

pdk123 15 Light Poster

Hello ,

I have map of the following type:
typedef map < int, vectorofInts > ,

Now the map has finite size. Each user when he registers, he will be allocated a key.
Lets say the map size is 4.

U1 will be allocated in K1.
next U2 on K2, U3 on K3, U4 on K4.

Later it happens in round robin way, U5 with K1 etc.

Meantime, U1 may dropoff, in that case U6, needs to be allocated K1. to keep uniformity.

Any feedback or idea regarding this alogrithm and optimum way to implement. Sorry that i am not c++ stl expert, working occasionally on this.

This is somewhat smaller version of the legacy program i have written to the one from the legacy code. Sorry for my poor c++ STL skills. Looking for the AddNewUser() function implementation.

#include <iostream>
#include <vector>
#include <map>
using namespace std;

typedef vector<int> int_vect;
typedef pair < int, int_vect > IntPair ;
typedef map<int,int_vect> outerarray;
outerarray outarr;
int_vect v0;

int AddNewUser()
{

}

int main()
{
   // vector of users
   int_vect v0;

   outarr.insert(std::make_pair(1, v0));
   outarr.insert(std::make_pair(2, v0));
   outarr.insert(std::make_pair(3, v0));
   outarr.insert(std::make_pair(4, v0));

   // Add a new User

   AddNewUser();


}

thanks
pdk

pdk123 15 Light Poster

Hello ,

I have map of the following type:
typedef map < int, vectorofInts > ,

Now the map has finite size. Each user when he registers, he will be allocated a key.
Lets say the map size is 4.

U1 will be allocated in K1.
next U2 on K2, U3 on K3, U4 on K4.

Later it happens in round robin way, U5 with K1 etc.

Meantime, U1 may dropoff, in that case U6, needs to be allocated K1. to keep uniformity and priority.

Any feedback or idea regarding this alogrithm and optimum way to implement. Sorry that i am not c++ stl expert, working occasionally on this.

thanks
pdk

pdk123 15 Light Poster

Hi,

In the legacy implementation, there is a Queue (which stored the PDUs) which need to be retransmitted. The queue has been implementated as stl map (c++). So the last element in the Queue may not be the largest SN, as per transmit window.
Is there any easy way to derive the largest SN (key) in the map ?

thanks,
pdk

pdk123 15 Light Poster

i am a c programmer, 6 month old for c++.

i am trying to add some feature to a huge c++ base code !.

stuck at this funtion . ( function names/varibles names modified )

void MCE::AddM( int Cid, int Tid, int Rid)
{
TrInstEntry* pTrInstanceEntry = (TrInstanceEntry*)m_MappingList->find(Tid);

if ( pTrInstanceEntry == 0 )
{
if ( nRbId != UNKNOWN )
pTrInstanceEntry = new TrInstanceEntry( Cid, Tid, Rid);
else
pTrInstanceEntry = new TrInstanceEntry(Cid,Tid );

:
:
:
}

later in the code i see the find being called with different ids..
for eg : id is from a array of Cids, we call, the
m_mappingList->find( Cid1);
also i see, m_MappingList being called with Tid type...
m_mappingList->find(Tid1)

i was thinking the id is a kind of key..i am not sure, how we can access the same database without indicating which key we are using ! Confused, help me...

pdk123 15 Light Poster

sorry, i know, i should have checked, i just posted..i will check before posting !!!

pdk123 15 Light Poster

Quick input: when tried with array size 2,2 works ok. But with rows=2, cols =3 coredumps !!!

pdk123 15 Light Poster

@ Moderator, sorry, by mistake i pressed the wrong rating button to csurfer and is -ve ! i am not able to change it..please change to +ve

pdk123 15 Light Poster

Thanks a lot csurfer, for the quick reply ! & pointing out my mistake. thanks a lot again.

I just made some small change in your class definition removing the .resize() and fill() functions as I didn't find their need.

template <typename T>
class dyn_arr{
public:
        //Dedault constructor
        dyn_arr() {};
		//Constructor
        dyn_arr( int rows, int cols)
        {
            for(int i=0; i<rows; i++)           
			{
				vector<T> row; // Your mistake was hardcoding int here as vector<int> as it will need vector<string> here
				for(int j=0; j<cols; j++)
				{
					row.push_back("hello");
				}
				arr.push_back(row);
			}
        }

        void print_array(int rows, int cols)
        {
			for(int i=0; i<cols; i++)
			{
				for(int j=0; j<rows; j++)
					cout << arr[i][j] << "\t";
				cout << endl;
			}
        }

private:
        vector<vector<T>> arr;
};

And ya if you are using it as a string array (dynamic) dont forget to include <string> header file.And it works. :)

pdk123 15 Light Poster

Hi, Trying to learn STL.

I tried implementing the dynamic array with the STL.

I wrote the following code and tried with int array works fine, but when i try with string array input, i get the error..can you please help me,

#include <iostream>
#include <vector>

using namespace std;

template < typename T>
class dyn_arr{

public:
        //Dedault constructor
        dyn_arr() {};

        //Constructor
        dyn_arr( int rows, int cols)

        {
            arr.resize(rows);


           for(int i=0; i<rows; i++)
           {
             vector<int> row;

             for(int j=0; j<cols; j++)
             {
                row.resize( cols);
                fill(row.begin(), row.end(), "hello");
             }
             arr.push_back(row);
           }
         }

        void print_array(int rows, int cols)
        {
          for(int i=0; i<cols; i++)
          {
             for(int j=0; j<rows; j++)
                cout << arr[i][j] << "\t";
             cout << endl;
          }
        }

private:
        vector< vector< T > > arr;
};

int main() {

        int rows=2, cols=2;

        dyn_arr<int> loc_arr(rows,cols);

        loc_arr.print_array(rows, cols);
}


For string: main looks like this

int main() {

        int rows=2, cols=2;

        dyn_arr<string> loc_arr(rows,cols);

        loc_arr.print_array(rows, cols);
}

Error:

dyn_arr.cpp: In constructor `dyn_arr<T>::dyn_arr(int, int) [with T =
std::string]':
dyn_arr.cpp:58: instantiated from here
dyn_arr.cpp:32: error: no matching function for call to `
std::vector<std::vector<std::string, std::allocator<std::string> >,
std::allocator<std::vector<std::string, std::allocator<std::string> > > >::
push_back(std::vector<int, std::allocator<int> >&)'
/usr/include/c++/3.3.1/bits/stl_vector.h:596: error: candidates are: void
std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp =
std::vector<std::string, std::allocator<std::string> >, _Alloc =
std::allocator<std::vector<std::string, std::allocator<std::string> > >]
/usr/include/c++/3.3.1/bits/stl_algobase.h: In function `void
std::fill(_ForwardIter, _ForwardIter, const _Tp&) [with _ForwardIter =
__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >,
_Tp = char[6]]':
dyn_arr.cpp:30: instantiated from `dyn_arr<T>::dyn_arr(int, int) [with T = …

pdk123 15 Light Poster

@arkoenig, thankyou very much for pointing out the problem with typecasting ..

yes , typecasting needs to be avoided !. As i am trying to modify the existing code, which is somehow working !, i donot want to touch that part as of now. I need to add another functionality, after that works, i plan to do this as part of the code cleanup.

pdk123 15 Light Poster

Hello,

Is the endianess can be for the nibble boundaries ? Because i have defined a class, and try to access the array with a pointer of class type.

typedef unsigned char uint8;

class A{
public:
uint8 a:4;
uint8 b:4;
};

int _tmain(int argc, _TCHAR* argv[])
{
    uint8 temp = 0xfa;

    A * ptr_a;

    ptr_a = (A *) &temp;

    printf("%x", ptr_a->a );

}

To my surprise, a is 0x0a and not '0x0f' !. Any comments on this, will be very helpful, as i have a very big structure with access to nibble boundaries, will make it more complex for me to determine which bit goes where !!!

pdk123 15 Light Poster

Thanks a lot, Guys for all the comments and help.

pdk123 15 Light Poster

Hi ,

Sorry for this basic question, i am stuck, with somethings,

I have a class

class A{

int * mem_ptr;

}


then somewhere in the code:

if ( mem_ptr == NULL )
{
mem_ptr = new int;
}

Is it safe to assume that mem_ptr is NULL when the class A object is created ?

pdk123 15 Light Poster

Hello,

I looking for the information regarding the ROHC compression (IETF 3095 ) for the ipv6.
ipv4 support is already implemented.

ROHCcompressed packets can be of the following types: IR, IR-DYN, UOR-2, UOR-2-ID, UOR-2-TS etc.

IR packets carry both the Static and dynamic header fields of the input stream header ( eg IP/UDP/RTP, IP/UDP etc streams). IR-DYN contains only the Dynamic part of the headers. UOR-2-ID contains the IP-ID, SN, CRC fields. Where in IP-ID is the compressed form of the ip-identifier field in the ipv4 header.

Now my question is in ipv6, there is no IP-Identification field. But the spec is not very clear abt the Packet types for ipv6. If it is using the same packet types, then i am not sure what to send in the IP-ID field in the ROHC packets ?

Any help or pointers are really appreciated.

pdk123 15 Light Poster

Hello Mike,

i got the output bin bag working fine, except that i had to make the folowing two functions virtual in the class serializable.

virtual void save(oBinBag& B) = 0;
virtual void load(iBinBag& B) = 0;

For iBinBag do you think, i need to explicitly declare the input array ? or create a new one and delete ?
my implementation is giving some compilation errors !

pdk123 15 Light Poster

Thanks a lot Mike.

I need really to do some home work, before i ask you anymore questions. This is really great.

Btw, it is for real implementation, i know, i need to ask more time now. I appreciate this help very much, i know it takes time for a c programmer to think in c++. Thanks a lot. It is really very very helpful.

pdk123 15 Light Poster

I don't mean to interrupt, but usually when you want a really robust binary interface for a byte-stream. You don't cast, or stringify, or pack/pragma, or what give you. You implement a binbag with off-the-hook protection from cross-platform, cross-compiler, cross-compiling-option.. the whole shabang. Implement the binbag's interface on the model of the std::iostreams (with those nice << >> operators) or like Boost Serialization. Then you write a save / load, or send / receive, or pack / unpack, or whatever you like to call it, that will serialize or un-serialize the data by packing it into or extracting from the binbag. This way you put all the nasty conditional compilations that you will need for ensuring off-the-hook binary-compatibility, all in one place (the binbag implementation).

Just my humble input, take it or leave it.

Thankyou Mike, My Kind request is, if possible, can you please elaborate a bit ( as i am basically a c programmer, tend to forget that c++ can offer so many things, which is obvious ). Hope i am not asking too much, without doing my homework

pdk123 15 Light Poster

Thanks a lot Mike, I will go through this option. I guess i need to do some homework for this. ( i come from c prograaming background and new to c++ )

It is really helpful , if i get design options to decide and i do some math.

pdk123 15 Light Poster

Thanks a lot Ancient Dragon. Yes, i.e the safest way.

But currently the entire ipv4 compression algo has been written with the typecasting .

So when i was trying to add the code for ipv6, it looked dangerous for me to typecast, ! ( which is obvious)...

As we discussed, to just the hack the existing code, i can put pragma as of now, ..
and when i get enough time, i guess, i need to manually extract each field from the input data stream ...

Thanks a lot, for understanding my problem exactly and suggestions are really helpful.

pdk123 15 Light Poster

Of course the receiver has to know what you are sending and he should be aware of the packing factor that you used on the data.

i guess, there is a slight misunderstanding here, :

i mean: The tcp/ip stream which is sent from the sender, or received by the receiver, will never be packed, it is just the byte stream, just with the data. The problem is how the receiver will see the data stream. The receiver, will need to interpret that as just data stream without any padding. If he wants to typecast the input data stream to a structure ptr, That ptr with which he sees the input data stream , may have the padding issue. i.e the input stream is just data, but the pointer to the structure is machine dependent, and the structure might have padding.. so if we interpret the data stream, by typecasting to structure, there will be problem with the padding...
Basic assumption here is that, whatever is transmitted or received is just the data stream, without any padding...

pdk123 15 Light Poster

i know i.e a problem, but the other guy should take care of interpretting the byte stream properly..i.e his problem right, if he misinterprets the byte stream !!!

pdk123 15 Light Poster

also currently we define the ipv4/ipv6 headers as class, i guess i can
use the prgma directive around the class ( i am a c programmer, shifting to c++, hope this will not cause any issues ? )

#pragma pack(1)

class st_ipv4 
{
//==================================================================================================
public:
//==================================================================================================

#ifdef _BIG_ENDIAN
  uint8    version:4;    // version 
  uint8    headerlength:4;  // header length 
#else
  uint8    headerlength:4;  // header length 
  uint8    version:4;    // version 
#endif
  uint8    tos;      // type of service 
  uint16  packetlength;  // total length 
  uint16  identification;  // identification 
  uint16  fragmentoffset;  // fragment offset field 
  uint8    ttl;      // time to live 
  uint8    protocol;    // protocol 
  uint16  checksum;    // checksum 
  uint32  sourceaddress;  // source address 
  uint32  destinationaddress;  // destination address 

 //**********************************************************************************************
  //* Description:
  /**  Specify/Return IPv4 Version
  */
  //**********************************************************************************************
  inline void setVersion(uint8 ubyVersion)
  {
     version = ubyVersion;
  }
  inline uint8 getVersion()
  {
    return version;
  }

}

#pragma pack()

Thanks a lot for the help/suggestions...

pdk123 15 Light Poster

Thanks a lot ...

yes, as of now there is no padding.. and as you adviced that the headers will not change,..

But my concern was when the if at all the machine size/compilers change ( i know it is very unlikely, but is still possible)...

As you suggested if i use the prgma_pack for these structures, i donot need to worry at all...

thanks a lot, it was really helpful

pdk123 15 Light Poster

i know the headers won't change, but is it ensured that they will never result in padding , lets say either the machine or compiler changes !!! i know it may not happen now, but in long term, there may be possibility of different machine sizes, which i donot know !!!

pdk123 15 Light Poster

yes, my question is, is it ensured that, TCP/IP standards define the headers in such a way that, it can be typecasted ( whatever the machine/compiler is ) !!!..even if they do, it may cause errors later, depending on upgrades in machine/compiler !!!...

any comments /advices are really helpful

pdk123 15 Light Poster

Hello All,

I have the following doubt:

Currently both the ipv4/ipv6 headers are such that they donot result in any padding. So it allows us to typecast the input stream to the ipv4/ipv6 header c structures. But don't you feel that this code is error prone ?

int Comp::getfield(uint8* pInPktStream)
{
  int swStreamType = -1;

  // examine the compressible chain of subheaders
  if(getVersion(*pInPktStream) == IP_VERSION_IPv4)
  {
    // IPv4
    st_ipv4* poIp = (st_ipv4*) pInPktStream;

:
:
}

Don;t you feel
st_ipv4* poIp = (st_ipv4*) pInPktStream;
blindly typecasting will result to problems ?

pdk123 15 Light Poster

Thankyou, problem is solved, as it was a huge code, and this new structure (structB which i added ) required forward declarations in some files ...

pdk123 15 Light Poster

Sorry for the delay, Thanks a lot Mike for the info.

I am making changes to already existing large code base, may be there is some issue somewhere , which is bit difficult to figure out..

pdk123 15 Light Poster

Thankou for the answer.
sorry, I meant function overloading.

Btw structA and structB are entirely different structures and both are defined in the header files included.

pdk123 15 Light Poster

Hello All,

I need your help to understand , if the following code is ok ? (Baically to have polymorphism of different argument types )

class A{

...

...

public:

int function( structA *ptrA);
int function( structB *ptrB);

}

I am getting the compilation error saying the

syntax error at the 2nd line :

error C2061: syntax error : identifier 'structB'

pdk123 15 Light Poster

yes, i know a bit abt , how local variables are stored.

lets say m=2, n=2 => calls m=1, n=1 => m=0,n=0 which returns num_elements =0 . In the instance when m=2, n=2, fn called, they are local varibales and all of them are pushed to stack along with num_elements =0; Then calls the instance m=1, n=1, again in this instance of the function, m and n and num-elements are pushed to stack and which in turn calls the m=0, n=0. Here m, n and num-elemnts are local varibales and returns '0' to the calling function. Then the calling function retrieves the stack for the local varibales ( m,n and num-elements) and updates the local varible with the return value '0'. Then increments num_elements and returns it to the calling function. This function where m=2, n=2, and num_elements are local varibales are retrieved from the stack. and return value is updated to the local variable, num_elements. i.e 1. Then it gets incremented to '2'.

control comes to fn m=1, n=1, num_elements get incremented and returned.

control comes to m=2, n=2, num_elements get incremented and returned.

pdk123 15 Light Poster

ok,
lets say m=2, n=2 => calls m=1, n=1 => m=0,n=0 which returns num_elements =0

control comes to fn m=1, n=1, num_elements get incremented and returned.

control comes to m=2, n=2, num_elements get incremented and returned.

pdk123 15 Light Poster

i understand recursion, By basic doubt is , since num_elements is stored in stack,(as it is local varible), will it be updated when we call the function and return value(which is also stored on stack) needs to update the local variable in the calling function....i have compiled and run. and it works fine. But i got this basic doubt....when i tried to think in terms on storage .

pdk123 15 Light Poster

sorry for my bit basic question..
may be i simplify my question further...

int function (int m, int n, int *set)
{
int num_elements =0;

if (m==0)
return 0;
else
{
num_elements = function(m-1, n-1, set);
num_elements++;
}
return num_elements;
}

main(){

printf ( "%d", function(2,2) );

}

I have a basic doubt:

First function will be called with m=2, n=2,
then it again recursively calls itself with m=1, n=1,
then it again recursively calls itself with m=0, n=0,
which returns 0, which will be assigned to num_elements.

later m=1, n=1, executes rest of the code, incrementing, num_elements and returning 1.

when it returns '1' to calling function local varible whose name is also "num-elements", will it be replaced by 1 ? or will it be masked by '0'

pdk123 15 Light Poster

num_elements is returned by each call recursively, will it be overwritten with the local variable , from the calling function ?

pdk123 15 Light Poster

Note this is a recursive function..

pdk123 15 Light Poster

Thanks a lot for the reply.

But let me rephrase, i never define num_elements globally.

Lets say the following code, (which i modified), can you please comment on what is wrong with the following code ?

//generates a psuedo-random integer between min and max
int randint(int min, int max)
{
    if (min>max)
    {
        return max+int((min-max+1)*rand()/(RAND_MAX+1.0));
    }
    else
    {
        return min+int((max-min+1)*rand()/(RAND_MAX+1.0));
    }
} 

unsigned int sample(unsigned int m, unsigned int n, unsigned int *set)
{
	unsigned int t, i, num_elements =0;
	unsigned int j,l;

	if (m==0)
		return 0;
	else
	{
		l=sample(m-1, n-1, set);
      
		t = randint(1,n);
         
		if(num_elements !=0)
		{
		   for (i=0; i <num_elements; i++)
		   {
		      if ( t == set[i])
		      {
		       	/* add t to s */
			     set[num_elements] = t;
		      }
		      else
		      {
			     /* add to n to s; */
			     set[num_elements] = n;
			     break;
		      } 
		   }
		}
		else
		{
			set[num_elements] = t;
		}

	}
	    num_elements++;
		return num_elements;
}

int _tmain(int argc, _TCHAR* argv[])
{
	unsigned int a = 2, b=4;
	unsigned int set[10];
	unsigned int num=0;
    num= sample(a, b, set);

	printf("%d", num);

	Sleep(10000);

	return 0;
}
pdk123 15 Light Poster

In the following c code, the num_elements is gobal.
But if i make it as local and return , it gives strange value just before return it becomes '0' ...can anybody explain why ?

int num_elements =0;
//generates a psuedo-random integer between min and max
int randint(int min, int max)
{
    if (min>max)
    {
        return max+int((min-max+1)*rand()/(RAND_MAX+1.0));
    }
    else
    {
        return min+int((max-min+1)*rand()/(RAND_MAX+1.0));
    }
} 

unsigned int sample(unsigned int m, unsigned int n, unsigned int *set)
{
	unsigned int t, i;
	unsigned int j,l;

	if (m==0)
		return 0;
	else
	{
		l=sample(m-1, n-1, set);
      
		t = randint(1,n);
         
		if(num_elements !=0)
		{
		   for (i=0; i <num_elements; i++)
		   {
		      if ( t == set[i])
		      {
		       	/* add t to s */
			     set[num_elements] = t;
		      }
		      else
		      {
			     /* add to n to s; */
			     set[num_elements] = n;
			     break;
		      } 
		   }
		}
		else
		{
			set[num_elements] = t;
		}

	}
	    j= num_elements++;
        printf("%d", num_elements);
		return j;
}

int _tmain(int argc, _TCHAR* argv[])
{
	unsigned int a = 2, b=4;
	unsigned int set[10];
	num_elements=0;
    sample(a, b, set);

	printf("%d", num_elements);

	Sleep(10000);

	return 0;
}
pdk123 15 Light Poster

thanks Dave for the answers.

for 6) is it not a problem that register is 'int' type where as input is ptr to long int.

pdk123 15 Light Poster

1

bool f( uint n )

{

return (n & (n-1)) == 0;

}

My answer was : if n is powers of 2 then return 1 else '0'

2.

uint f( uint n )

{

return –n & 7;

}

My answer: last 3 (LSB) bits of the 2's complement of the input number .

3.

int f( int n, int l, int r )

{

return (n << l) >> r;

}

my Answer : n is bit shifted left by l bits and result is again right shifted by n bits.
6.

void fn(long* p1, long* p2)

{

register int x = *p1;

register int y = *p2;

x ^= y;

y ^= x;

x ^= y;

*p1 = x;

*p2 = y;

}

my answer : swaps the two inputs x and y.

7.

void send(int count, short *to, short *from)

{

/* count > 0 assumed */

register n = (count + 7) / 8;

switch (count % 8)

{

case 0: do { *to = *from++;

case 7: *to = *from++;

case 6: *to = *from++;

case 5: *to = *from++;

case 4: *to = *from++;

case 3: *to = *from++;

case 2: *to = *from++;

case 1: *to = *from++;

} while (--n > 0);

}

}

My answer : this expression copies the counth element of 'from' array to the first element of the 'to' array.