Search Results

Search found 976 results on 40 pages for 'typedef'.

Page 23/40 | < Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >

  • Create Generic Class Instance from Static Method in a Derived Class

    - by user343547
    I have a class in C# with a template and static method similar to class BClass<T> { public static BClass<T> Create() { return new BClass<T>(); } } From this I derive a class and specify a template parameter to the base class class DClass : BClass<int> { } A problem occurs when I try to use the static method to create an instance of D class Program { static void Main(string[] args) { DClass d = DClass.Create(); } } Gives a compiler error "Cannot implicitly convert type 'Test.BClass<int ' to 'Test.DClass'." Adding the below cast leads to a runtime casting exception. DClass d = (DClass)DClass.Create(); Is there any succint way to allow the static method to create instances of the derived class? Ideally I would like the equivalent of a c++ typedef and I don't want the below syntax (which does work). BClass<int> d = DClass.Create();

    Read the article

  • C++ STL map.find() not finding my stuff

    - by Joe
    Hello, I have constructed a map and loaded it with data. If I iterate over all the elements I see they are all valid. However, the find method doesn't find my item. I'm sure it's something stupid I am doing. Here is snippet: // definitions // I am inserting a person class and using the firstname as the key typedef std::map<char*,Person *> mapType; mapType _myMap; mapType::iterator _mapIter; ... Person *pers = new Person(FirstName, LastName, Address, Phone); _myMap.insert(make_pair(pers->firstName, pers); ... ...later.... _mapIter = _myMap.find(firstName); // returns map.end _mapIter = _myMap.find("joe"); // returns map.end and I have no idea why :(

    Read the article

  • <function> referenced from; symbol(s) not found.

    - by jfm429
    I have a piece of C code that is used from a C++ function. At the top of my C++ file I have the line: #include "prediction.h" In prediction.h I have this: #ifndef prediction #define prediction #include "structs.h" typedef struct { double estimation; double variance; } response; response runPrediction(int obs, location* positions, double* observations, int targets, location* targetPositions); #endif I also have prediction.c, which has: #include "prediction.h" response runPrediction(int obs, location* positions, double* observations, int targets, location* targetPositions) { // code here } Now, in my C++ file (which as I said includes prediction.h) I call that function, then compile (through Xcode) I get this error: "runPrediction(int, location*, double*, int, location*)", referenced from: mainFrame::respondTo(char*, int)in mainFrame.o ld: symbol(s) not found collect2: ld returned 1 exit status prediction.c is marked for compilation for the current target. I don't have any problems with other .cpp files not being compiled. Any thoughts here?

    Read the article

  • C Class Instance from Void Pointer using Ctypes

    - by g.d.d.c
    I've got a C DLL that exposes a handful of methods that return void pointers to a Class like so: void *GetLicense() { static AppLicenseImpl ipds_; return (void *) &ipds_; } In C++, after loading the DLL, I'd do this to work with it: typedef void *(* FPGetLicense)(); GetLicense_ = (FPGetLicense)GetAddress("GetLicense"); license_ = (AppLicense *) GetLicense_(); license_->GetApplicationStatus(); // Load data so that other calls don't fail I can't figure out how to parallel that in Python. This gets me the pointer: d = ctypes.cdll.LoadLibrary('license.dll') d.GetLicense.restype = ctypes.c_void_p p = d.GetLicense() # returns ptr loc, something like 8791433660848L But I obviously can't call p.GetApplicationStatus() in Python. Does anyone have a suggestion on how I'd instantiate that Class the rest of the way in Python so that I can call GetApplicationStatus()?

    Read the article

  • Creating Instance of Python Extension Type in C

    - by Brad Zeis
    I am writing a simple Vector implementation as a Python extension module in C that looks mostly like this: typedef struct { PyObject_HEAD double x; double y; } Vector; static PyTypeObject Vector_Type = { ... }; It is very simple to create instances of Vector while calling from Python, but I need to create a Vector instance in the same extension module. I looked in the documentation but I couldn't find a clear answer. What's the best way to do this?

    Read the article

  • Casting to global variable from LPVOID - C

    - by Jamie Keeling
    I am trying to cast data to a struct from a parameter passed into my method, I need the data to be passed to a global variable as it is needed elsewhere in my application. I have tried the following but I get errors saying that diceResult is an undeclared identifier Here is the code itself: //Structure to hold dice data typedef struct diceData { int dice1; int dice2; }; struct diceResult; DWORD WINAPI UnpackDiceData(LPVOID sentData) { //Unpack data struct diceData unpackedData = *((struct diceData*)sentData); diceResult.dice1 = unpackedData.dice1; diceResult.dice2 = unpackedData.dice2; } I don't understand why it won't recognise it being there when it's clearly global.

    Read the article

  • C error expected specifier-qualifier-list before ‘time_t’

    - by ambika
    I got the error from error.c:31: /usr/include/ap/mas.h:254: error: expected specifier-qualifier-list before ‘time_t’ make: *** [error.o] Error 1 Feedback We at least need to see line 31 of error.c and line 254 of mas.h, with preferably a few lines of context around each. This error may have nothing to do with how time_t is being declared. – John Bode Then I check in error.c (line no 31) -- #include "mas.h" then I check line no 254 in mas.h. in mas.h #include <sys/types.h> typedef struct _x{ time_t time; }x; Can anybody suggest where I am going wrong?

    Read the article

  • Copy a function in memory and execute it

    - by Elinghton
    Hi everybody, I would like to know how in C in can copy the content of a function into memroy and the execute it? I'm trying to do something like this: typedef void(*FUN)(int *); char * myNewFunc; char *allocExecutablePages (int pages) { template = (char *) valloc (getpagesize () * pages); if (mprotect (template, getpagesize (), PROT_READ|PROT_EXEC|PROT_WRITE) == -1) { perror ("mprotect"); } } void f1 (int *v) { *v = 10; } // allocate enough spcae but how much ?? myNewFunc = allocExecutablePages(...) /* Copy f1 somewere else * (how? assume that i know the size of f1 having done a (nm -S foo.o)) */ ((FUN)template)(&val); printf("%i",val); Thanks for your answers

    Read the article

  • Why am I getting a segmentation fault with this code?

    - by gooswa
    Trying to make a simple rectangle/bin packer in C. Takes a given area and finds placement for any given size rectangle. About after 4 recursions is when I get the segmentation fault. #include <stdio.h> #include <stdlib.h> typedef struct node_type PackNode; struct node_type { int x , y; int width , height; int used; struct node_type *left; struct node_type *right; }; typedef struct point_type PackPoint; struct point_type { int x,y; }; PackNode _clone(PackNode *node) { PackNode clone; clone.used = 0; clone.x = node->x; clone.y = node->y; clone.width = node->width; clone.height= node->height; clone.left = NULL; clone.right= NULL; return clone; } PackNode root; int rcount; PackPoint* recursiveFind(PackNode *node, int w, int h) { PackPoint rp; PackPoint *p = NULL; rcount++; printf ("rcount = %u\n", rcount); //left is not null go to left, if left didn't work try right. if (node->left!=NULL) { //move down to left branch p = recursiveFind(node->left, w, h); if (p!=NULL) { return p; } else { p = recursiveFind(node->right, w, h); return p; } } else { //If used just return null and possible go to the right branch; if (node->used==1 || w > node->width || h > node->height) { return p; } //if current node is exact size and hasn't been used it return the x,y of the mid-point of the rectangle if (w==node->width && h == node->height) { node->used=1; rp.x = node->x+(w/2); rp.y = node->y+(h/2); p = &rp; return p; } //If rectangle wasn't exact fit, create branches from cloning it's parent. PackNode l_clone = _clone(node); PackNode r_clone = _clone(node); node->left = &l_clone; node->right = &r_clone; //adjust branches accordingly, split up the current unused areas if ( (node->width - w) > (node->height - h) ) { node->left->width = w; node->right->x = node->x + w; node->right->width = node->width - w; } else { node->left->height = h; node->right->y = node->y + h; node->right->height = node->height - h; } p = recursiveFind(node->left, w, h); return p; } return p; } int main(void) { root = malloc( root.x=0; root.y=0; root.used=0; root.width=1000; root.height=1000; root.left=NULL; root.right=NULL; int i; PackPoint *pnt; int rw; int rh; for (i=0;i<10;i++) { rw = random()%20+1; rh = random()%20+1; pnt = recursiveFind(&root, rw, rh); printf("pnt.x,y: %d,%d\n",pnt->x,pnt->y); } return 0; }

    Read the article

  • Fault address when malloc/free pthread_t across threads

    - by scleung
    Fault address occurred when i malloc pthread_t to save a newly created thread id and free it in another thread. Codes as follows: typedef struct _TaskInfo { // int dummy_int; pthread_t tid; } TaskInfo; void* dummy_task(void* pArg) { free(pArg); return NULL; } void create_task() { TaskInfo *pInfo; pthread_attr_t attr; // set detached state stuff ... pInfo = (TaskInfo*) malloc(sizeof(TaskInfo)); pthread_create(&pInfo->tid, &attr, dummy_task, pInfo); // destroy pthread attribute stuff ... } int main() { int i; while(i < 10000) { create_task(); ++i; } return 0; } When I uncomment the member dummy_int of TaskInfo it sometimes ran successfully, but sometimes failed. My platform is VMWare + Ubuntu 9.10 + ndk r3 Thanks!

    Read the article

  • Is it a good practice to pass struct object as parameter to a function in c++?

    - by tsubasa
    I tried an example live below: typedef struct point { int x; int y; } point; void cp(point p) { cout<<p.x<<endl; cout<<p.y<<endl; } int main() { point p1; p1.x=1; p1.y=2; cp(p1); } The result thats printed out is: 1 2 which is what I expected. My question is: Does parameter p get the full copy of object p1? If so, I wonder if this is a good practice? (I assumed when the struct gets big in size, this will create a lot of copy overhead).

    Read the article

  • winsock compile crash

    - by ioil
    The following errors are from a file with just windows and winsock2 included. C:\Users\ioil\Desktop\dm\bin>dmc sockit.c typedef struct fd_set { ^ C:\Users\ioil\Desktop\dm\bin\..\include\win32\WINSOCK2.H(85) : Error: 'fd_set' is already defined } fd_set; ^ C:\Users\ioil\Desktop\dm\bin\..\include\win32\WINSOCK2.H(88) : Error: identifier or '( declarator )' expected struct timeval { ^ C:\Users\ioil\Desktop\dm\bin\..\include\win32\WINSOCK2.H(129) : Error: 'timeval' is already defined }; ^ C:\Users\ioil\Desktop\dm\bin\..\include\win32\WINSOCK2.H(132) : Error: identifier or '( declarator )' expected struct hostent { ^ C:\Users\ioil\Desktop\dm\bin\..\include\win32\WINSOCK2.H(185) : Error: 'hostent' is already defined Fatal error: too many errors --- errorlevel 1 C:\Users\ioil\Desktop\dm\bin> What's already been tried : placing the winsock.dll file in the same directory as the compiler and program to be compiled, placing it in the system32 directory, and entering it in the registry with the regsrv32 command. Don't really know where to go from here, appreciate any advice . . .

    Read the article

  • C++ Structure within itself?

    - by Douglas
    I've been trying to port this code to python, but there is something I do not quite understand in C++ (I do know a bit of C++ but this is beyond me): typedef struct huffnode_s { struct huffnode_s *zero; struct huffnode_s *one; unsigned char val; float freq; } huffnode_t; What I don't get is how huffnode_s can be within itself, I've never seen this before and don't quite understand it. What does this mean, and if someone can, what would be the python equivalent?

    Read the article

  • What is the ISO C++ way to directly define a conversion function to reference to array?

    - by ben
    According to the standard, a conversion function has a function-id operator conversion-type-id, which would look like, say, operator char(&)[4] I believe. But I cannot figure out where to put the function parameter list. gcc does not accept either of operator char(&())[4] or operator char(&)[4]() or anything I can think of. Now, gcc seems to accept (&operator char ())[4] but clang does not, and I am inclined to not either, since it does not seem to fit the grammar as I understand it. I do not want to use a typedef because I want to avoid polluting the namespace with it.

    Read the article

  • C errors - Cannot combine with previous 'struct' declaration specifier && Redefinition of 'MyMIDINotifyProc' as different kind of symbol

    - by user1905634
    I'm still new to C but trying to understand it better by working my way through a small MIDI audio unit (in Xcode 4.3.3). I've been searching for an answer to this all day and still don't even understand exactly what the problem is. Here's the code in question: //MyMIDINotifyProc.h #ifndef MIDIInstrumentUnit_CallbackProcs_h #define MIDIInstrumentUnit_CallbackProcs_h void MyMIDINotifyProc (const MIDINotification *message, void *refCon); #endif //MyMIDINotifyProc.c #include <CoreMIDI/CoreMIDI.h> #include "MyMIDINotifyProc.h" void MyMIDINotifyProc (const MIDINotification *message, void *refCon) { //manage notification } In the header definition I get this: ! Cannot combine with previous 'struct' declaration specifier I've made sure the definitions match and tried renaming them and I still get this in my .c file: ! Redefinition of 'MyMIDINotifyProc' as different kind of symbol Which points to the .h definition as the 'Previous definition'. I know that MIDIServices.h in the CoreMIDI framework defines: typedef void (*MIDINotifyProc)(const MIDINotification *message, void *refCon); But I don't understand if/why that would cause an error. I would be grateful if anyone could offer some help.

    Read the article

  • Auto pointer for unsigned char array?

    - by Gianluca
    I'd need a class like std::auto_ptr for an array of unsigned char*, allocated with new[]. But auto_ptr only calls delete and not delete[], so i can't use it. I also need to have a function which creates and returns the array. I came out with my own implementation within a class ArrayDeleter, which i use like in this example: #include <Utils/ArrayDeleter.hxx> typedef Utils::ArrayDeleter<unsigned char> Bytes; void f() { // Create array with new unsigned char* xBytes = new unsigned char[10]; // pass array to constructor of ArrayDeleter and // wrap it into auto_ptr return std::auto_ptr<Bytes>(new Bytes(xBytes)); } ... // usage of return value { auto_ptr<Bytes> xBytes(f()); }// unsigned char* is destroyed with delete[] in destructor of ArrayDeleter Is there a more elegant way to solve this? (Even using another "popular" library)

    Read the article

  • c++ to vb.net , problem with callback function

    - by johan
    I'm having a hard time here trying to find a solution for my problem. I'm trying to convert a client API funktion from C++ to VB.NET, and i think have some problems with the callback function. parts of the C++ code: typedef struct{ BYTE m_bRemoteChannel; BYTE m_bSendMode; BYTE m_nImgFormat; // =0 cif ; = 1 qcif char *m_sIPAddress; char *m_sUserName; char *m_sUserPassword; BOOL m_bUserCheck; HWND m_hShowVideo; }CLIENT_VIDEOINFO, *PCLIENT_VIDEOINFO; CPLAYER_API LONG __stdcall MP4_ClientStart(PCLIENT_VIDEOINFO pClientinfo,void(CALLBACK *ReadDataCallBack)(DWORD nPort,UCHAR *pPacketBuffer,DWORD nPacketSize)); void CALLBACK ReadDataCallBack(DWORD nPort,UCHAR *pPacketBuffer,DWORD nPacketSize) { TRACE("%d\n",nPacketSize); } ..... aa5.m_sUserName = "123"; aa5.m_sUserPassword="w"; aa5.m_bUserCheck = TRUE; MP4_ClientSetTTL(64); nn1 = MP4_ClientStart(&aa5,ReadDataCallBack); if (nn1 == -1) { MessageBox("error"); return; } SDK description: MP4_ClientStart This function starts a connection. The format of the call is: LONG __stdcall MP4_ClientStart(PCLIENT_VIDEOINFO pClientinfo, void(*ReadDataCallBack)(DWORD nChannel,UCHAR *pPacketBuffer,DWORD nPacketSize)) Parameters pClientinfo holds the information. of this connection. nChannel holds the channel of card. pPacketBuffer holds the pointer to the receive buffer. nPacketSize holds the length of the receive buffer. Return Values If the function succeeds the return value is the context of this connection. If the function fails the return value is -1. Remarks typedef struct{ BYTE m_bRemoteChannel; BYTE m_bSendMode; BYTE m_bImgFormat; char *m_sIPAddress; char *m_sUserName; char *m_sUserPassword; BOOL m_bUserCheck; HWND m_hShowVideo; } CLIENT_VIDEOINFO, * PCLIENT_VIDEOINFO; m_bRemoteChannel holds the channel which the client wants to connect to. m_bSendMode holds the network mode of the connection. m_bImgFormat : Image format, 0 is main channel video, 1 is sub channel video m_sIPAddress holds the IP address of the server. m_sUserName holds the user’s name. m_sUserPassword holds the user’s password. m_bUserCheck holds the value whether sends the user’s name and password or not. m_hShowVideo holds Handle for this video window. If m_hShowVideo holds NULL, the client can be record only without decoder. If m_bUserCheck is FALSE, we will send m_sUserName and m_sUserPassword as NULL, else we will send each 50 bytes. The length of m_sIPAddress and m_sUserName must be more than 50 bytes. ReadDataCallBack: When the library receives a packet from a server, this callback is called. My VB.Net code: Imports System.Runtime.InteropServices Public Class Form1 Const WM_USER = &H400 Public Structure CLIENT_VIDEOINFO Public m_bRemoteChannel As Byte Public m_bSendMode As Byte Public m_bImgFormat As Byte Public m_sIPAddress As String Public m_sUserName As String Public m_sUserPassword As String Public m_bUserCheck As Boolean Public m_hShowVideo As Long 'hWnd End Structure Public Declare Function MP4_ClientSetNetPort Lib "hikclient.dll" (ByVal dServerPort As Integer, ByVal dClientPort As Integer) As Boolean Public Declare Function MP4_ClientStartup Lib "hikclient.dll" (ByVal nMessage As UInteger, ByVal hWnd As System.IntPtr) As Boolean <DllImport("hikclient.dll")> Public Shared Function MP4_ClientStart(ByVal Clientinfo As CLIENT_VIDEOINFO, ByRef ReadDataCallBack As CALLBACKdel) As Long End Function Public Delegate Sub CALLBACKdel(ByVal nPort As Long, <MarshalAs(UnmanagedType.LPArray)> ByRef pPacketBuffer As Byte(), ByVal nPacketSize As Long) Public Sub CALLBACK(ByVal nPort As Long, <MarshalAs(UnmanagedType.LPArray)> ByRef pPacketBuffer As Byte(), ByVal nPacketSize As Long) End Sub Public mydel As New CALLBACKdel(AddressOf CALLBACK) Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim Clientinfo As New CLIENT_VIDEOINFO() Clientinfo.m_bRemoteChannel = 0 Clientinfo.m_bSendMode = 0 Clientinfo.m_bImgFormat = 0 Clientinfo.m_sIPAddress = "193.168.1.100" Clientinfo.m_sUserName = "1" Clientinfo.m_sUserPassword = "a" Clientinfo.m_bUserCheck = False Clientinfo.m_hShowVideo = Me.Handle 'Nothing MP4_ClientSetNetPort(850, 850) MP4_ClientStartup(WM_USER + 1, Me.Handle) MP4_ClientStart(Clientinfo, mydel) End Sub End Class here is some other examples of the code in: C# http://blog.csdn.net/nenith1981/archive/2007/09/17/1787692.aspx VB ://read.pudn.com/downloads70/sourcecode/graph/250633/MD%E5%AE%A2%E6%88%B7%E7%AB%AF%28VB%29/hikclient.bas__.htm ://read.pudn.com/downloads70/sourcecode/graph/250633/MD%E5%AE%A2%E6%88%B7%E7%AB%AF%28VB%29/Form1.frm__.htm Delphi ://read.pudn.com/downloads91/sourcecode/multimedia/streaming/349759/Delphi_client/Unit1.pas__.htm

    Read the article

  • a nicer way to create structs in a loop

    - by sandra
    Hi guys, I haven't coded in C++ in ages. And recently, I'm trying to work on something involving structs. Like this typedef struct{ int x; int y; } Point; Then in a loop, I'm trying to create new structs and put pointers to them them in a list. Point* p; int i, j; while (condition){ // compute values for i and j with some function... p = new Point; p* = {i, j}; //initialize my struct. list.append(p); //append this pointer to my list. } Now, my question is it possible to simplify this? I mean, the pointer variable *p outside of the loop and calling p = new Point inside the loop. Isn't there a better/nicer syntax for this?

    Read the article

  • Segmentation fault problem (C)

    - by user228938
    I have a struct named Game with an array of levels, defined like this: typedef struct { Level levels[x]; } Game; When I compile the code, if x is 1, 2 or 3, the program runs normally. If it's any other value (4, for instance), I get a segmentation fault. I'm not accessing the array anywhere. Main is something like this at the moment (commented everything except the initialization): int main (...) { Game g; return 0; } Any clue of what this might be? Thanks in advance.

    Read the article

  • Getting plane slices from array data

    - by umanga
    Greetings all, I read 3d grid data (from multiple TIF images) into a structure as follows : typedef struct VolumeData{ int nx; int ny; int nz; unsigned char *data; // size is nx*ny*nz } Now I want to get the plane slices from this 1-D grid data: eg: unsigned char* getXYPlaneStack(VolumeData *vol,int z); I could implement above function because the *data array stores image stack. But i am having difficult time implement along the other axes: unsigned char* getYZPlaneStack(VolumeData *vol,int x); and unsigned char* getXZPlaneStack(VolumeData *vol,int y); any easy algorithm for this? thanks in advance.

    Read the article

  • Multithreading with STL container

    - by Steven
    I have an unordered map which stores a pointer of objects. I am not sure whether I am doing the correct thing to maintain the thread safety. typedef std::unordered_map<string, classA*>MAP1; MAP1 map1; pthread_mutex_lock(&mutexA) if(map1.find(id) != map1.end()) { pthread_mutex_unlock(&mutexA); //already exist, not adding items } else { classA* obj1 = new classA; map1[id] = obj1; obj1->obtainMutex(); //Should I create a mutex for each object so that I could obtain mutex when I am going to update fields for obj1? pthread_mutex_unlock(&mutexA); //release mutex for unordered_map so that other threads could access other object obj1->field1 = 1; performOperation(obj1); //takes some time obj1->releaseMutex(); //release mutex after updating obj1 }

    Read the article

  • C++ function-pointer and inheritance

    - by pingvinus
    In parent class I have function, that operates under an array of functions, declared in child-class, number of functions for every child-class may vary. But since every function uses some object-variables, I can't declare them as static. I've try to do something like this: class A { public: typedef int (A::*func)(); func * fs; void f() { /*call functions from this->fs*/ } }; class B : public A { public: int smth; B(int smth) { this->smth = smth; this->fs = new func[1]; fs[0] = &B::f; } int f() { return smth + 1; } }; But, obviously it doesn't work. Any suggestions?

    Read the article

  • Global list in C/gtk+

    - by sterh
    Hello, I need in global list in my gtk+ application, i use for it GList: For example: I have structure: typedef struct _data { Glist list; }Data; I want to use one copy of the list in the whole program: I have a function bulid my list: gboolean build_list() { Data->list = g_list_append(mw->a, "First "); Data->list = g_list_append(mw->a, "Second "); Data->list = g_list_append(mw->a, "Third "); g_list_foreach(Data->list, (GFunc)printf, NULL); } After calling this function to display all items in the list. zbut when i try to make it in another function - for example: void foreach() { g_list_foreach(Data->list, (GFunc)printf, NULL); } I see error in gdb: *Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 0xb7335700 (LWP 5364)] 0xb765a7d7 in strchrnul () from /lib/i686/cmov/libc.so.6 * How can i create global list in my application? Thank you.

    Read the article

  • C programming: hashtable insertion/search

    - by Ricardo Campos
    Hello i have a problem with my hash table its implemented like this: #define HT_SIZE 10 typedef struct _list_t_ { char key[20]; char string[20]; char prevValue[20]; struct _list_t_ *next; } list_t; typedef struct _hash_table_t_ { int size; /* the size of the table */ list_t ***table; /* first */ sem_t lock; } hash_table_t; I have a Linked list with 3 pointers because i want a hash table with several partitions (shards), here is my initialization of my Hash table: hash_table_t *create_hash_table(int NUM_SERVER_THREADS, int num_shards){ hash_table_t *new_table; int j,i; if (HT_SIZE<1) return NULL; /* invalid size for table */ /* Attempt to allocate memory for the hashtable structure */ new_table = (hash_table_t*)malloc(sizeof(hash_table_t)*HT_SIZE); /* Attempt to allocate memory for the table itself */ new_table->table = (list_t ***)calloc(1,sizeof(list_t **)); /* Initialize the elements of the table */ for(j=0; j<num_shards; j++){ new_table->table[j] = (list_t **)calloc(1,sizeof(list_t *)); for(i=0; i<HT_SIZE; i++){ new_table->table[j][i] = (list_t *)calloc(1,sizeof(list_t )); } } /* Set the table's size */ new_table->size = HT_SIZE; sem_init(&new_table->lock, 0, 1); return new_table; } Here is my search function to search in the hash table list_t *lookup_string(hash_table_t *hashtable, char *key, int shardId){ list_t *list ; int hashval = hash(key); /* Go to the correct list based on the hash value and see if key is * in the list. If it is, return return a pointer to the list element. * If it isn't, the item isn't in the table, so return NULL. */ sem_wait(&hashtable->lock); for(list = hashtable->table[shardId][hashval]; list != NULL; list =list->next) { if (strcmp(key, list->key) == 0){ sem_post(&hashtable->lock); return list; } } sem_post(&hashtable->lock); return NULL; } And my insert function: char *add_string(hash_table_t *hashtable, char *str,char *key, int shardId){ list_t *new_list; list_t *current_list; unsigned int hashval = hash(key); /*printf("|%d|%d|%s|\n",hashval,shardId,key);*/ /* Lock for concurrency */ sem_wait(&hashtable->lock); /* Attempt to allocate memory for list */ new_list = (list_t*)malloc(sizeof(list_t)); /* Does item already exist? */ sem_post(&hashtable->lock); current_list = lookup_string(hashtable, key,shardId); sem_wait(&hashtable->lock); /* item already exists, don't insert it again. */ if (current_list != NULL){ strcpy(new_list->prevValue,current_list->string); strcpy(new_list->string,str); strcpy(new_list->key,key); new_list->next = hashtable->table[shardId][hashval]; hashtable->table[shardId][hashval] = new_list; sem_post(&hashtable->lock); return new_list->prevValue; } /* Insert into list */ strcpy(new_list->string,str); strcpy(new_list->key,key); new_list->next = hashtable->table[shardId][hashval]; hashtable->table[shardId][hashval] = new_list; /* Unlock */ sem_post(&hashtable->lock); return new_list->prevValue; } My main class runs some of tests by executing the insertion / reading / delete from the elements of the hash table the problem is when i have more than 4 partitions/shards the tests stop at the first reading element saying it returned the wrong value NULL on the search function, when its less than 4 it runs perfectly well and passes all the tests. You can see my main.c in here if you want to give a look: http://hostcode.sourceforge.net/view/1105 My complete Hash table code: http://hostcode.sourceforge.net/view/1103 And other functions where hash table code is executed: .c file http://hostcode.sourceforge.net/view/1104 .h file http://hostcode.sourceforge.net/view/1106 Thank for you time, i appreciate any help you can give to me this is a college important project that I'm trying to solve and I'm stuck here for 2 days.

    Read the article

< Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >