Search Results

Search found 6123 results on 245 pages for 'unsigned char'.

Page 68/245 | < Previous Page | 64 65 66 67 68 69 70 71 72 73 74 75  | Next Page >

  • Multithreading using pthread in C++ with shared variables

    - by Saviour Self
    I'm new to threading (and C/C++ for that matter), and I'm attempting to use multiple threads to access shared variables. In the main, I've created a variable char inputarray[100]; Thread 1: This thread will be reading data from stdin in 2 byte bursts, and appending them to the inputarray. (input by feeding a file in) Thread 2: This thread will be reading data 1 byte at a time, performing a calculation, and putting its data into an output array. Thread 3: This thread will be outputting data from the output array in 2 byte bursts. (stdout) I've attempted the input part and got it working by passing a struct, but would like to do it without using a struct, but it has been giving me problems. If I can get input down, I'm sure I'll be able to use a similar strategy to complete output. Any help would be greatly appreciated. Below is a rough template for the input thread. #include <stdio.h> #include <pthread.h> using namespace std; void* input(void* arg) { char reading[3]; fread(reading,1,2,stdin); //append to char inputarray[]..??? } int main() { char inputarray[100]; pthread_t t1; pthread_create(&t1, NULL, &input, &inputarray); void *result; pthread_join(t1,&result); return 0; }

    Read the article

  • code is not compiling

    - by user323422
    template< class Type ,int Size = 3> class cStack { Type *m_array; int m_Top; int m_Size; public:cStack(); friend std::ostream& operator <<(std::ostream &, const cStack<Type,Size> &); }; template< class Type ,int Size > std::ostream& operator << ( std::ostream &os, const cStack<Type,Size> &s) { for( int i=0; i<=s.GetTop();i++) { os << s.m_array[i]; } return os; } on compilin it showing following error error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class cStack<int,3> const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$cStack@H$02@@@Z) referenced in function _main

    Read the article

  • Process is killed without a (obvious) reason and program stops working

    - by Krzysiek Gurniak
    Here's what my program is supposed to do: create 4 child processes: process 0 is reading 1 byte at a time from STDIN, then writing it into FIFO process 1 is reading this 1 byte from fifo and write its value as HEX into shared memory process 2 is reading HEX value from shared memory and writing it into pipe finally process 3 is reading from pipe and writing into STDOUT (in my case: terminal) I can't change communication channels. FIFO, then shared memory, then pipes are the only option. My problem: Program stops at random moments when some file is directed into stdin (for example:./program < /dev/urandom). Sometimes after writing 5 HEX values, sometimes after 100. Weird thing is that when it is working and in another terminal I write "pstree -c" there is 1 main process with 4 children processes (which is what I want), but when I write "pstree -c" after it stopped writing (but still runs) there are only 3 child processes. For some reason 1 is gone even though they all have while(1) in them.. I think I might have problem with synchronization here, but I am unable to spot it (I've tried for many hours). Here's the code: #include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/shm.h> #include <sys/sem.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <string.h> #include <signal.h> #define BUFSIZE 1 #define R 0 #define W 1 // processes ID pid_t p0, p1, p2, p3; // FIFO variables int fifo_fd; unsigned char bufor[BUFSIZE] = {}; unsigned char bufor1[BUFSIZE] = {}; // Shared memory variables key_t key; int shmid; char * tab; // zmienne do pipes int file_des[2]; char bufor_pipe[BUFSIZE*30] = {}; void proces0() { ssize_t n; while(1) { fifo_fd = open("/tmp/fifo",O_WRONLY); if(fifo_fd == -1) { perror("blad przy otwieraniu kolejki FIFO w p0\n"); exit(1); } n = read(STDIN_FILENO, bufor, BUFSIZE); if(n<0) { perror("read error w p0\n"); exit(1); } if(n > 0) { if(write(fifo_fd, bufor, n) != n) { perror("blad zapisu do kolejki fifo w p0\n"); exit(1); } memset(bufor, 0, n); // czyszczenie bufora } close(fifo_fd); } } void proces1() { ssize_t m, x; char wartosc_hex[30] = {}; while(1) { if(tab[0] == 0) { fifo_fd = open("/tmp/fifo", O_RDONLY); // otwiera plik typu fifo do odczytu if(fifo_fd == -1) { perror("blad przy otwieraniu kolejki FIFO w p1\n"); exit(1); } m = read(fifo_fd, bufor1, BUFSIZE); x = m; if(x < 0) { perror("read error p1\n"); exit(1); } if(x > 0) { // Konwersja na HEX if(bufor1[0] < 16) { if(bufor1[0] == 10) // gdy enter { sprintf(wartosc_hex, "0x0%X\n", bufor1[0]); } else { sprintf(wartosc_hex, "0x0%X ", bufor1[0]); } } else { sprintf(wartosc_hex, "0x%X ", bufor1[0]); } // poczekaj az pamiec bedzie pusta (gotowa do zapisu) strcpy(&tab[0], wartosc_hex); memset(bufor1, 0, sizeof(bufor1)); // czyszczenie bufora memset(wartosc_hex, 0, sizeof(wartosc_hex)); // przygotowanie tablicy na zapis wartosci hex x = 0; } close(fifo_fd); } } } void proces2() { close(file_des[0]); // zablokuj kanal do odczytu while(1) { if(tab[0] != 0) { if(write(file_des[1], tab, strlen(tab)) != strlen(tab)) { perror("blad write w p2"); exit(1); } // wyczysc pamiec dzielona by przyjac kolejny bajt memset(tab, 0, sizeof(tab)); } } } void proces3() { ssize_t n; close(file_des[1]); // zablokuj kanal do zapisu while(1) { if(tab[0] == 0) { if((n = read(file_des[0], bufor_pipe, sizeof(bufor_pipe))) > 0) { if(write(STDOUT_FILENO, bufor_pipe, n) != n) { perror("write error w proces3()"); exit(1); } memset(bufor_pipe, 0, sizeof(bufor_pipe)); } } } } int main(void) { key = 5678; int status; // Tworzenie plikow przechowujacych ID procesow int des_pid[2] = {}; char bufor_proces[50] = {}; mknod("pid0", S_IFREG | 0777, 0); mknod("pid1", S_IFREG | 0777, 0); mknod("pid2", S_IFREG | 0777, 0); mknod("pid3", S_IFREG | 0777, 0); // Tworzenie semaforow key_t klucz; klucz = ftok(".", 'a'); // na podstawie pliku i pojedynczego znaku id wyznacza klucz semafora if(klucz == -1) { perror("blad wyznaczania klucza semafora"); exit(1); } semafor = semget(klucz, 1, IPC_CREAT | 0777); // tworzy na podstawie klucza semafor. 1 - ilosc semaforow if(semafor == -1) { perror("blad przy tworzeniu semafora"); exit(1); } if(semctl(semafor, 0, SETVAL, 0) == -1) // ustawia poczatkowa wartosc semafora (klucz, numer w zbiorze od 0, polecenie, argument 0/1/2) { perror("blad przy ustawianiu wartosci poczatkowej semafora"); exit(1); } // Tworzenie lacza nazwanego FIFO if(access("/tmp/fifo", F_OK) == -1) // sprawdza czy plik istnieje, jesli nie - tworzy go { if(mkfifo("/tmp/fifo", 0777) != 0) { perror("blad tworzenia FIFO w main"); exit(1); } } // Tworzenie pamieci dzielonej // Lista pamieci wspoldzielonych, komenda "ipcs" // usuwanie pamieci wspoldzielonej, komenta "ipcrm -m ID_PAMIECI" shmid = shmget(key, (BUFSIZE*30), 0666 | IPC_CREAT); if(shmid == -1) { perror("shmget"); exit(1); } tab = (char *) shmat(shmid, NULL, 0); if(tab == (char *)(-1)) { perror("shmat"); exit(1); } memset(tab, 0, (BUFSIZE*30)); // Tworzenie lacza nienazwanego pipe if(pipe(file_des) == -1) { perror("pipe"); exit(1); } // Tworzenie procesow potomnych if(!(p0 = fork())) { des_pid[W] = open("pid0", O_WRONLY | O_TRUNC | O_CREAT); // 1 - zapis, 0 - odczyt sprintf(bufor_proces, "Proces0 ma ID: %d\n", getpid()); if(write(des_pid[W], bufor_proces, sizeof(bufor_proces)) != sizeof(bufor_proces)) { perror("blad przy zapisie pid do pliku w p0"); exit(1); } close(des_pid[W]); proces0(); } else if(p0 == -1) { perror("blad przy p0 fork w main"); exit(1); } else { if(!(p1 = fork())) { des_pid[W] = open("pid1", O_WRONLY | O_TRUNC | O_CREAT); // 1 - zapis, 0 - odczyt sprintf(bufor_proces, "Proces1 ma ID: %d\n", getpid()); if(write(des_pid[W], bufor_proces, sizeof(bufor_proces)) != sizeof(bufor_proces)) { perror("blad przy zapisie pid do pliku w p1"); exit(1); } close(des_pid[W]); proces1(); } else if(p1 == -1) { perror("blad przy p1 fork w main"); exit(1); } else { if(!(p2 = fork())) { des_pid[W] = open("pid2", O_WRONLY | O_TRUNC | O_CREAT); // 1 - zapis, 0 - odczyt sprintf(bufor_proces, "Proces2 ma ID: %d\n", getpid()); if(write(des_pid[W], bufor_proces, sizeof(bufor_proces)) != sizeof(bufor_proces)) { perror("blad przy zapisie pid do pliku w p2"); exit(1); } close(des_pid[W]); proces2(); } else if(p2 == -1) { perror("blad przy p2 fork w main"); exit(1); } else { if(!(p3 = fork())) { des_pid[W] = open("pid3", O_WRONLY | O_TRUNC | O_CREAT); // 1 - zapis, 0 - odczyt sprintf(bufor_proces, "Proces3 ma ID: %d\n", getpid()); if(write(des_pid[W], bufor_proces, sizeof(bufor_proces)) != sizeof(bufor_proces)) { perror("blad przy zapisie pid do pliku w p3"); exit(1); } close(des_pid[W]); proces3(); } else if(p3 == -1) { perror("blad przy p3 fork w main"); exit(1); } else { // proces macierzysty waitpid(p0, &status, 0); waitpid(p1, &status, 0); waitpid(p2, &status, 0); waitpid(p3, &status, 0); //wait(NULL); unlink("/tmp/fifo"); shmdt(tab); // odlaczenie pamieci dzielonej shmctl(shmid, IPC_RMID, NULL); // usuwanie pamieci wspoldzielonej printf("\nKONIEC PROGRAMU\n"); } } } } exit(0); }

    Read the article

  • Java: over-typed structures?

    - by HH
    Term over-type structure = a data structure that accepts different types, can be primitive or user-defined. I think ruby supports many types in structures such as tables. I tried a table with types 'String', 'char' and 'File' in Java but errs. How can I have over-typed structure in Java? How to show types in declaration? What about in initilization? Suppose a structure: INDEX VAR FILETYPE //0 -> file FILE //1 -> lineMap SizeSequence //2 -> type char //3 -> binary boolean //4 -> name String //5 -> path String Code import java.io.*; import java.util.*; public class Object { public static void print(char a) { System.out.println(a); } public static void print(String s) { System.out.println(s); } public static void main(String[] args) { Object[] d = new Object[6]; d[0] = new File("."); d[2] = 'T'; d[4] = "."; print(d[2]); print(d[4]); } } Errors Object.java:18: incompatible types found : java.io.File required: Object d[0] = new File("."); ^ Object.java:19: incompatible types found : char required: Object d[2] = 'T'; ^

    Read the article

  • How does object of sub-class record information about its super-class the in a Virtual Inheritance

    - by Summer_More_More_Tea
    Hi there: I encounter this problem when tackling with virtual inheritance. I remember that in a non-virtual inheritance hierarchy, object of sub-class hold an object of its direct super-class. What about virtual inheritance? In this situation, does object of sub-class hold an object of its super-class directly or just hold a pointer pointing to an object of its super-class? By the way, why the output of the following code is: sizeof(A): 8 sizeof(B): 20 sizeof(C): 32 Code: #include <iostream> using namespace std; class A{ char k[ 3 ]; public: virtual void a(){}; }; class B : public virtual A{ char j[ 3 ]; public: virtual void b(){}; }; class C : public virtual B{ char i[ 3 ]; public: virtual void c(){}; }; int main( int argc, char *argv[] ){ cout << "sizeof(A): " << sizeof( A ) << endl; cout << "sizeof(B): " << sizeof( B ) << endl; cout << "sizeof(C): " << sizeof( C ) << endl; return 0; } Thanks in advance. Kind regards.

    Read the article

  • C++ union data-structure, easy acccess of bits within a DWORD

    - by TK
    Im running through a set of DirectX tutorials online and I have the following structure: struct CUSTOMVERTEX { FLOAT x, y, z, rhw; // from the D3DFVF_XYZRHW flag DWORD color; // from the D3DFVF_DIFFUSE flag } My basic understanding of directX leads me to thing tha color is made up of 8-bit alpha, red, green and blue channels. I am attempting to get east access to these channels. Rather than write the following code numerous times (within the CUSTOMVERTEX structure): public: int red() { return (color & 0x00FF0000) >> 16; } I could write a more elegant somution with a combination of a union and a structure e.g. struct CUSTOMVERTEX { FLOAT x, y, z, rhw; // from the D3DFVF_XYZRHW flag #pragma pack(2) union { DWORD color; // from the D3DFVF_DIFFUSE flag struct { char a; char r; char g; char b; }; }; } However this does not appear to function as expected, the values in r, g, & b almost appear the reverse of whats in color e.g. if color is 0x12345678 a = 0x78, r = 0x56. Is this an endieness issue? Also what other problems could I be expecting from this solution? e.g. overflow from the color members? I guess what Im asking is ... is there a better way to do this?!

    Read the article

  • C -- Basic Struct questions

    - by Ryan Yu
    So I'm trying to learn C right now, and I have some basic struct questions I'd like to clear up: Basically, everything centers around this snippet of code: #include <stdio.h> #include <stdlib.h> #define MAX_NAME_LEN 127 typedef struct { char name[MAX_NAME_LEN + 1]; unsigned long sid; } Student; /* return the name of student s */ const char* getName (const Student* s) { // the parameter 's' is a pointer to a Student struct return s->name; // returns the 'name' member of a Student struct } /* set the name of student s If name is too long, cut off characters after the maximum number of characters allowed. */ void setName(Student* s, const char* name) { // 's' is a pointer to a Student struct | 'name' is a pointer to the first element of a char array (repres. a string) s->name = name; } /* return the SID of student s */ unsigned long getStudentID(const Student* s) { // 's' is a pointer to a Student struct return s->sid; } /* set the SID of student s */ void setStudentID(Student* s, unsigned long sid) { // 's' is a pointer to a Student struct | 'sid' is a 'long' representing the desired SID s->sid = sid; } I've commented up the code in an attempt to solidify my understanding of pointers; I hope they're all accurate. So anyway, I have a feeling that setName and setStudentID aren't correct, but I'm not exactly sure why. Can someone explain? Thanks!

    Read the article

  • How can I modify the value of a string defined in a struct?

    - by Eric
    Hi, I have the following code in c++: #define TAM 4000 #define NUMPAGS 512 struct pagina { bitset<12> direccion; char operacion; char permiso; string *dato; int numero; }; void crearPagina(pagina* pag[], int pos, int dir) { pagina * paginas = (pagina*)malloc(sizeof(char) * TAM); paginas -> direccion = bitset<12> (dir); paginas -> operacion = 'n'; paginas -> permiso = 'n'; string **tempDato = &paginas -> dato; char *temp = " "; **tempDato = temp; paginas -> numero = 0; pag[pos] = paginas; } I want to modify the value of the variable called "string *dato" in the struct pagina but, everytime I want to assing a new value, the compiler throws a segmentation fault. In this case I'm using a pointer to string, but I have also tried with a string. In a few words I want to do the following: pagina - dato = "test"; Any idea? Thanks in advance!!!

    Read the article

  • how to write binary copy of structure array to file

    - by cerr
    I would like to write a binary image of a structure array to a binary file. I have tried this so far: #include <stdio.h> #include <string.h> #define NUM 256 const char *fname="binary.bin"; typedef struct foo_s { int intA; int intB; char string[20]; }foo_t; void main (void) { foo_t bar[NUM]; bar[0].intA = 10; bar[0].intB = 999; strcpy(bar[0].string,"Hello World!"); Save(bar); printf("%s written succesfully!\n",fname); } int Save(foo_t* pData) { FILE *pFile; int ptr = 0; int itr = 0; pFile = fopen(fname, "w"); if (pFile == NULL) { printf("couldn't open %s\n", fname); return; } for (itr = 0; itr<NUM; itr++) { for (ptr=0; ptr<sizeof(foo_t); ptr++) { fputc((unsigned char)*((&pData[itr])+ptr), pFile); } fclose(pFile); } } but the compiler is saying aggregate value used where an integer was expected fputc((unsigned char)*((&pData[itr])+ptr), pFile); and I don't quite understand why, what am I doing wrong? Thanks!

    Read the article

  • iPhone and iPad : Doing a "select * from something" query in a SQLite database

    - by Abramodj
    Hi folks, i'm trying to use the SQLite data base in my iPad app, and here's my function to make a query: - (void)executeQuery:(char*)query { NSString *file = [self getWritableDBPath]; NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL success = [fileManager fileExistsAtPath:file]; // If its not a local copy set it to the bundle copy if(!success) { //file = [[NSBundle mainBundle] pathForResource:DATABASE_TITLE ofType:@"db"]; [self createEditableCopyOfDatabaseIfNeeded]; } dataArray = NULL; dataArray = [NSMutableArray array]; sqlite3 *database = NULL; if (sqlite3_open([file UTF8String], &database) == SQLITE_OK) { sqlite3_exec(database, query, loadTimesCallback, dataArray, NULL); } sqlite3_close(database); [self logResults]; } if I call [self executeQuery:"select name from table1"]; everything is working fine. But if i call [self executeQuery:"select * from cars"]; the app crashes telling me that the NSMutableArray dataArray is not the right kind of variable where to set the query results. So, how can i do a "select * form table1" query, and store the results? Thanks! EDIT: Here's my loadTimesCallback method: static int loadTimesCallback(void *context, int count, char **values, char **columns) { NSMutableArray *times = (NSMutableArray *)context; for (int i=0; i < count; i++) { const char *nameCString = values[i]; [times addObject:[NSString stringWithUTF8String:nameCString]]; } return SQLITE_OK; }

    Read the article

  • Why does mmap() fail with ENOMEM on a 1TB sparse file?

    - by metadaddy
    I've been working with large sparse files on openSUSE 11.2 x86_64. When I try to mmap() a 1TB sparse file, it fails with ENOMEM. I would have thought that the 64 bit address space would be adequate to map in a terabyte, but it seems not. Experimenting further, a 1GB file works fine, but a 2GB file (and anything bigger) fails. I'm guessing there might be a setting somewhere to tweak, but an extensive search turns up nothing. Here's some sample code that shows the problem - any clues? #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/types.h> #include <unistd.h> int main(int argc, char *argv[]) { char * filename = argv[1]; int fd; off_t size = 1UL << 40; // 30 == 1GB, 40 == 1TB fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, 0666); ftruncate(fd, size); printf("Created %ld byte sparse file\n", size); char * buffer = (char *)mmap(NULL, (size_t)size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if ( buffer == MAP_FAILED ) { perror("mmap"); exit(1); } printf("Done mmap - returned 0x0%lx\n", (unsigned long)buffer); strcpy( buffer, "cafebabe" ); printf("Wrote to start\n"); strcpy( buffer + (size - 9), "deadbeef" ); printf("Wrote to end\n"); if ( munmap(buffer, (size_t)size) < 0 ) { perror("munmap"); exit(1); } close(fd); return 0; }

    Read the article

  • UIImage Object surprisingly returning null but not NSData

    - by riyaz
    i have created a sqlite db. and i have insert a few datas in my db.. UIImage * imagee=[UIImage imageNamed:@"image.png"]; NSData *mydata=[NSData dataWithData:UIImagePNGRepresentation(imagee)]; const char *dbpath = [databasePath UTF8String]; NSString *insertSQL=[NSString stringWithFormat:@"insert into CONTACTS values(\"%@\",\"%@\")",@"Mathan",mydata]; NSLog(@"mydata %@",mydata); sqlite3_stmt *addStatement; const char *insert_stmt=[insertSQL UTF8String]; if (sqlite3_open(dbpath,&contactDB)==SQLITE_OK) { sqlite3_prepare_v2(contactDB,insert_stmt,-1,&addStatement,NULL); if (sqlite3_step(addStatement)==SQLITE_DONE) { sqlite3_bind_blob(addStatement,1, [mydata bytes], [mydata length], SQLITE_TRANSIENT); NSLog(@"Data saved"); } else{ NSLog(@"Some Error occured"); } sqlite3_close(contactDB); } else{ NSLog(@"Failure"); } have written some codes to retrive the data sqlite3_stmt *statement; if (sqlite3_open([databasePath UTF8String], &contactDB) == SQLITE_OK) { NSString *sql = [NSString stringWithFormat:@"SELECT * FROM contacts"]; if (sqlite3_prepare_v2( contactDB, [sql UTF8String], -1, &statement, nil) == SQLITE_OK) { while (sqlite3_step(statement) == SQLITE_ROW) { char *field1 = (char *) sqlite3_column_text(statement, 0); NSString *field1Str = [[NSString alloc] initWithUTF8String: field1]; NSLog(@"UserName %@",field1Str); NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement, 1) length:sqlite3_column_bytes(statement, 1)]; UIImage *newImage = [[UIImage alloc]initWithData:data]; NSLog(@"Image OBJ %@",newImage); NSLog(@"Image Data %@",data); } sqlite3_close(contactDB); } } sqlite3_finalize(statement); the problem is in log, inserted NSData object and retrieved NSData Objects are different (printing in log gives different stream) moreover Image OBJ is printed null in log.. Have seen similar questions in stackoverflow. But nothing seems to help. Please give some suggestions to overcome this issue.

    Read the article

  • Why does Go not seem to recognize size_t in a C header file?

    - by Graeme Perrow
    I am trying to write a go library that will act as a front-end for a C library. If one of my C structures contains a size_t, I get compilation errors. AFAIK size_t is a built-in C type, so why wouldn't go recognize it? My header file looks like: typedef struct mystruct { char * buffer; size_t buffer_size; size_t * length; } mystruct; and the errors I'm getting are: gcc failed: In file included from <stdin>:5: mydll.h:4: error: expected specifier-qualifier-list before 'size_t' on input: typedef struct { char *p; int n; } _GoString_; _GoString_ GoString(char *p); char *CString(_GoString_); #include "mydll.h" I've even tried adding either of // typedef unsigned long size_t or // #define size_t unsigned long in the .go file before the // #include, and then I get "gcc produced no output". I have seen these questions, and looked over the example with no success.

    Read the article

  • throwing exception from APCProc crashes program

    - by lazy_banana
    I started to do some research on how terminate a multithreaded application properly and I found those 2 post(first, second) about how to use QueueUserAPC to signal other threads to terminate. I thought I should give it a try, and the application keeps crashing when I throw the exception from the APCProc. Code: #include <stdio.h> #include <windows.h> class ExitException { public: char *desc; DWORD exit_code; ExitException(char *desc,int exit_code): desc(desc), exit_code(exit_code) {} }; //I use this class to check if objects are deconstructed upon termination class Test { public: char *s; Test(char *s): s(s) { printf("%s ctor\n",s); } ~Test() { printf("%s dctor\n",s); } }; DWORD CALLBACK ThreadProc(void *useless) { try { Test t("thread_test"); SleepEx(INFINITE,true); return 0; } catch (ExitException &e) { printf("Thread exits\n%s %lu",e.desc,e.exit_code); return e.exit_code; } } void CALLBACK exit_apc_proc(ULONG_PTR param) { puts("In APCProc"); ExitException e("Application exit signal!",1); throw e; return; } int main() { HANDLE thread=CreateThread(NULL,0,ThreadProc,NULL,0,NULL); Sleep(1000); QueueUserAPC(exit_apc_proc,thread,0); WaitForSingleObject(thread,INFINITE); puts("main: bye"); return 0; } My question is why does this happen? I use mingw for compilation and my OS is 64bit. Can this be the reason?I read that you shouldn't call QueueApcProc from a 32bit app for a thread which runs in a 64bit process or vice versa, but this shouldn't be the case.

    Read the article

  • c++ code cons/pros

    - by VirusEcks
    below i have a code that runs in most of my simple programs .. . i want to know if it's good/bad ... and cons/pros . . win32 header file: win32.h #include <windows.h> #include <process.h> #include <stdarg.h> main header file: inc.h #include "win32.h" #ifndef INCS #define INCS #define DD #else #define DD extern #endif #ifndef VARS #define titlen L"my program" #endif DD wchar_t gtitle[512]; DD wchar_t gclass[512]; DD wchar_t gdir[32767]; #include "resources.h" #include "commonfunctions.h" then all files have something like this commonfunctions.h DD inline bool icmp( const char *String1, const char *String2 ) { if ( _stricmp( String1, String2 ) == 0 ) { return true; } return false; } DD inline bool scmp( const char *String1, const char *String2 ) { if ( strcmp( String1, String2 ) == 0 ) { return true; } return false; } all global variables have DD infront of them and all functions have DD too . is there a bad side of this ? . i came up with this idea and it wasn't problematic at all in small programs . but before i apply it in a large project will it be problematic ?. thanks in advance.

    Read the article

  • Sha256 is giving junk output

    - by user1746617
    hey can u be more specific on how to convert to bin to hex. bool HashStatus::calculate_digest_value(char * path,unsigned char * output) { FILE* file = fopen(path, "rb"); if(!file) { g_message("SignatureValidator::VerifyReferences,file not opened"); return -1; } unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&sha256); const int bufSize = 32768; unsigned char* buffer = malloc(bufSize); int bytesRead = 0; if(!buffer) return NULL; while((bytesRead = fread(buffer, 1, bufSize, file))) { g_message("calculate digest value,verify.cpp::%s",buffer); SHA256_Update(&sha256, buffer, bytesRead); } SHA256_Final(hash, &sha256); g_message("verify.cpp,after final"); sha256_hash_string(hash, output); g_message("verify.cpp,after sha256_hash_string %s",hash); fclose(file); free(buffer); return true; } this is my code to convert file data into hash using sha256 openssl function o/p is :1d54e12333988471354907a760b9cde861423615bb5255ee837e3b27b32366 but actual o/p is:HVThAjM5iEcTVJB6dgC5zehhQjYVu1JV7oN+OyezI2Y= can you guys please help me with whatz wrong with this code,ASAP and i'm new to this please guide me step by step and in detail..

    Read the article

  • printing out dictionnaires

    - by kyril
    I have a rather specific question: I want to print out characters at a specific place using the \033[ syntax. This is what the code below should do: (the dict cells has the same keys as coords but with either '*' or '-' as value.) coords = {'x'+str(x)+'y'+str(y) : (x,y) for x,y, in itertools.product(range(60), range(20))} for key, value in coords.items(): char = cells[key] x,y = value HORIZ=str(x) VERT=str(y) char = str(char) print('\033['+VERT+';'+HORIZ+'f'+char) However, I noticed that if I put this into a infinite while loop, it does not always prints the same characters at the same position. There are only slight changes, but it deletes some and puts them back in after some loops. I already tried it with lists, and there it seems to behave just fine, so I tend to think it has something todo with the dict, but I can not figure out what it could be. You can see the Problem in a console here: SharedConsole.I am happy for every tip on this matter. On a related topic: After the printing, some changes should be made at the values of the cells dict, but for reason unknown to me, the only the first two rules are executed and the rest is ignored. The rules should test how many neighbours (which is in population) are around the cell and apply the according rule. In my implemention of this I have some kind of weird tumor growth (which should not happen, as if there more than three around they should the cell should die) (see FreakingTumor): if cells_copy [coord] == '-': if population == 3: cells [coord] = '*' if cells_copy [coord] == '*': if population > 3: cells [coord] = '-' elif population <= 1: cells [coord] = '-' elif population == 2 or 3: cells [coord] = '*' I checked the population variable several times, so I am quite sure that is not the matter. I am sorry for the slow consoles. Thanks in advance! Kyril

    Read the article

  • MySQL Datefields: duplicate or calculate?

    - by Konerak
    We are using a table with a structure imposed upon us more than 10 years ago. We are allowed to add columns, but urged not to change existing columns. Certain columns are meant to represent dates, but are put in different format. Amongst others: * CHAR(6): YYMMDD * CHAR(6): DDMMYY * CHAR(8): YYYYMMDD * CHAR(8): DDMMYYYY * DATE * DATETIME Since we now would like to do some more complex queries, using advanced date functions, my manager proposed to d*uplicate those problem columns* to a proper FORMATTED_OLDCOLUMNNAME column using a DATE or DATETIME format. Is this the way to go? Couldn't we just use the STR_TO_DATE function each time we accessed the columns? To avoid every query having to copy-paste the function, I could still work with a view or a stored procedure, but duplicating data to avoid recalculation sounds wrong. Solutions I see (I guess I prefer 2.2.1) 1. Physically duplicate columns 1.1 In the same table 1.1.1 Added by each script that does a modification (INSERT/UPDATE/REPLACE/...) 1.1.2 Maintained by a trigger on each modification 1.2 In a separate table 1.2.1 Added by each script that does a modification (INSERT/UPDATE/REPLACE/...) 1.2.2 Maintained by a trigger on each modification 2. On-demand transformation 2.1 Each query has to perform the transformation 2.1.1 Using copy-paste in the source code 2.1.2 Using a library 2.1.3 Using a STORED PROCEDURE 2.2 A view performs the transformation 2.2.1 A separate table replacing the entire table 2.2.2 A separate table just adding the date-fields for the primary keys Am I right to say it's better to recalculate than to store? And would a view be a good solution?

    Read the article

  • How string accepting interface should look like?

    - by ybungalobill
    Hello, This is a follow up of this question. Suppose I write a C++ interface that accepts or returns a const string. I can use a const char* zero-terminated string: void f(const char* str); // (1) The other way would be to use an std::string: void f(const string& str); // (2) It's also possible to write an overload and accept both: void f(const char* str); // (3) void f(const string& str); Or even a template in conjunction with boost string algorithms: template<class Range> void f(const Range& str); // (4) My thoughts are: (1) is not C++ish and may be less efficient when subsequent operations may need to know the string length. (2) is bad because now f("long very long C string"); invokes a construction of std::string which involves a heap allocation. If f uses that string just to pass it to some low-level interface that expects a C-string (like fopen) then it is just a waste of resources. (3) causes code duplication. Although one f can call the other depending on what is the most efficient implementation. However we can't overload based on return type, like in case of std::exception::what() that returns a const char*. (4) doesn't work with separate compilation and may cause even larger code bloat. Choosing between (1) and (2) based on what's needed by the implementation is, well, leaking an implementation detail to the interface. The question is: what is the preffered way? Is there any single guideline I can follow? What's your experience?

    Read the article

  • What are the linkage of the following functions?

    - by Derui Si
    When I was reading the c++ 03 standard (7.1.1 Storage class specifiers [dcl.stc]), there are some examples as below, I'm not able to tell how the linkage of each successive declarations is determined? Could anyone help here? Thanks in advance! static char* f(); // f() has internal linkage char* f() { /* ... */ } // f() still has internal linkage char* g(); // g() has external linkage static char* g() { /* ... */ } // error: inconsistent linkage void h(); inline void h(); // external linkage inline void l(); void l(); // external linkage inline void m(); extern void m(); // external linkage static void n(); inline void n(); // internal linkage static int a; // a has internal linkage int a; // error: two definitions static int b; // b has internal linkage extern int b; // b still has internal linkage int c; // c has external linkage static int c; // error: inconsistent linkage extern int d; // d has external linkage static int d; // error: inconsistent linkage UPD: Additionally, how can I understand the statement in the standard, " The linkages implied by successive declarations for a given entity shall agree. That is, within a given scope, each declaration declaring the same object name or the same overloading of a function name shall imply the same linkage. Each function in a given set of overloaded functions can have a different linkage, however."

    Read the article

  • Java: over-typed structures? To have many types in Object[]?

    - by HH
    Term over-type structure = a data structure that accepts different types, can be primitive or user-defined. I think ruby supports many types in structures such as tables. I tried a table with types 'String', 'char' and 'File' in Java but errs. How can I have over-typed structure in Java? How to show types in declaration? What about in initilization? Suppose a structure: INDEX VAR FILETYPE //0 -> file FILE //1 -> lineMap SizeSequence //2 -> type char //3 -> binary boolean //4 -> name String //5 -> path String Code import java.io.*; import java.util.*; public class Object { public static void print(char a) { System.out.println(a); } public static void print(String s) { System.out.println(s); } public static void main(String[] args) { Object[] d = new Object[6]; d[0] = new File("."); d[2] = 'T'; d[4] = "."; print(d[2]); print(d[4]); } } Errors Object.java:18: incompatible types found : java.io.File required: Object d[0] = new File("."); ^ Object.java:19: incompatible types found : char required: Object d[2] = 'T'; ^

    Read the article

  • How to know the type of an object in a list?

    - by nacho4d
    Hi, I want to know the type of object (or type) I have in my list so I wrote this: void **list; //list of references list = new void * [2]; Foo foo = Foo(); const char *not_table [] = {"tf", "ft", 0 }; list[0] = &foo; list[1] = not_table; if (dynamic_cast<LogicProcessor*>(list[0])) { //ERROR here ;( printf("Foo was found\n"); } if (dynamic_cast<char*> (list[0])) { //ERROR here ;( printf("char was found\n"); } but I get : error: cannot dynamic_cast '* list' (of type 'void*') to type 'class Foo*' (source is not a pointer to class) error: cannot dynamic_cast '* list' (of type 'void*') to type 'char*' (target is not pointer or reference to class) Why is this? what I am doing wrong here? Is dynamic_cast what I should use here? Thanks in advance EDIT: I know above code is much like plain C and surely sucks from the C++ point of view but is just I have the following situation and I was trying something before really implementing it: I have two arrays of length n but both arrays will never have an object at the same index. Hence, or I have array1[i]!=NULL or array2[i]!=NULL. This is obviously a waste of memory so I thought everything would be solved if I could have both kind of objects in a single array of length n. I am looking something like Cocoa's (Objective-C) NSArray where you don't care about the type of the object to be put in. Not knowing the type of the object is not a problem since you can use other method to get the class of a certain later. Is there something like it in c++ (preferably not third party C++ libraries) ? Thanks in advance ;)

    Read the article

  • What are the C# equivalent of these C++ structs

    - by Otake
    typedef union _Value { signed char c; unsigned char b; signed short s; unsigned short w; signed long l; unsigned long u; float f; double *d; char *p; } Value; typedef struct _Field { WORD nFieldId; BYTE bValueType; Value Value; } Field; typedef struct _Packet { WORD nMessageType; WORD nSecurityType; BYTE bExchangeId; BYTE bMarketCenter; int iFieldCount; char cSymbol[20]; Field FieldArr[1]; } Packet; What are the C# equivalent of these C++ structs? I am migrating some code from C++ to C# and having problems to migrate these structures. I had tried a few things but I always ended up having marshalling problems.

    Read the article

  • Problem in data binding in NSString?

    - by Rajendra Bhole
    Hi, I selecting the row of the table. The text of the row i stored in the application delegate object as a NSString. That NSString i want to retrieving or binding in SELECT statement of SQLite query, For that i written code in the TableView Class (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { selectedText = [appDelegate.categoryArray objectAtIndex:indexPath.row]; appDelegate.selectedTextOfRow = selectedText; ListOfPrayersViewController *listVC = [[ListOfPrayersViewController alloc] init]; [self.navigationController pushViewController:listVC animated:YES]; [listVC release]; } and database class class code is. + (void) getDuas:(NSString *)dbPath{ if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK){ SalahAppDelegate *appDelegate = (SalahAppDelegate *)[[UIApplication sharedApplication] delegate]; NSString *categoryTextForQuery =[NSString stringWithFormat:@"SELECT Category FROM Prayer WHERE Category ='%s'", appDelegate.selectedTextOfRow ]; NSLog(@"The Text %@", categoryTextForQuery); //const char *sqlQuery1 = (char *)categoryTextForQuery; //const char *sqlQuery = "SELECT Category FROM Prayer WHERE Category = 'Invocations for the beginning of the prayer'"; sqlite3_stmt *selectstmt; if(sqlite3_prepare_v2(database, [categoryTextForQuery UTF8String], -1, &selectstmt, NULL) == SQLITE_OK){ appDelegate.duasArray =[[NSMutableArray alloc] init]; while(sqlite3_step(selectstmt) == SQLITE_ROW){ NSString *dua = [[NSString alloc] initWithCString:(char *)sqlite3_column_text(selectstmt,0) encoding:NSASCIIStringEncoding]; Prayer *prayerObj = [[Prayer alloc] initwithDuas:dua]; prayerObj.DuaName = dua; [appDelegate.duasArray addObject:prayerObj]; } } } } The code is comes out of loop on the statement or starting the loop of the while(sqlite3_step(selectstmt) == SQLITE_ROW) Why? How i bind the table selected text in SELECT statement of sqlite?

    Read the article

  • Operator Overloading << in c++

    - by thlgood
    I'm a fresh man in C++. I write this simple program to practice Overlaoding. This is my code: #include <iostream> #include <string> using namespace std; class sex_t { private: char __sex__; public: sex_t(char sex_v = 'M'):__sex__(sex_v) { if (sex_v != 'M' && sex_v != 'F') { cerr << "Sex type error!" << sex_v << endl; __sex__ = 'M'; } } const ostream& operator << (const ostream& stream) { if (__sex__ == 'M') cout << "Male"; else cout << "Female"; return stream; } }; int main(int argc, char *argv[]) { sex_t me('M'); cout << me << endl; return 0; } When I compiler it, It print a lots of error message: The error message was in a mess. It's too hard for me to found useful message sex.cpp: ???‘int main(int, char**)’?: sex.cpp:32:10: ??: ‘operator<<’?‘std::cout << me’????? sex.cpp:32:10: ??: ???: /usr/include/c++/4.6/ostream:110:7: ??: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostre

    Read the article

< Previous Page | 64 65 66 67 68 69 70 71 72 73 74 75  | Next Page >