question
stringlengths
25
894
answer
stringlengths
4
863
in threads, i need to periodically do some work in some different intervals, what would be a good way to do this? With sleep(), then i need keep track of the interval to the next wakeup, which doesn't seem to be the best way. thanks.
You can useclock_nanosleepwith theTIMER_ABSTIMEflag to work with absolute times instead of relative times for your sleep. That will avoid error accumulation problems and race conditions where your program gets interrupted and another process scheduled after getting the current time but before calling sleep. Alternatively you could use POSIX timers (timer_create) with a signal handler, where the signal you choose is blocked in all threads but yours, or with timer delivery in a new thread that signals a condition variable or semaphore your thread is waiting on.
This question already has answers here:Closed12 years ago. Possible Duplicate:C/C++: is GOTO faster than WHILE and FOR? I know this has been asked for many times, but I never got an answer which satisfies me by googling. I read somewhere that every loop(for/while/do-while/untill) will be eventually be converted to goto statements internally, Is that True? If not, Which is the best loop to use as per the performance wise? Let me know if anybody knows?
The correct answer is to learn enough assembly in order to read through your compiler's generated code. However, these micro-optimizations usually don't matter (except for very specific areas).
Which of these calls is faster on average? I've heard thatmmapis faster for smaller allocations but I haven't heard a comparison of either. Any information on performance for these would be nice.
You should tag this with a particular implementation (likelinux) since the answer surely varies by implementation. For now I'll assume Linux since it's the most popular. With that said,brkis in theory more optimizable, and in practice it runs about 10% faster on my machine. Allocating one page, these are the times I get: brk: min 2550 cycles, typical 2650 cyclesmmap: min 2700 cycles, typical 2800 cycles I remember hearing something along the lines ofbrkbeing able to skip locking themmapsemaphore, which would explain the discrepancy. Note:I updated these times after adjusting my test to make a dummy calls prior to timing, to ensure that the code would all be in the cache.
I trying to get size of files in a directory by using dirent.h headers. However ``` stat(ent->d_name, &statbuf) ``` returns always -1 and I can't get the size properly. What could be the reason?
d_namecontains the name of the file within that directory.statwants a name including the directory part, unless it's the current directory. Make a temporary string containing the full path to thed_namefile. EDIT: Sample ``` char const * DirName = "/tmp"; .... char * FullName = (char*) malloc(strlen(DirName) + strlen(ent->d_name) + 2); strcpy(FullName, DirName); strcat(FullName, "/"); strcat(FullName, ent->d_name); stat(FullName, &statbuf); free(FullName); ```
pretty simple question I have here, but I couldn't find the answer: Assume I have some conditional clause made up of several conditions. E.g. something like ``` if((a == b && strcmp(string1, string)) || x <= 5) ``` My question is: Will all of those statements be evaluated, no matter what the result of the first ones was, or will the evaluation stop once the result is clear. As I am not sure whether my question is clear, here's an example: ``` if(a == 5 || b > 12 || (c = someFun()) == 3) ``` In this case, if a == 5, no further checks would be required, because the result of the big statement is TRUE, so we could simply continue. This would mean that someFun() would not be evaluated. Is this the case? I know Java makes a difference here between && and & resp. || and | (the latter aren't available in C anyways), but I do not know how C handles this
These operators areshort-circuitingin C (and C++).
In Lex i can start a new state using the keyword BEGIN STATE1. I want to do the same from yacc in between rules . In the action section of a rule , if i add BEGIN STATE1 , it says BEGIN undeclared error. Is there any way i can do this?
Ise Wisteria found the answer for me. Create separate functions in lex that use the BEGIN macro . Call them in bison . Note:For those very beginners like me , do not forget to add a declaration of these functions at the beginning of the .y file or you will get an undeclared error during linking.
``` typedef struct employee { int age; char name[30]; } emp_t; emp_t * e; int main( ) { printf("\nName : "); scanf("%s", &e->name); return 0; } ``` this code compiles but when I try to enter my name such as "mukesh" it throughs out an error Can somebody explain why this is happening In the structure I used char name[] as well as char * name......did't work I don't understandwhy??????? do I need to allocate memory dynamically to the structure employee and then assign it it to e->name
Yes, you must allocate the storage before you can access it. Otherwise you'll just be pointing at some random location in memory. Try this: ``` typedef struct employee { int age; char name[30]; } emp_t; emp_t * e; int main( ) { e = malloc(sizeof(emp_t)); printf("\nName : "); scanf("%s", e->name); return 0; } ```
This question already has answers here:sprintf() with automatic memory allocation?(8 answers)Closed8 years ago. I've heard there is a version ofsprintf(), possibly a GNU/gcc extension which either allocates its own buffer which I mustfree()or perhaps works using the stack likealloca(). Either method is fine for me. Can anyone tell me what function I was thinking of?
You probably meanasprintf? From the man page: Description The functions asprintf() and vasprintf() are analogues of sprintf() and vsprintf(), except that they allocate a string large enough to hold the output including the terminating null byte, and return a pointer to it via the first parameter. This pointer should be passed to free(3) to release the allocated storage when it is no longer needed. Note that asprintf is a GNU extension, which is also found in various BSD implementations, but it's not in standard C or POSIX.
I'm writing a JSON library for C (seehttps://github.com/DanielWaterworth/Butterfly). I can serialize every other data type, but floating-points have stumped me. I need to write 2 functions: The first takes as an argument the number (as a double) to be serialized and returns the length that the serialized string would be (minus the null terminator).The second takes as arguments the number (as a double) and a buffer (which is at least as long as the output of the previous function). It then writes to the buffer and returns the length of the serialized string. All I need is some helpful hints to get me started.
I have a working implementation usingsnprintfandasprintf. It seems that this is the technique that python'sreprfunction used to use until they moved to a dtoa based approach. I'm still interested in other approaches.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question Anyone knows what is a kinspect? Is it related to somewhere memory leaks? Someone please help me, if you'll know. Thanks in advance
According to google it's a typo'd version ofLinspect
strtok() function uses static variable. Thus it's not re-entrant. and cannot be used to parse multiple strings. What I want to know is why strtok() is designed this way? strtok_r() should have been strtok(). Will this function going to stay in standard library in future?
The function won't change. Backward compatibility is a big thing for standards. Why is the function not reentrant? Well, I wasn't there in the 70s when it was designed, but I assume that reentrency wasn't needed for the use cases it was written. Then its use spread of as it was useful and keeping compatibility was more a desirable than the added flexibility of reentrency. And finally the committee normalized the existing practice and instead of designing a new solution when there was already existing one.
Here is func : ``` char *ToLowerSTR(/*char*/ WCHAR* buffer) // NEED TO FIX UNRESOLVED EXTERNAL { CHAR* str; MultiByteToWideChar(CP_ACP, 0, str, strlen(str) + 1, buffer, sizeof(buffer)/sizeof(WCHAR)); .... return str; } ``` and error : LNK2019: unresolved external symbol "char * __cdecl ToLowerSTR(char *)" (?ToLowerSTR@@YAPADPAD@Z) referenced in function "unsigned long __cdecl GetPID(char *)" ) how can I conver wchar * to char * ?
Your linker is trying to find a function like: ``` char * ToLowerSTR(char *) ``` but you have defined your function to takeWCHARas argument.Look at the declaration of your function and see if it saysWCHAR*orchar*
in threads, i need to periodically do some work in some different intervals, what would be a good way to do this? With sleep(), then i need keep track of the interval to the next wakeup, which doesn't seem to be the best way. thanks.
You can useclock_nanosleepwith theTIMER_ABSTIMEflag to work with absolute times instead of relative times for your sleep. That will avoid error accumulation problems and race conditions where your program gets interrupted and another process scheduled after getting the current time but before calling sleep. Alternatively you could use POSIX timers (timer_create) with a signal handler, where the signal you choose is blocked in all threads but yours, or with timer delivery in a new thread that signals a condition variable or semaphore your thread is waiting on.
This question already has answers here:Closed12 years ago. Possible Duplicate:C/C++: is GOTO faster than WHILE and FOR? I know this has been asked for many times, but I never got an answer which satisfies me by googling. I read somewhere that every loop(for/while/do-while/untill) will be eventually be converted to goto statements internally, Is that True? If not, Which is the best loop to use as per the performance wise? Let me know if anybody knows?
The correct answer is to learn enough assembly in order to read through your compiler's generated code. However, these micro-optimizations usually don't matter (except for very specific areas).
Which of these calls is faster on average? I've heard thatmmapis faster for smaller allocations but I haven't heard a comparison of either. Any information on performance for these would be nice.
You should tag this with a particular implementation (likelinux) since the answer surely varies by implementation. For now I'll assume Linux since it's the most popular. With that said,brkis in theory more optimizable, and in practice it runs about 10% faster on my machine. Allocating one page, these are the times I get: brk: min 2550 cycles, typical 2650 cyclesmmap: min 2700 cycles, typical 2800 cycles I remember hearing something along the lines ofbrkbeing able to skip locking themmapsemaphore, which would explain the discrepancy. Note:I updated these times after adjusting my test to make a dummy calls prior to timing, to ensure that the code would all be in the cache.
I trying to get size of files in a directory by using dirent.h headers. However ``` stat(ent->d_name, &statbuf) ``` returns always -1 and I can't get the size properly. What could be the reason?
d_namecontains the name of the file within that directory.statwants a name including the directory part, unless it's the current directory. Make a temporary string containing the full path to thed_namefile. EDIT: Sample ``` char const * DirName = "/tmp"; .... char * FullName = (char*) malloc(strlen(DirName) + strlen(ent->d_name) + 2); strcpy(FullName, DirName); strcat(FullName, "/"); strcat(FullName, ent->d_name); stat(FullName, &statbuf); free(FullName); ```
pretty simple question I have here, but I couldn't find the answer: Assume I have some conditional clause made up of several conditions. E.g. something like ``` if((a == b && strcmp(string1, string)) || x <= 5) ``` My question is: Will all of those statements be evaluated, no matter what the result of the first ones was, or will the evaluation stop once the result is clear. As I am not sure whether my question is clear, here's an example: ``` if(a == 5 || b > 12 || (c = someFun()) == 3) ``` In this case, if a == 5, no further checks would be required, because the result of the big statement is TRUE, so we could simply continue. This would mean that someFun() would not be evaluated. Is this the case? I know Java makes a difference here between && and & resp. || and | (the latter aren't available in C anyways), but I do not know how C handles this
These operators areshort-circuitingin C (and C++).
In Lex i can start a new state using the keyword BEGIN STATE1. I want to do the same from yacc in between rules . In the action section of a rule , if i add BEGIN STATE1 , it says BEGIN undeclared error. Is there any way i can do this?
Ise Wisteria found the answer for me. Create separate functions in lex that use the BEGIN macro . Call them in bison . Note:For those very beginners like me , do not forget to add a declaration of these functions at the beginning of the .y file or you will get an undeclared error during linking.
``` typedef struct employee { int age; char name[30]; } emp_t; emp_t * e; int main( ) { printf("\nName : "); scanf("%s", &e->name); return 0; } ``` this code compiles but when I try to enter my name such as "mukesh" it throughs out an error Can somebody explain why this is happening In the structure I used char name[] as well as char * name......did't work I don't understandwhy??????? do I need to allocate memory dynamically to the structure employee and then assign it it to e->name
Yes, you must allocate the storage before you can access it. Otherwise you'll just be pointing at some random location in memory. Try this: ``` typedef struct employee { int age; char name[30]; } emp_t; emp_t * e; int main( ) { e = malloc(sizeof(emp_t)); printf("\nName : "); scanf("%s", e->name); return 0; } ```
This question already has answers here:sprintf() with automatic memory allocation?(8 answers)Closed8 years ago. I've heard there is a version ofsprintf(), possibly a GNU/gcc extension which either allocates its own buffer which I mustfree()or perhaps works using the stack likealloca(). Either method is fine for me. Can anyone tell me what function I was thinking of?
You probably meanasprintf? From the man page: Description The functions asprintf() and vasprintf() are analogues of sprintf() and vsprintf(), except that they allocate a string large enough to hold the output including the terminating null byte, and return a pointer to it via the first parameter. This pointer should be passed to free(3) to release the allocated storage when it is no longer needed. Note that asprintf is a GNU extension, which is also found in various BSD implementations, but it's not in standard C or POSIX.
I'm writing a JSON library for C (seehttps://github.com/DanielWaterworth/Butterfly). I can serialize every other data type, but floating-points have stumped me. I need to write 2 functions: The first takes as an argument the number (as a double) to be serialized and returns the length that the serialized string would be (minus the null terminator).The second takes as arguments the number (as a double) and a buffer (which is at least as long as the output of the previous function). It then writes to the buffer and returns the length of the serialized string. All I need is some helpful hints to get me started.
I have a working implementation usingsnprintfandasprintf. It seems that this is the technique that python'sreprfunction used to use until they moved to a dtoa based approach. I'm still interested in other approaches.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question Anyone knows what is a kinspect? Is it related to somewhere memory leaks? Someone please help me, if you'll know. Thanks in advance
According to google it's a typo'd version ofLinspect
strtok() function uses static variable. Thus it's not re-entrant. and cannot be used to parse multiple strings. What I want to know is why strtok() is designed this way? strtok_r() should have been strtok(). Will this function going to stay in standard library in future?
The function won't change. Backward compatibility is a big thing for standards. Why is the function not reentrant? Well, I wasn't there in the 70s when it was designed, but I assume that reentrency wasn't needed for the use cases it was written. Then its use spread of as it was useful and keeping compatibility was more a desirable than the added flexibility of reentrency. And finally the committee normalized the existing practice and instead of designing a new solution when there was already existing one.
Here is func : ``` char *ToLowerSTR(/*char*/ WCHAR* buffer) // NEED TO FIX UNRESOLVED EXTERNAL { CHAR* str; MultiByteToWideChar(CP_ACP, 0, str, strlen(str) + 1, buffer, sizeof(buffer)/sizeof(WCHAR)); .... return str; } ``` and error : LNK2019: unresolved external symbol "char * __cdecl ToLowerSTR(char *)" (?ToLowerSTR@@YAPADPAD@Z) referenced in function "unsigned long __cdecl GetPID(char *)" ) how can I conver wchar * to char * ?
Your linker is trying to find a function like: ``` char * ToLowerSTR(char *) ``` but you have defined your function to takeWCHARas argument.Look at the declaration of your function and see if it saysWCHAR*orchar*
How can we code conditional behaviorwithoutusingifor?(ternary operator) ? One idea comes to mind: ``` for(;boolean_expression;) { // our code break; } ``` Any others ?
I hope what you dont want is just 'if' or 'ternary'. #1 How about this: Instead of :if (condition) printf("Hi"); Use: ``` condition && printf("Hi"); ``` Short circuit evaluation. This is much similar to usingifthough. #2 Forif (condition) a(); else b(); Use: ``` int (*p[2])(void) = {b, a}; (p[!!condition])() ``` Using array of function pointers, and double negation. #3 Yet another variant close to ternary operator (function, though) ``` ternary_fn(int cond, int trueVal, int falseVal){ int arr[2]; arr[!!cond] = falseVal; arr[!cond] = trueVal; return arr[0]; } ``` Use it likeret = ternary_fn(a>b, 5, 3)instead ofret = a > b ? 5 : 3;
Given an input, I want to print a square like this: ``` Enter number: 5 ##### ##### ##### ##### ##### ``` My attempt: ``` int n; int col=0; int row=0; //user input blah blah while (col < n) { while (row < n) { printf("#"); row++; } col++; printf("\n"); } ``` But it isn't printing what I'm expecting... can anyone fix this? EDIT: The actual output looks like this (followed by 4 \n characters, SO doesn't seem to display it). ``` ##### ```
``` while (col < n) { while (row < n) { printf("#"); row++; } col++; printf("\n"); row = 0; // <<< THIS HELPS } ```
Should I use the register keyword on myphonevariable not? I have this: ``` void *anything(Caller *caller) { register void *phone = caller->phone; /* or this */ void *phone = caller->phone; if (phone) { return phone; } return NULL; } ``` Is there a difference? What should I do?
Theregisterkeyword was intended as an optimization hint to the compiler. The problem is, the compiler knows your code better than you do, and these days do not need such simplistic hints to generate better code. So the only thingregisterdoes with modern compilers is prevent you from using&to take the address of the variable. That's it.
i am creating clipped HDC (Device Context) handle using windows api, then sending it to another process. Will be this handle valid for drawing in it?
You will need to expose a method of drawing onto the DC from within your application. The most likely candidates are Windows Messages defined by you (WM_APP or WM_USER). ``` WM_USER + 1, WM_USER + 2, WM_USER + 3, etc... ``` then you would handle those in your applications WNDPROC ``` switch case { WM_USER + 1: // draw a circle WM_USER + 2: // draw a rectangle WM_USER + 3: // draw a snowman } ``` finally from a third party application, they would simple send messages to your application via the SendMessage API: ``` SendMessage(hWndSergey, WM_USER + 1, 0, 0); ``` where the LPARAM and WPARAM can be pointers to global shared memory to exchange parameters or simply dword values etc... http://msdn.microsoft.com/en-us/library/ms644950(v=VS.85).aspx
Does anybody know how variable arguments are passed in classic C? I did some debugging today and most regular arguments are passed via stack. However it seems that this does not apply for variable arguments. Are those parameters stored somewhere else like constant strings? Thanks in advance!
It depends on the platform./usr/include/stdarg.his the place to start looking for details.
I was going through some code at work and I found this ``` inline FLAGS get_flags(void) { FLAGS res; memset(&res, 0, sizeof(res)); return res } ``` This is declared in a header file included in the program. I realize it would be a very bad thing if it was not inlined as this is allocated on the stack. We have never had problems with the code in question, but I was just curious about it.
No, it is not guaranteed to be expanded inline.inlineis merely a hint to the compiler. That said, whileresdoes indeed exist on the stack, youreturn a copy of it. It won't be "a very bad thing" if inline expansion doesn't occur.
I want to implement the factorial algorithm, and the following code gives me wrong result for factorial(5) ``` int factorial(int n) { int i = 1, ret = 1; while(i++<=n) ret *= i; return ret; } ``` Looks like the code will continue to run even when i = 6, I don't understand why the while loop didn't stop.
You are using a post-increment operator which means the final check fori <= nhappens beforeiis incremented for the final time. In other words, wheniis 5 your code: ``` check if i <= 5 -> true increment i -> i is now 6 execute loop -> executes for i = 6 check if i <= 5 -> false (i is now 6) ``` You should change to: ``` while(++i <= n) ```
Is there a way to get the names of all files inside a directory using C?
While C itself does not specify a way (or even specify directories), POSIX does. You can either useopendirandreaddiryourself to read an entry at a time, or you can usescandirorglobto get the results all together in memory (and filter which entries get listed).
I am creating an iPhone app (if that matters) in Objective-C, and I use SQLite storage. I want to sanitize the database inputs to prevent the user from doing something like ``` Robert'); DROP TABLE Students; -- ``` What is the best way to do this in C or Objective-C? I tried replacing'with''but I am sure this is not enough.
The best thing to do is to never, ever, under any circumstances, even in those special cases where you justknowit would be easier but really seriously I mean this DO NOT construct SQL statements by concatenating the parameters values into the statement. Use parameter markers and bind the values to the markers. This isthe wayto avoid SQL injection attacks. Everything else is just so much wasted time and effort because for every N things you think to alter/modify/check for in the parameters typed in by your user somebody is going to think of thing N+1. Share and enjoy.
Using GDB we can set breakpoints and step into the test program. Sometimes on continuing step by step we step into some library file like "malloc.c", which we might not be really interested in looking into the whole file. Can it be possible to skip the whole file? Like is there are command like:skip malloc.clike that? If not, how to achieve it? Thanks in advance
Rather thanstep, why not usenextto go to the next line without stepping into the function call?
What I am trying to do is that I want to read a file using python, and then with the data in the file, create a variable in c/c++(I don't want to read var from the file :) ). Is this possible? If this is possible, then how would you do it? Thank you guys!
MaybeBoost.Pythoncan help. You could expose a C++ function to your Python script. Something like that: ``` void do_sth_with_processed_data(const std::string& data) { // … } BOOST_PYTHON_MODULE(do_sth) { def("do_sth_with_processed_data", do_sth_with_processed_data); } ``` In your Python script you now could have: ``` import do_sth // … do_sth_with_processed_data(my_processed_data) // this calls the c++ function ```
I have a C program which uses a timer, when the timer expires the program does something (sets a flag). My question is: When i set the breakpoints and run the program using GDB, and use "step" to check line by line, does the timer keeps on ticking in the background? or does it halt till i press "s" again (the next step)?
Assuming you usedCLOCK_REALTIME, yes. The timer will keep ticking along and if you spend a bunch of time looking at a single instruction it will send its signal the next time something in your program is executed. You can useCLOCK_THREAD_CPUTIME_IDorCLOCK_PROCESS_CPUTIME_IDin Linux after 2.6.12, but those will probably not get you what you want, since they don't measure wall clock time.
When i creating TThread i can't pass parameters to thread, so i need use global variables or what? I am using Embarcaderos Rad Studio C++ Builder 2010
You have a class derived from TThread, right? Can you just make your class constructor take additional arguments (beyond thebool suspendedone that seems to be common)?
I'm trying to understand how recursion works in C. Can anyone give me an explanation of the control flow? ``` #include <stdio.h> /* printd: print n in decimal */ void printd(int n) { if (n < 0) { putchar('-'); n = -n; } if (n / 10) printd(n / 10); putchar(n % 10 + '0'); } int main() { printd(123); return 0; } ```
The control flow looks like this (where->is a function call) ``` main() └─> printd(123) β”œβ”€> printd(12) β”‚ β”œβ”€> printd(1) β”‚ β”‚ └─> putchar('1') β”‚ └─> putchar('2') └─> putchar('3') ```
I've got a weird one here. strtol, atol and atoi all return an incorrect value when I pass in the following string: ``` long test = strtol("3087663490", &p, 10); ``` According to my debugger it returns 2147483647. I'm completely stumped on this. Any advice?
Your value is larger than what a signedlongtype can represent. Try: ``` unsigned long test = strtoul("3087663490", &p, 10); ``` (You're getting 2147483647 since it isLONG_MAXor 0x7FFFFFFF)
I want to compare two strings. Is it possible withstrcmp? (I tried and it does not seem to work). Isstring::comparea solution? Other than this, is there a way to compare astringto achar? Thanks for the early comments. I was coding in C++ and yes it wasstd::stringlike some of you mentioned. I didn't post the code because I wanted to learn the general knowledge and it is a pretty long code, so it was irrelevant for the question. I think I learned the difference between C++ and C, thanks for pointing that out. And I will try to use overloaded operators now. And by the waystring::compareworked too.
For C++, usestd::stringand compare usingstring::compare. For C usestrcmp. If your (i meant your programs) strings (for some weird reason) aren'tnulterminated, usestrncmpinstead. But why would someonenotuse something as simple as==forstd::string?
Here is my issue, one of the rcvfrom() parameters is a char * and once I got the data from it I want to convert it to a struct. However, the cast is unsuccessful. What am I doing wrong? Here is what I did: ``` struct { int8_t seq; int8_t ack; bool flag; char data[payload]; }r_pckt; //...bunch of codes char *buf = NULL; buf = (char *)malloc (sizeof(char) * MTU); memset(buf, 0, MTU); //... res = recvfrom(socket_fd, buf, MTU, 0,(struct sockaddr *) &cli_addr, (socklen_t *)&cli_len); //.. r_pckt *tmp_pckt = (struct r_pckt *) &buf; ``` And it does not work. Any ideas? Thanks.
``` typedef struct { int8_t seq; int8_t ack; bool flag; char data[payload]; } r_pckt; ``` The above makes r_pckt a type, not a variable. Then, ``` r_pckt *tmp_pckt = (struct r_pckt *) &buf; ``` should be ``` r_pckt *tmp_pckt = (r_pckt *) buf; ```
I'm looking for a C, C++, or Objective-C library that can connect to a MySQL database. I'm aware of libmysqlclient (GPL) and SQLAPI++ (non-GPL). Are there any alternatives besides SQLAPI++ that can be included in a non-GPL project?
The MySQL C connector used to be LGPL (thus, allowing dynamic linking to proprietary code). Oracle has changed the license from LGPL to GPL starting from versions later than 3.23.58. To use a LGPL connector therefore you have the following options: Use the old version (i.e. LGPL) of the MySQL connector:https://mariadb.com/kb/en/mariadb/lgpl-mysql-client-library-32358/Use the MariaDB connector (a fork of the old LGPL MySQL connector):https://mariadb.com/kb/en/mariadb/mariadb-connector-c/Use Qt's database drivers (which are LGPL and have connectors for databases):http://doc.qt.io/qt-4.8/sql-driver.htmlUse Libdrizzle:https://launchpad.net/libdrizzle
I want to know what is best and fastest way of implementing graph data structure and its related algorithms. Adjacency-List is suggested by the book. But I fail to understand for a large graph when I want to find the edge between the two verticesv1andv2 I will have to traverse through the array which will beO(n). Is my understanding correct or there is better approach to get this done.
first of all, it is not O(n). Keep the lists sorted and it will be O(logN). Adjacency list need not be necessarily implemented by a linked list. It's more usual to have an array. Another very popular approach is the adjacency matrixnxnwhere a[i][j] is 1 (or the weight of the edge) if i and j are connected and 0 otherwise. This approach is optimal for dense graphs, which has many edges. For sparse graphs the adjacencly list tends to be better
In the code below (for problem 1-17 in "The C Programming Language", by Kernighan and Ritchie) why doesn't it print the longest line (at the bottom)? ``` #include <stdio.h> #define MAXLINE 1000 #define LONGLINE 10 int getLineLength(char line[], int maxline){ int i, c; for(i = 0; i< maxline-1 && (c = getchar() != EOF) && c != '\n'; i++) line[i] = c; if(c == '\n') { line[i] = c; i++; } line[i] = '\0'; return i; } main() { int len; char line[MAXLINE]; while((len = getLineLength(line, MAXLINE)) > 0) if(len > LONGLINE) printf("The line was over the maxlength\n\t %s", line); return 0; } ```
In your code: ``` (c = getchar() != EOF) ``` This will be evaluated as(c = (getchar() != EOF)), giving the wrong result. What you need is: ``` ((c = getchar()) != EOF) ```
Since C was developed as a general purpose language and is not owned by a private company in general, can the standardization process be explained? I mean how did this standardization process come about?
There is awhole page dedicated to information on the C standard committeeaka JTC1/SC22/WG14. Actually JTC1 is the IT standards group and SC22 is the programming langages standards sub committee and WG14 is the C standards sub sub committee. Also, theHistory section of the C Programming Language on Wikipediais very informative. [update] Here is themost complete history of C I can find from Bell Labs.
In sed source I saw often ``` func(...) int b; char c; { ... } ``` Why put variables there? Does it change the scope? Like here:http://www.mirrors.docunext.com/lxr/http/source/src/bin/sed/lib/regex_internal.c?v=haiku ``` re_string_allocate (pstr, str, len, init_len, trans, icase, dfa) 51 re_string_t *pstr; 52 const char *str; 53 int len, init_len, icase; 54 RE_TRANSLATE_TYPE trans; 55 const re_dfa_t *dfa; 56 { 57 reg_errcode_t ret; 58 int init_buf_len; 59 ```
This is K&R (old) style, it works, but..
I'm using OpenAL as the sound engine for my iPhone game, but still learning how to use it. I managed to play sounds with it, however I'm in one point when I need to concatenate (not merge) 2 sound sources (same file in fact, so this needs no conversion I guess) and I'm stuck. Any help would totally be appreciated:D
I wonder if you landed on this:OpenAL Programmers Guide Try looking intoExtAudioFile.
i write a boolean that checks to see if a point is within a given distance of a filled rectangle the rectangle is defined by its bottom left point and its width and height
Is this homework? Anyway. Assuming you mean proper distance, as in "distance between the closest point to the rectangle": ``` int IsWithinDistance(int pointX, int pointY, int rectX, int rectY, int rectWidth, int rectHeight, int distanceThreshold) { int x2 = rectX + rectWidth; int y2 = rectY + rectHeight; int xDiff = (pointX < rectX) ? rectX - pointX : pointX - x2; int yDiff = (pointY < rectY) ? rectY - pointY : pointY - y2; int distance2; xDiff = (xDiff < 0) ? 0 : xDiff; yDiff = (yDiff < 0) ? 0 : yDiff; distance2 = xDiff * xDiff + yDiff * yDiff; return distance2 < (distanceThreshold * distanceThreshold); } ```
i am trying to allocate memory for a 2 dimensional array using c and i am getting an exception in visual studio 2008. ``` int Count=16383,N=14; char **result=(char**)malloc(sizeof(char)*Count); for(int i=1;i<=Count;i++) result[i] = (char*)malloc(sizeof(char)*N); Unhandled exception at 0x012e1692 in combination.exe: 0xC0000005: Access violation writing location 0x00590000 ``` the exception takes place when i is 11272 and i can't understand why!
``` char **result=(char**)malloc(sizeof(char)*Count); ``` should be ``` char **result=(char**)malloc(sizeof(char*)*Count); ```
I am reading set of numbers from file by fscanf(), for each number I want to put it into array. Problem is that thoose numbers are separated by "," how to determine that fscanf should read several ciphers and when it find "," in file, it would save it as a whole number? Thanks
This could be a start: ``` #include <stdio.h> int main() { int i = 0; FILE *fin = fopen("test.txt", "r"); while (fscanf(fin, "%i,", &i) > 0) printf("%i\n", i); fclose(fin); return 0; } ``` With this input file: ``` 1,2,3,4,5,6, 7,8,9,10,11,12,13, ``` ...the output is this: ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 ``` What exactly do you want to do?
If fopen( path, "w" ) succeeds, then the file will be truncated. If the fopen fails, are there an guarantees that the file is not modified?
No there are no guarantees about the state of a file iffopen(path, "w")fails. The failure could be coming from any operation from opening the file, committing the truncation to disk, etc ... The only guarantee a failure provides is that you don't have access to the file.
I am using the system() function in C to run a system command. While using the system(), the command I am using is: ``` system("C:\splint-3.1.2\bin\splint first.c>output.txt"); ``` However, the output of this is not being correctly sent to the txt file. To be more specific, the txt file is created, however the output is not appended to the file. On running the same command from the CMD, the output is correctly sent to the txt file. Any idea on what's going wrong?
Escape your backslashes so the compiler interprets them correctly: ``` system("C:\\splint-3.1.2\\bin\\splint first.c>output.txt"); ```
I am writing a program which has one process reading and writing to a shared memory and another process only reading it. In the shared memory there is a struct like this: ``` struct A{ int a; int b; double c; }; ``` what I expect is to read the struct at once because while I am reading, the other process might be modifying the content of the struct. This can be achieved if the struct assignment is atomic, that is not interrupted. Like this: ``` struct A r = shared_struct; ``` So, is struct assignment atomic in C/C++? I tried searching the web but cannot find helpful answers. Can anyone help? Thank you.
No, both C and C++ standard don't guarantee assignment operations to be atomic. You need some implementation-specific stuff for that - either something in the compiler or in the operating system.
Given an integer , print the next smallest and next largest number that have the same number of 1 bits in their binary representation After Counting the number of 1's in the number.How to determine the next smallest number?
for next high you can use Hakmem 175 : ITEM 175 (Gosper): To get the next higher number with the same number of 1 bits: ``` unsigned nexthi_same_count_ones(unsigned a) { /* works for any word length */ unsigned c = (a & -a); unsigned r = a+c; return (((r ^ a) >> 2) / c) | r; } ``` For next lower I do not know a fast algorithm so I would use the classic approach, if the number is > then 2^0+2^1+...2^n then deduct one from your number and count the number of bits. The first number with n bits is the one.
Are there working open source implementations of the Kalman filter in C or Objective-C to correct accelerometer data? I couldn't find one, but before I start spending a month on this I'd better ask :-)
No, not that I know of. But don't you want Kalman filter to removegyro drift? That's what it is good for. Kalman filter is difficult to understand. If you do not understand it you won't be able to implement and use it correctly. The good news is that you have other filters with comparable results, you may findthis answerhelpful. See especially thefilter.pdf. If you insist on the Kalman filter, the most human readable intro with examples I have found so far is theSIGGRAPH Course Pack.
I have a fixed size array (example:struct bucket[DATASIZE]) where at the very beginning I load information from a file. Since I am concerned about scalability and execution time, no dynamic array was used. Each time I process half of the array I am free to replace those spots with more data from the file. I don't have a clear idea on how I would do that but I thought about pthreads to start 2 parallel tasks: one would be the actual data processing and the other one would make sure to fill out the array. However, all the examples that I've seen on pthreads show that they are all working on the same task but concurrently. Is there a way to have them do separate things? Any ideas, thoughts?
You can definitely have threads doing different tasks. The pattern you're after is very common - it's called a Producer-Consumer arrangement.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed10 years ago. HI all! I'm currently taking the course Operating Systems in my university. We mainly study theory and have simple exercises in c++ to exercise some theoretical principles. I want to study more about the practical programming in concurrency and threads in c\c++ and i was wondering if any of you have a good book to recommend on. Thank you all
Introduction to parallel computing:https://computing.llnl.gov/tutorials/parallel_comp/POSIX threads programming:https://computing.llnl.gov/tutorials/pthreads/
Is there anything like 'call-by-value result' in c programming? If it exists , what is the difference between 'call-by-value' and 'call-by-value-result'? Or both are same?
call-by-value-result definitionAn argument passing convention where the actual argument is a variable V whose value is copied to a local variable L inside the called function or procedure. If the procedure modifies L, these changes will not affect V, which may also be in scope inside the procedure, until the procedure returns when the final value of L is copied to V. Under call-by-reference changes to L would affect V immediately. Used, for example, by BBC BASIC V on the Acorn Archimedes. Source:http://dictionary.reference.com/browse/call-by-value-result As Oli said, C incorporates call-by-value behaviour.
I want to delete a string from a particular position in the file. Is thre a function to do that? Can I delete last line of a file through a function?
You have two option To read whole file, remove what you need and write it backIf the file is big, read file sequentially, remove given part, and move content after that forward
I have some work to do on the OS-9 platform in C for a college assignment. Problem is, I can only do this work in my project lab. I tend to work better at home, so here's my question. Is there any way of virtualizing an OS-9 environment at home? I realize OS-9 is proprietary, so I'm guessing I'll have to pay to do this (which I can't, but I'll satisfy my curiosity). Any information on OS-9 and 'Ultra C', as I think it's called, would also be greatly appreciated. Thanks guys.
Here is an OS/9 emulatorfor Mac, Windows, and Linux -- that certainly sounds promising.
I have a program that takes console input that I'm trying to debug. Sending an EOF (Ctrl+D in shell) is important to its function; but Ctrl+D doesn't send one in Eclipse's debugger console. This should be super simple, but Google (and my limited experience) yields nothing. Thanks so much for any help!
I just found a solution to this problem: When you finish entering your inputs on console, click on another window (editor, Project Explorer, etc.), then click back on console. HittingCtrl+Zwill work now.
When I use class dump z, I don't get any header files, all I get is this: /** * This header is generated by class-dump-z 0.2-0. * class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3. * * Source: (null) */ But if use class dump 3.3.3, I can get the header files. Is there anything I am missing? In terminal I typed: class-dump-z path-to-file Thanks! For those wondering why I am not using class dump 3.3.3, it's because it screws up with structs and cfobjectrefs
class-dump-z was written for iPhone development and will not work with OS X files. Instead, you get a blank file with no error message. Seethis page.
When i creating TThread i can't pass parameters to thread, so i need use global variables or what? I am using Embarcaderos Rad Studio C++ Builder 2010
You have a class derived from TThread, right? Can you just make your class constructor take additional arguments (beyond thebool suspendedone that seems to be common)?
I'm trying to understand how recursion works in C. Can anyone give me an explanation of the control flow? ``` #include <stdio.h> /* printd: print n in decimal */ void printd(int n) { if (n < 0) { putchar('-'); n = -n; } if (n / 10) printd(n / 10); putchar(n % 10 + '0'); } int main() { printd(123); return 0; } ```
The control flow looks like this (where->is a function call) ``` main() └─> printd(123) β”œβ”€> printd(12) β”‚ β”œβ”€> printd(1) β”‚ β”‚ └─> putchar('1') β”‚ └─> putchar('2') └─> putchar('3') ```
I've got a weird one here. strtol, atol and atoi all return an incorrect value when I pass in the following string: ``` long test = strtol("3087663490", &p, 10); ``` According to my debugger it returns 2147483647. I'm completely stumped on this. Any advice?
Your value is larger than what a signedlongtype can represent. Try: ``` unsigned long test = strtoul("3087663490", &p, 10); ``` (You're getting 2147483647 since it isLONG_MAXor 0x7FFFFFFF)
I want to compare two strings. Is it possible withstrcmp? (I tried and it does not seem to work). Isstring::comparea solution? Other than this, is there a way to compare astringto achar? Thanks for the early comments. I was coding in C++ and yes it wasstd::stringlike some of you mentioned. I didn't post the code because I wanted to learn the general knowledge and it is a pretty long code, so it was irrelevant for the question. I think I learned the difference between C++ and C, thanks for pointing that out. And I will try to use overloaded operators now. And by the waystring::compareworked too.
For C++, usestd::stringand compare usingstring::compare. For C usestrcmp. If your (i meant your programs) strings (for some weird reason) aren'tnulterminated, usestrncmpinstead. But why would someonenotuse something as simple as==forstd::string?
Here is my issue, one of the rcvfrom() parameters is a char * and once I got the data from it I want to convert it to a struct. However, the cast is unsuccessful. What am I doing wrong? Here is what I did: ``` struct { int8_t seq; int8_t ack; bool flag; char data[payload]; }r_pckt; //...bunch of codes char *buf = NULL; buf = (char *)malloc (sizeof(char) * MTU); memset(buf, 0, MTU); //... res = recvfrom(socket_fd, buf, MTU, 0,(struct sockaddr *) &cli_addr, (socklen_t *)&cli_len); //.. r_pckt *tmp_pckt = (struct r_pckt *) &buf; ``` And it does not work. Any ideas? Thanks.
``` typedef struct { int8_t seq; int8_t ack; bool flag; char data[payload]; } r_pckt; ``` The above makes r_pckt a type, not a variable. Then, ``` r_pckt *tmp_pckt = (struct r_pckt *) &buf; ``` should be ``` r_pckt *tmp_pckt = (r_pckt *) buf; ```
I'm looking for a C, C++, or Objective-C library that can connect to a MySQL database. I'm aware of libmysqlclient (GPL) and SQLAPI++ (non-GPL). Are there any alternatives besides SQLAPI++ that can be included in a non-GPL project?
The MySQL C connector used to be LGPL (thus, allowing dynamic linking to proprietary code). Oracle has changed the license from LGPL to GPL starting from versions later than 3.23.58. To use a LGPL connector therefore you have the following options: Use the old version (i.e. LGPL) of the MySQL connector:https://mariadb.com/kb/en/mariadb/lgpl-mysql-client-library-32358/Use the MariaDB connector (a fork of the old LGPL MySQL connector):https://mariadb.com/kb/en/mariadb/mariadb-connector-c/Use Qt's database drivers (which are LGPL and have connectors for databases):http://doc.qt.io/qt-4.8/sql-driver.htmlUse Libdrizzle:https://launchpad.net/libdrizzle
I want to know what is best and fastest way of implementing graph data structure and its related algorithms. Adjacency-List is suggested by the book. But I fail to understand for a large graph when I want to find the edge between the two verticesv1andv2 I will have to traverse through the array which will beO(n). Is my understanding correct or there is better approach to get this done.
first of all, it is not O(n). Keep the lists sorted and it will be O(logN). Adjacency list need not be necessarily implemented by a linked list. It's more usual to have an array. Another very popular approach is the adjacency matrixnxnwhere a[i][j] is 1 (or the weight of the edge) if i and j are connected and 0 otherwise. This approach is optimal for dense graphs, which has many edges. For sparse graphs the adjacencly list tends to be better
In the code below (for problem 1-17 in "The C Programming Language", by Kernighan and Ritchie) why doesn't it print the longest line (at the bottom)? ``` #include <stdio.h> #define MAXLINE 1000 #define LONGLINE 10 int getLineLength(char line[], int maxline){ int i, c; for(i = 0; i< maxline-1 && (c = getchar() != EOF) && c != '\n'; i++) line[i] = c; if(c == '\n') { line[i] = c; i++; } line[i] = '\0'; return i; } main() { int len; char line[MAXLINE]; while((len = getLineLength(line, MAXLINE)) > 0) if(len > LONGLINE) printf("The line was over the maxlength\n\t %s", line); return 0; } ```
In your code: ``` (c = getchar() != EOF) ``` This will be evaluated as(c = (getchar() != EOF)), giving the wrong result. What you need is: ``` ((c = getchar()) != EOF) ```
Since C was developed as a general purpose language and is not owned by a private company in general, can the standardization process be explained? I mean how did this standardization process come about?
There is awhole page dedicated to information on the C standard committeeaka JTC1/SC22/WG14. Actually JTC1 is the IT standards group and SC22 is the programming langages standards sub committee and WG14 is the C standards sub sub committee. Also, theHistory section of the C Programming Language on Wikipediais very informative. [update] Here is themost complete history of C I can find from Bell Labs.
In sed source I saw often ``` func(...) int b; char c; { ... } ``` Why put variables there? Does it change the scope? Like here:http://www.mirrors.docunext.com/lxr/http/source/src/bin/sed/lib/regex_internal.c?v=haiku ``` re_string_allocate (pstr, str, len, init_len, trans, icase, dfa) 51 re_string_t *pstr; 52 const char *str; 53 int len, init_len, icase; 54 RE_TRANSLATE_TYPE trans; 55 const re_dfa_t *dfa; 56 { 57 reg_errcode_t ret; 58 int init_buf_len; 59 ```
This is K&R (old) style, it works, but..
I'm using OpenAL as the sound engine for my iPhone game, but still learning how to use it. I managed to play sounds with it, however I'm in one point when I need to concatenate (not merge) 2 sound sources (same file in fact, so this needs no conversion I guess) and I'm stuck. Any help would totally be appreciated:D
I wonder if you landed on this:OpenAL Programmers Guide Try looking intoExtAudioFile.
i write a boolean that checks to see if a point is within a given distance of a filled rectangle the rectangle is defined by its bottom left point and its width and height
Is this homework? Anyway. Assuming you mean proper distance, as in "distance between the closest point to the rectangle": ``` int IsWithinDistance(int pointX, int pointY, int rectX, int rectY, int rectWidth, int rectHeight, int distanceThreshold) { int x2 = rectX + rectWidth; int y2 = rectY + rectHeight; int xDiff = (pointX < rectX) ? rectX - pointX : pointX - x2; int yDiff = (pointY < rectY) ? rectY - pointY : pointY - y2; int distance2; xDiff = (xDiff < 0) ? 0 : xDiff; yDiff = (yDiff < 0) ? 0 : yDiff; distance2 = xDiff * xDiff + yDiff * yDiff; return distance2 < (distanceThreshold * distanceThreshold); } ```
i am trying to allocate memory for a 2 dimensional array using c and i am getting an exception in visual studio 2008. ``` int Count=16383,N=14; char **result=(char**)malloc(sizeof(char)*Count); for(int i=1;i<=Count;i++) result[i] = (char*)malloc(sizeof(char)*N); Unhandled exception at 0x012e1692 in combination.exe: 0xC0000005: Access violation writing location 0x00590000 ``` the exception takes place when i is 11272 and i can't understand why!
``` char **result=(char**)malloc(sizeof(char)*Count); ``` should be ``` char **result=(char**)malloc(sizeof(char*)*Count); ```
I am reading set of numbers from file by fscanf(), for each number I want to put it into array. Problem is that thoose numbers are separated by "," how to determine that fscanf should read several ciphers and when it find "," in file, it would save it as a whole number? Thanks
This could be a start: ``` #include <stdio.h> int main() { int i = 0; FILE *fin = fopen("test.txt", "r"); while (fscanf(fin, "%i,", &i) > 0) printf("%i\n", i); fclose(fin); return 0; } ``` With this input file: ``` 1,2,3,4,5,6, 7,8,9,10,11,12,13, ``` ...the output is this: ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 ``` What exactly do you want to do?
If fopen( path, "w" ) succeeds, then the file will be truncated. If the fopen fails, are there an guarantees that the file is not modified?
No there are no guarantees about the state of a file iffopen(path, "w")fails. The failure could be coming from any operation from opening the file, committing the truncation to disk, etc ... The only guarantee a failure provides is that you don't have access to the file.
how do you color mask a 32 bit unsigned integer for the red, green, and blue values is it like this? (color_to_be_masked>>8)
This should get you the result you want: ``` short red = (color >> 16) & 0xFF; short green = (color >> 8) & 0xFF; short blue = (color) & 0xFF; ```
here is my problem: In C, I create the copy of a file (with some changes) This is done trivially via fopen(), getchar and putchar. Copying the file is fine and the outputfile itself is what I want it to be. My problem is: I assume that I will use this program often as sudo and then the resulting file has both another owner (root) as well as different permissions (execute rights are gone). My question is: How can I copy the owner and permissions of the original file and then write them into the new one?
Use thefstat(2) system call to obtain the details about the owner and the permissions, and thefchmod(2) andfchown(2) system calls to set them. See an example in thesetfilefunction of the *BSDcp(1)source code.
I need to know if I can access internet from my proxy, I'm doing this now: ``` if((system("wget -q www.google.it -O /dev/null")); // I don't have access. ``` Is there a better way to solve this problem? Is there a function in C? Thank you very much.
Everyone loves this guide. http://beej.us/guide/bgnet/ It'll help you learn how to get to grips with networking programming in C very easily.
i am working in C and want to open a simple text file then perform some processing over it. My code looks like ``` FILE *pFile; pFile = fopen("d:\\series.txt", "r"); if (pFile == NULL) { printf("File not found or Unable to open file\nPress any key to continue . . ." ); getch(); return; } else { //process here } ``` every time the condition becomes true if (pFile == NULL) so i am not able to perform processing on file. I check that file exist in my drive with same name and its open properly when i double click on it
Try putting this inside theifblock: ``` perror(NULL); ``` That should give a descriptive error message, so you know what went wrong.
Is there any difference between the computation of small floats - that are close to 0 - and big floats - that are far from 0?
As far as I understand how processors work, there should be absolutely no difference at all
I got this code inside a small program to read a file: ``` #ifdef WIN32 unsigned char *buffer = (unsigned char *)alloca((unsigned int)ui.length); #else unsigned char buffer[ui.length]; #endif ``` Why is a pointer used for Win32 platform and character array for other platforms?
It seems previously to C99 defining a variable length array on the stack was not supported. alloca essentially does this. Seems this programmer had a WIN32 compiler that didn't support VLA's so was using (the well-supported but non-standard) alloca. More on this in stack overflow:Why is the use of alloca() not considered good practice?and this rather useful array summaryhttp://www.programmersheaven.com/2/Pointers-and-Arrays-page-2mentioned by Arthur on the stack overflow post.
This question already has answers here:Closed12 years ago. Possible Duplicate:Difference between WIN32 and other c string I got this code inside a small program to read a file ``` #ifdef WIN32 unsigned char *buffer = (unsigned char *)alloca((unsigned int)ui.length); #else unsigned char buffer[ui.length]; #endif ``` Can anybody tell me , why pointer used for win32 platform and character array for other platform?
The code intended to declare an array of length not known at compile time. It was likely written with the assumption that C++ compilers for Windows targets don't support declaring such arrays (for example, Visual C++ doesn't support that). So when compilation is done for Windows targetsalloca()function is used to achieve the same effect.
In case a system call function fails, we normally use perror to output the error message. I want to use fprintf to output the perror string. How can I do something like this: ``` fprintf(stderr, perror output string here); ```
``` #include <errno.h> fprintf(stderr, "%s\n", strerror(errno)); ``` Note: strerror doesn't apply\nto the end of the message
I have been attempting to use the GNU mailutils library but have had no end of problems just getting it installed and in a state of doing the email equivalent of 'Hello world'. I am also less than impressed with the documentation. Could anyone suggest an alternative C library to read and delete local emails on a Fedora system?
The UW-IMAP c-client works for me.http://www.washington.edu/imap/ It has some fairly good documentation, although the formatting/presentation could be better ...
Is it possible to put arguments in a systems call? something like ``` system("rm %s %s", string1, string2) ```
The prototype for thesystemfunction is: ``` int system(const char *command); ``` so, no. But, how about: ``` snprintf(buffer, sizeof(buffer), "rm %s %s", target1, target2); system(buffer); ```
In c program, I want run c++ library function(s), but I don't know how can I do that. Like ever c++ programmer, I know how to use c program under c++ prog. therefore, I wonder it is possible using c++ library function, namely cout, vector etc., in c ?
Generally, you cannot use C++ facilities in C. However, a C++ library may choose to export some of its functionality to C programs, by declaring themextern "C". If your C++ library doesn't do this, you will have to write some wrappers (in C++) that do this. Note that such exported functionality have to conform to C's limitations. For example, you can't use non-POD types, function overloading, operator overloading, conversion operators, RTTI, exceptions, templates, etc.
I'm trying to do something fairly simple. Of course it could be done with an extra line of code, but technically speaking, why does this not work? int foo = 5; int *bar = &(--foo); GCC compiler tells me"invalid lvalue in unary &"
Because--foois not an lvalue (so named since they typicaly appeared on the left of an asignment). It's the same problem with: ``` --foo = 7; ``` If, for some bizarre reason, you need it on one line, just use: ``` --foo; int *bar = &foo; ``` If you think you need it in oneinstruction,think again. Even if you make such a horrible monstrosity(a), it will probably compile down to the same machine language sequence as that code snippet above. (a)int *bar = (--foo, &(foo));
I am trying to use a open source library under C++. The README file states that You need to link your program with `svm.cpp'. I am wondering how to link my program with svm.cpp? Do I need to modify the make file to make this happen?
Compilesvm.cppwith not linking, will resultsvn.oobject file, use it object file with your program linking.
I'm using a Python library (SimpleParse) that I seem to be causing some runaway recursion with it. It's already crashed my computer once when I was just trying to debug it. What would be the best way for me to set some limits on how much memory it's using? I was thinking I would write up a quick C program withsetrlimitto call Python, and test it from there.
Python providessetrlimit(), so you can stay in Python. (Unless you're happier in C :) Note that the Linux kernel hasn't supported the RSS accounting in a long time; the address space accounting is probably your best bet, but it might be overly restrictive. (If the programmmap(2)s a few gigabytes but never bothers reading or writing it, it won't really matter; the rlimits might forbid themmap(2), rather than forbid actuallyusingthe memory.)
``` #include <stdio.h> int main(int argc, char *argv[]) { printf("remove %s\n", argv[0]); remove(argv[0]); printf("rename %s to %s\n", argv[1], argv[2]); rename(argv[1], argv[2]); } $g++ hello.cpp -o hello $touch tmp $./hello tmp temp remove ./hello rename tmp to temp ``` Why is it possible?
In Unix at least (and that includes Linux and Mac OS X), if you remove a file while somebody has it open, i doesn't actually go away until the program that had it open either closes the file or terminates.
Quite a basic question but can someone tell me the difference between downloading src files against downloading binary files?
Source files are uncompiled C/C++ code, while binary files are the compiled programs.
I would like to check if a number is larger than 0. The 0 is in string format How do I either Compare the value to a string representation of 0Cast the string to an int
strtol()
I have parsed a basic xml document with the following format ``` <?xml version="1.0"?> <data> <title>sometitle</title> <keyword>example keyword</keyword> <body> <headline>headline</headline> <para>body text.</para> </body> </data> ``` and it works correctly. My issue is trying to access data within a single< >like so ``` <tileset firstgid="1" name="testSet" tilewidth="20" tileheight="20" spacing="1" margin="1"> <image source="Tile.png" width="265" height="199"/> </tileset> ``` How does one access e.g. 1 from firstgid or testSet from name ?
Those are attributes and you would use@within your xpath: ``` /tileset/@firstgid ``` or ``` /tileset/@name ```
If I want to compile a c source file that uses libxml, how do I setup libxml on mac osx so that my source file will just compile correctly and be ready to run? I have been using XCode until now, but have switched to TextMate & Terminal, Do I need to create a makefile if I want to use libxml or how will this work? Thanks EDIT: I use the current imports ``` #include <libxml/xmlmemory.h> #include <libxml/parser.h> ```
The headers for the libxml2 distribution on 10.6 resides within/usr/include/libxml2/. Unfortunately, just the/usr/includepart is within the system default header search path. Thus, you need to explicitly include it on the command line (or have your#includesalso include the additional libxml2 folder). The library itself resides at the usual/usr/lib/libxml2.dylib. Thus, use the following command to compile your program: ``` gcc source.c -I/usr/include/libxml2 -lxml2 -o output ```
I am thinking about developing an application that will, on a six core machine, run six asynchronous tasks, one on each core. But is it possible to lock the tasks to their own core? The idea is for them to run mostly by themselves, but to sometimes communicate over a shared memory area. However, I want the tasks to run as undisturbed as possible.
The concept you're looking for is called "thread affinity". How it's implemented and the interfaces to ask for it are OS-specific. Under Linux, trysched_setaffinity(). glibc may also offer pthread_attr_setaffinity_np().
How does select work with gpio under Linux? Is it possible to use select to create a kind of interrupt driven program, maybe with the help of some threads? And what shall I think about when I use the select call? Thanks Note: I have read the man page on select, but I think I need some more help on this topic. man 3posix selectman 2 selectman 2 select_tut Update: The gpio is exposed in the sysfs gpio block. But I don't know if I can use that with select.
Apparently you can use select() on a GPIO exposed through sysfs, but only if it can be configured to generate an interrupt. Your platform may have this or not. What you want to read though is Documentation/gpio.txt in your kernel source, which mentions how to enable an interrupt for a pin if the kernel driver allows it.
When I try to compile the piece of code below, I get this warning: warning: suggest parentheses around assignment used as truth value Why does this happen? This is a rather common idiom, I believe. I even use something like it earlier on my code. ``` struct PIDList* getRecordForPID(struct PIDList* list, pid_t pid) { while(list = list->next) if (list->pid == pid) return list; return NULL; } ```
Be explicit - then the compiler won't warn that you perhaps made a mistake. ``` while ( (list = list->next) != NULL ) ``` or ``` while ( (list = list->next) ) ``` Some day you'll be glad the compiler told you, peopledomake that mistake ;)
How do i change the c coding style format in emacs ? Specifically i need to change the indentation in the c code shown by emacs from i per block to 2 per block
Type M-x followed by "customize-mode" followed by "c-mode". Then use the built-in customization page to override the default "C Basic Offset" with your new value of "2". When you're done, be sure to select "Save for future sessions" at the top of the page.