question
stringlengths
25
894
answer
stringlengths
4
863
forkandpthread_createwill return a process id or thread id. But I don't know the value range of these ids. Now I want to make a lookup table, in each entry there is a item/field for thread id. the structure of each entry is like: ``` typedef struct { int seq; pthread_t tid; ... } entry_t; ``` I want to a...
Thepthread_ttype is completely opaque. You can only compare it for equality with thepthread_equalfunction, and there is no reserved value distinct from any valid thread id, though such a value will probably be added to the next version of the POSIX standard. As such, you'll need to store a second field alongside the t...
I am having trouble getting a simple pass by reference to work the way I expect. Fist off, when I compile, I get the following warning: ``` warning: value computed is not used [-Wunused-value] ``` Second, I expect it to print a 2, not a 1 at the end of the program. ``` $ ./testAdd 1 ``` Here is the simple code: ...
Operator precedence. The increment operator binds more tightly than the dereference operator, so your code is semantically equivalent to: ``` *(j++) // invalid read BTW ``` When you wanted ``` (*j)++ ``` Also note that C has no notion of pass by reference; everything is pass by value. You're passing the address...
I have a large file (say 10 terabytes) with stream of MD5 hashes (which contains duplicates), I am given a memory of 10MB(very limited) and unlimited hard disc space. Find all the unique hashes(eliminating duplicates) using given conditions. Please help, this is obviously not a homework question
You can sort the hashes with an external sorting algorithm (e.g. with apolyphase merge sort), after which you just need to traverse the file and skip any hashes that equal the most recent hash ``` hash mostRecentHash; while(fileHasHashes) { temp = fileWithDuplicates.readHash(); if(!hashesAreEqual(mostRecentHa...
What's wrong with this code? ``` #include "stdio.h" typedef int type1[10]; typedef type1 *type2; typedef struct { int field1; type2 field2; } type3; typedef type3 type4[5]; int main() { type4 a; a[0].(*field2[3]) = 99; // Line 16 return 0; } ``` Getting:main.c:16:10: error: expected identif...
The compiler error tells youexactlywhat's wrong: expected identifierbefore <(> token You can only access structure members using their name (which is an identifier), not by some arbitrary expression.
I was using a nested while loop, and ran into a problem, as the inner loop is only run once. To demonstrate I've made a bit of test code. ``` #include <stdio.h> int main(){ int i = 0; int j = 0; while(i < 10){ printf("i:%d\n", i); while(j < 10){ printf("j:%d\n", j); j++; } i++; } } `...
You never reset the value ofjto0, and as such, your inner loop condition is never true after the first run. Assigningj = 0;in the outer loop afterward should fix it.
Is there any way to have gcc issue warnings for implicit enum to int (or vice versa) conversion in C (notC++). I find that the implicit conversions can be a little bit sloppy, and I spend a long time tracking down a bug I caused which was related to this.
In C there is no implicit conversion warning because the constants of anenumby definition of the language are of typeintnot of theenumtype. If you'd have the compiler warn on these things you would have a warning in the second line but not the third: ``` enum things { thing }; //< declaration of a constant of t...
This question already has answers here:C++ simple sizeof difference between char array and char pointer(4 answers)Closed10 years ago. ``` char *str1 = "pupupupu"; char str2[] = "pupupupu"; printf("%s\t%d\n", str1, (int)sizeof(str1)); printf("%s\t%d\n", str2, (int)sizeof(str2)); ``` Output: ``` pupupupu 8 pupupu...
sizeof(str1)is size of char pointer where assizeof(str2)gives size of array that is string length (pupupupu) + 1 Read my this answer, its not exactly same but help you much:What does sizeof(&arr) returns?
Why is answer of it ``` -1, 2, -3 ? (especially -3 ??? how come) struct b1 { int a:1; int b:3; int c:4; } ; int main() { struct b1 c = {1,2,13}; printf("%d, %d, %d",c.a,c.b,c.c); return 0; } ``` Compiled on VC++ 32 bit editor. Many Thanks.
signed integers are represented in twos complement. The range of a 1-bit twos complement number is -1 to 0. Because the first bit of a twos complement number indicates it is negative, which is what you have done there. See here:sign extend 1-bit 2's complement number? That is the same for the third number, you have ...
``` printf("Hello%cWorld\n", '\r'); ``` Outputs: ``` World ``` Because'\r'moves the cursor to the beginning of the line Can I trust that all terminals have this behavior?
lib curses will tell you the capabilities of your terminal.
I am dying here. So I have a complex number(-4.9991 + 15.2631i). In matlab if I do ``` angle(-4.9991 + 15.2631i) = 1.8873 ``` I thought that angle basically calculated like ``` atan(15.2631/-4.9991) = -1.2543 ``` Why are these different? I need to write a c function that calculates the angle of a complex number...
``` -1.2543 + Pi(radians) = 1.8873 (with rounding) ``` As pointed out by others, useatan2()
I recently faced an interview question on what's the hidden problem with the following code. I was unable to detect it .Can anyone help? ``` #include<stdio.h> int main(void) { char buff[10]; memset(buff,0,sizeof(buff)); gets(buff); printf("\n The buffer entered is [%s]\n",buff); return 0; } ``...
The functiongetsaccepts a string from stdin and does not check the capacity of the buffer.This may result in buffer overflow. The standard functionfgets()can be used here.
I created a 2D character array using malloc and have been trying to assign its values to '\0'. ``` char **predicate_array = malloc(no_of_lines_in_data_map); for(int i = 0; i < no_of_lines_in_data_map; i++){ predicate_array[i] = malloc(1024 * sizeof(char)); predicate_array[i][0] = '\0'; } ``` However, when I ...
the parameter of the first malloc don't fit your 2d-array. fix it as below ``` char **predicate_array = (char **)malloc(no_of_lines_in_data_map*sizeof(char *)); ```
I am attempting to convert a negative angle (in degrees) to positive. But I am getting a compile error saying: test.cpp invalid operands of types 'double' and 'int' to binary 'operator%'test.cpp invalid operands of types 'float' and 'int' to binary 'operator%' My code: ``` double to_positive_angle(double angle) { ...
This version works for all possible inputs, not just ones greater than 3600000, and solves the%issue you were experiencing. ``` double to_positive_angle(double angle) { angle = fmod(angle, 360); if (angle < 0) angle += 360; return angle; } ```
forkandpthread_createwill return a process id or thread id. But I don't know the value range of these ids. Now I want to make a lookup table, in each entry there is a item/field for thread id. the structure of each entry is like: ``` typedef struct { int seq; pthread_t tid; ... } entry_t; ``` I want to a...
Thepthread_ttype is completely opaque. You can only compare it for equality with thepthread_equalfunction, and there is no reserved value distinct from any valid thread id, though such a value will probably be added to the next version of the POSIX standard. As such, you'll need to store a second field alongside the t...
I am having trouble getting a simple pass by reference to work the way I expect. Fist off, when I compile, I get the following warning: ``` warning: value computed is not used [-Wunused-value] ``` Second, I expect it to print a 2, not a 1 at the end of the program. ``` $ ./testAdd 1 ``` Here is the simple code: ...
Operator precedence. The increment operator binds more tightly than the dereference operator, so your code is semantically equivalent to: ``` *(j++) // invalid read BTW ``` When you wanted ``` (*j)++ ``` Also note that C has no notion of pass by reference; everything is pass by value. You're passing the address...
I have a large file (say 10 terabytes) with stream of MD5 hashes (which contains duplicates), I am given a memory of 10MB(very limited) and unlimited hard disc space. Find all the unique hashes(eliminating duplicates) using given conditions. Please help, this is obviously not a homework question
You can sort the hashes with an external sorting algorithm (e.g. with apolyphase merge sort), after which you just need to traverse the file and skip any hashes that equal the most recent hash ``` hash mostRecentHash; while(fileHasHashes) { temp = fileWithDuplicates.readHash(); if(!hashesAreEqual(mostRecentHa...
What's wrong with this code? ``` #include "stdio.h" typedef int type1[10]; typedef type1 *type2; typedef struct { int field1; type2 field2; } type3; typedef type3 type4[5]; int main() { type4 a; a[0].(*field2[3]) = 99; // Line 16 return 0; } ``` Getting:main.c:16:10: error: expected identif...
The compiler error tells youexactlywhat's wrong: expected identifierbefore <(> token You can only access structure members using their name (which is an identifier), not by some arbitrary expression.
I was using a nested while loop, and ran into a problem, as the inner loop is only run once. To demonstrate I've made a bit of test code. ``` #include <stdio.h> int main(){ int i = 0; int j = 0; while(i < 10){ printf("i:%d\n", i); while(j < 10){ printf("j:%d\n", j); j++; } i++; } } `...
You never reset the value ofjto0, and as such, your inner loop condition is never true after the first run. Assigningj = 0;in the outer loop afterward should fix it.
Is there any way to have gcc issue warnings for implicit enum to int (or vice versa) conversion in C (notC++). I find that the implicit conversions can be a little bit sloppy, and I spend a long time tracking down a bug I caused which was related to this.
In C there is no implicit conversion warning because the constants of anenumby definition of the language are of typeintnot of theenumtype. If you'd have the compiler warn on these things you would have a warning in the second line but not the third: ``` enum things { thing }; //< declaration of a constant of t...
If I want to accept a connection I callaccept, but how can I refuse a connection? In a working socket echo client I have this if statement. In the echo server, how can I make the echo client reach thisprintfstatement? ``` ... if (connect(sock, (struct sockaddr *) &server, sizeof(server)) < 0) { printf("Connecti...
To get the behavior you want (only accept one connection at a time, other clients attempting should get a failure), there are two choices. You can close your listen socket after you have accepted a connection. Re-create your listen socket after the accepted connection closes.You can close newly established connection...
I have a C project compiled with a set of makefiles. I would like to do continuous integration of this project. Do you know a tool such as Jenkins I can use for my C project?
Jenkins can do anything. It's written in Java, but it's not restricted to Java projects at all. You can invoke tools like ant or maven, but you could also have a project that purely uses bash or other shell tools. This gives you the flexibility to do practically anything, as long as the tools you want to use are ins...
Suppose I have 8-bits (mono and stereo).wavfiles. When processing of this file I have to declare pointer to array of samples. Suppose I create array for samples. Then if it ismono, I read each sample usingfor(i = 0; i < n; i++ ). Q: How can I access right and left channels separately (stereo)? PS I've read a lot a...
You still have array of samples, the question is how you address individual values. This is how you do it: ``` const UCHAR* pnSamples = ... if(bMono) { for(INT nIndex = 0; ...) { const UCHAR nSample = pnSamples[nIndex]; // ... } } else if(bStereo) { for(INT nIndex = 0; ...) { const UCHAR nLeftSa...
Is there any C function to check if string s2 exists in s1? s1: "CN1 CN2 CN3" s2: "CN2" or "CG2" s1 is fixed, and I want to check whether variants of s2 exists in s1 or not. I am using C not C++.
You can usestrstr: ``` #include <string.h> if (strstr(s1, s2) != NULL) { // s2 exists in s1 } ```
as in the following code: ``` typedef struct list { ... ... struct Data *data; } List; List* list = (List*)malloc(sizeof(List)) struct Data* data = (struct Data*) malloc(sizeof(struct Data)); .....// here fill the `data` list->data = data; .... struct Data* new_data = list->data; free(list); /* my questi...
The contents ofnew_datawill not be affected. It will still be valid after the "parent" data is freed.
This question already has answers here:What does an assignment return?(5 answers)Closed4 years ago. In the following code: ``` int c; while((c=10)>0) ``` What doesc = 10evaluate to? Is it 1 which indicates that the value 10 is assigned to variable c successfully, or is it 10? Why?
c = 10 is an expression returning 10 which also assigns 10 to c.
How will an expression of the forma/b/c/dbe evaluated in gcc ? Will it be(a*d) / (b*c)or will it be( ( (a/b) / c) / d )? Is there a rule for this in C standard ?
The C standard (and the C++ standard) says that operators are evaluated from left to right once priority is decided. The compiler MAY optimize the operations if it knows this can be done without affecting the actual result, but it would be invalid if the result [within the defined behaviour of the standard] is affecte...
I am working on a C program (under Linux ) that relies on shared libraries as plugins. I provide each plugin with several functions from a static library of mine. In order to change the workflow of my program, I need to know at runtime whether a plugin is going to call a certain function included from the aforementio...
You can tryLibELFwhich allows you to manipulate ELF binaries (i.e. read sections). Very nice examples you can findhere.
I need to parse table of mounted filesystems without using /proc/mounts since I'm parsing it to determine where proc file system is mounted. How can I do it? I've googled it, but all answers was to use /proc And why people are so sure that procfs is mounted to default place? I'm asking out of curiosity. I underst...
Look in /etc/mtab, it keeps track of mounted file systems.
I've been curious howremin Linux works and trying to write my ownCcode that can delete a file but when I searched for the answer, I only got the programs that were usingremove()system call. Is there any other way of doing it without using system call like writing your own code to do the job? I've accomplished copyin...
``` int unlink (const char *filename) ``` The unlink function deletes the file name filename. The function unlink is declared in the header file unistd.h. This function returns 0 on successful completion, and -1 on error
I have created a Window and then, created 50 buttons on this Window but I can only see 10 buttons on my window. Rest are out of view since I am not able to scroll the window down. I have added auto scroll to window by adding WS_VSCROLL | WS_HSCROLL | ES_AUTOVSCROLL | ES_AUTOHSCROLL toWindow Styleparameter ofCreateW...
you will have to handle WM_VSCROLLand WM_HSCROLL messages.
I know that a NULL pointer is(void*)0.But what happens when we use statements like the following: ``` if(ptr==NULL) ``` whereptrcan be achar,floatorintpointer?IsNULLguaranteed to be implicitly converted to the type on the left just as, for example, in C, the type returned bymalloc()isvoid*but is implicitly converted...
Is NULL guaranteed to be implicitly converted to the type on the left? [...] Yes. According to section 6.3.2.3.4 of theISO/IEC 9899:2011 C programming language standard: Conversion of a null pointer to another pointer type yields a null pointer of that type. Any two null pointers shall compare equal. and to sect...
This question already has answers here:How does the Comma Operator work(9 answers)C++ What does 'int x = (anyInt1, anyInt2);' mean? [duplicate](2 answers)Closed10 years ago. I've just come across code that essentially does the following: ``` int a = (1, 2, 3); ``` I've never seen this notation before. What does it ...
This is thecomma operator: evaluation ofa, bfirst causesato be evaluated, thenb, and the result is that ofb. int a = (1, 2, 3);first evaluates1, then2, finally3, and uses that last3to initialisea. It is useless here, but it can be useful when the left operand of,has side effects (usually: when it's a function call).
Is there a function equivalent togit diff FILEinlibgit2? In other words, how to efficiently retrieve the diff of asinglefile without havinglibgit2to look at other files in the working directory?
git diff FILEwill display the changes you've made relative to the index. This can be achieved through the use of the libgit2git_diff_index_to_workdir()function. This function accepts agit_diff_optionsstructure as a parameter into which you can provide a pathspec, or a list of pathspecs, you're specifically intereste...
I wrote an ArduinosketchforArduino UnoRev3 to monitor temperature and electrical current. My Arduino 'crashes' after 6+ hours. After resetting the Arduino, it runs well again. Did I write something that cause this problem in my code? Code, at pastebin http://pastebin.com/1G8SwHge
Well, for one thing, you're overflowing your string buffers. You've assigned 15 bytes forcc ``` char cc[15]; ``` But you have code: ``` strncat(cc,o,20); strncat(cc,"|",20); strncat(cc,m,20); strncat(cc,"|",20); strncat(cc,n,20); ``` That could put up to 62 bytes in there. The same is true for most of your ot...
Can some one explain why the output of program is 0 1 1 3 1 ``` void main(void) { int i=-1,j=0,k=1,l=2,m; m=i++&&j++&&k++||l++; printf("%d %d %d %d %d",i,j,k,l,m); } ``` Main concern is "why k is not incremented". FYI..I am compiling the program in VC++ editor Windows 7 32 bit. Many Thanks in ...
Roughly: To evaluatei++&&j++, compiler evaluatedifirst. The result is-1.-1is stored in a temporary variable. Thenigot incremented. Because-1is not zero, compiler evaluatedj, which is0. Compiler now evaluated-1 && 0, which is0. Thenjgot incremented. At this point,i = 0andj = 1. Remaining expression:m=0&&k++||l++; T...
On the internet I have found that there are OpenGL extensions for AMD and NVIDIA to get the memory information of the graphics card. Now I'm trying to get the total video memory size but I'm always getting 0 as a result. This is the current version of my code: ``` #include <GL/gl.h> #include <stdio.h> int main() { ...
You should always check withglGetError()if a call seems to be failing. In your case, I think you need a validOpenGL contextbefore you can call OpenGL functions.
I don't understand why this works: ``` void main() { int * b; b = (int *)malloc(sizeof(int)); *b = 1; printf("*b = %d\n", *b); } ``` while this does not (gets segmentation fault for themalloc()): ``` void main() { int ** a; int i; for (i = 0; i<= 3; i++) { a[i] = (int*)mal...
You need to allocate memory forafirst, so that you can access its members asa[i]. So if you want to allocate for 4int *do ``` a = malloc(sizeof(int *) * 4); for (i = 0; i<= 3; i++) { ... } ``` or define it as array of integer pointers as ``` int *a[4]; ```
I want to store all the MAC the mac address which has access to my server. All I know are only the IP addresses. All the machines are under unique gateway. Could I got the MAC address from their IP address?
MAC addresses are not part of any protocol that gets routed, you will never get the MAC address of a machine that is on the other side of a router or switch. They are are the addresses of the physical ports, not of machines (which are what you're taling to using IP).
I wrote a program, where the size of an array is taken as an input from user. ``` #include <stdio.h> main() { int x; scanf("%d", &x); int y[x]; /* some stuff */ } ``` This program failed to compile on my school's compilerTurbo C(an antique compiler). But when I tried this on my PC with GNU CC, it com...
It is a valid C program now, but it wasn't 15 years ago. Either way, it's a buggy C program becausexis used without any knowledge of how large it might be. The user can input a malicious value forxand cause the program to crash or worse.
I need to parse table of mounted filesystems without using /proc/mounts since I'm parsing it to determine where proc file system is mounted. How can I do it? I've googled it, but all answers was to use /proc And why people are so sure that procfs is mounted to default place? I'm asking out of curiosity. I underst...
Look in /etc/mtab, it keeps track of mounted file systems.
I've been curious howremin Linux works and trying to write my ownCcode that can delete a file but when I searched for the answer, I only got the programs that were usingremove()system call. Is there any other way of doing it without using system call like writing your own code to do the job? I've accomplished copyin...
``` int unlink (const char *filename) ``` The unlink function deletes the file name filename. The function unlink is declared in the header file unistd.h. This function returns 0 on successful completion, and -1 on error
I have created a Window and then, created 50 buttons on this Window but I can only see 10 buttons on my window. Rest are out of view since I am not able to scroll the window down. I have added auto scroll to window by adding WS_VSCROLL | WS_HSCROLL | ES_AUTOVSCROLL | ES_AUTOHSCROLL toWindow Styleparameter ofCreateW...
you will have to handle WM_VSCROLLand WM_HSCROLL messages.
I know that a NULL pointer is(void*)0.But what happens when we use statements like the following: ``` if(ptr==NULL) ``` whereptrcan be achar,floatorintpointer?IsNULLguaranteed to be implicitly converted to the type on the left just as, for example, in C, the type returned bymalloc()isvoid*but is implicitly converted...
Is NULL guaranteed to be implicitly converted to the type on the left? [...] Yes. According to section 6.3.2.3.4 of theISO/IEC 9899:2011 C programming language standard: Conversion of a null pointer to another pointer type yields a null pointer of that type. Any two null pointers shall compare equal. and to sect...
This question already has answers here:How does the Comma Operator work(9 answers)C++ What does 'int x = (anyInt1, anyInt2);' mean? [duplicate](2 answers)Closed10 years ago. I've just come across code that essentially does the following: ``` int a = (1, 2, 3); ``` I've never seen this notation before. What does it ...
This is thecomma operator: evaluation ofa, bfirst causesato be evaluated, thenb, and the result is that ofb. int a = (1, 2, 3);first evaluates1, then2, finally3, and uses that last3to initialisea. It is useless here, but it can be useful when the left operand of,has side effects (usually: when it's a function call).
Is there a function equivalent togit diff FILEinlibgit2? In other words, how to efficiently retrieve the diff of asinglefile without havinglibgit2to look at other files in the working directory?
git diff FILEwill display the changes you've made relative to the index. This can be achieved through the use of the libgit2git_diff_index_to_workdir()function. This function accepts agit_diff_optionsstructure as a parameter into which you can provide a pathspec, or a list of pathspecs, you're specifically intereste...
I wrote an ArduinosketchforArduino UnoRev3 to monitor temperature and electrical current. My Arduino 'crashes' after 6+ hours. After resetting the Arduino, it runs well again. Did I write something that cause this problem in my code? Code, at pastebin http://pastebin.com/1G8SwHge
Well, for one thing, you're overflowing your string buffers. You've assigned 15 bytes forcc ``` char cc[15]; ``` But you have code: ``` strncat(cc,o,20); strncat(cc,"|",20); strncat(cc,m,20); strncat(cc,"|",20); strncat(cc,n,20); ``` That could put up to 62 bytes in there. The same is true for most of your ot...
Can some one explain why the output of program is 0 1 1 3 1 ``` void main(void) { int i=-1,j=0,k=1,l=2,m; m=i++&&j++&&k++||l++; printf("%d %d %d %d %d",i,j,k,l,m); } ``` Main concern is "why k is not incremented". FYI..I am compiling the program in VC++ editor Windows 7 32 bit. Many Thanks in ...
Roughly: To evaluatei++&&j++, compiler evaluatedifirst. The result is-1.-1is stored in a temporary variable. Thenigot incremented. Because-1is not zero, compiler evaluatedj, which is0. Compiler now evaluated-1 && 0, which is0. Thenjgot incremented. At this point,i = 0andj = 1. Remaining expression:m=0&&k++||l++; T...
On the internet I have found that there are OpenGL extensions for AMD and NVIDIA to get the memory information of the graphics card. Now I'm trying to get the total video memory size but I'm always getting 0 as a result. This is the current version of my code: ``` #include <GL/gl.h> #include <stdio.h> int main() { ...
You should always check withglGetError()if a call seems to be failing. In your case, I think you need a validOpenGL contextbefore you can call OpenGL functions.
I don't understand why this works: ``` void main() { int * b; b = (int *)malloc(sizeof(int)); *b = 1; printf("*b = %d\n", *b); } ``` while this does not (gets segmentation fault for themalloc()): ``` void main() { int ** a; int i; for (i = 0; i<= 3; i++) { a[i] = (int*)mal...
You need to allocate memory forafirst, so that you can access its members asa[i]. So if you want to allocate for 4int *do ``` a = malloc(sizeof(int *) * 4); for (i = 0; i<= 3; i++) { ... } ``` or define it as array of integer pointers as ``` int *a[4]; ```
I want to store all the MAC the mac address which has access to my server. All I know are only the IP addresses. All the machines are under unique gateway. Could I got the MAC address from their IP address?
MAC addresses are not part of any protocol that gets routed, you will never get the MAC address of a machine that is on the other side of a router or switch. They are are the addresses of the physical ports, not of machines (which are what you're taling to using IP).
I wrote a program, where the size of an array is taken as an input from user. ``` #include <stdio.h> main() { int x; scanf("%d", &x); int y[x]; /* some stuff */ } ``` This program failed to compile on my school's compilerTurbo C(an antique compiler). But when I tried this on my PC with GNU CC, it com...
It is a valid C program now, but it wasn't 15 years ago. Either way, it's a buggy C program becausexis used without any knowledge of how large it might be. The user can input a malicious value forxand cause the program to crash or worse.
I need help in Kocher's blowfish algorythm to implement in C. Its url is(http://www.schneier.com/code/bfsh-koc.zip). I could do the basics (initialize), but decryption isn't well. I know I should work with longs, but please help me to write a char * function what needs (char *encrypted_text) and returns the decrypted ...
Blowfish is already implemented in C all over the place. There's no need to write it yourself. The PolarSSL library has a C implementation, which can be foundhere.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
Use FMOD Library The FMOD Library Link Using this, see ifthiscan be implemented
I am having some doubts about Linux Terminal output's in a c program i made a ``` printf("Write A Message"); fgets(buffer,BUFSIZ,stdin); ``` which waits for a Message to be typed from keyboard I have threads on background which give back a ouptut, is it posible to output their message's in the terminal during the ...
If your threads also print to the terminal, the output will show up on the screen and mess up what is there. So if you wait for a keypress and in the meantime threads are printing, the message may dissapear.
How do you convert a MAC address within anintarray to string in C? For example, I am using the following array to store a MAC address: ``` int array[6] = {0x00, 0x0d, 0x3f, 0xcd, 0x02, 0x5f}; ``` How do I convert this to a string, like"00:0d:3f:cd:02:5f"?
You could do this: ``` char macStr[18]; int array[6] = {0x00, 0x0d, 0x3f, 0xcd, 0x02, 0x5f}; snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", array[0], array[1], array[2], array[3], array[4], array[5]); ``` If you want an uppercase string, use uppercase 'X': ``` snprintf(macStr, sizeof(ma...
I tried the following code snippet with MSVC 10, where it works fine. ``` enum { FOO = (sizeof(void*) == 8 ? 10 : 20) }; int main() { return FOO; } ``` What I would like to know is: Does the C++ Standard (preferably C++98) allow me to use the conditional-operator in a constant expression when all operands are c...
This is perfectly valid and sensible standard C++. The ternary conditional operator forms anexpression, and the expression is a constant expression if its operands are. The standard reference is C++11 5.19/2: Aconditional-expressionis acore constant expression[...] Note that by 5.16, ternary conditional expression...
I am trying to compile a C program which uses regexes on FreeBSD. I have checked in /usr/local/include and the file pcre.h is definitely there. However, no matter what I do, I get the following compiler error: ``` /usr/home/myname/project/include/pcre_wrap.h:4:18: error: pcre.h: No such file or directory ``` What c...
As the comment above says you need to use #include. If this isn't working you may want to export an environment variableC_INCLUDE_PATHthat points to the header file. Failing that why not try adding-I/usr/local/includeto yourgcccall, something likegcc myfile.c -I/usr/local/include -o myexe
I have C library with a header file. Now i want to make a wrapper in C++ in order to use it in .NET. When i include the library, the compiler reports an syntax errors regarding the variable types (DWORD, LPCSTR, etc...). In short, probably it thinks that the library is in C++ instead of C. I tried ``` extern "C"{ ...
You need to include<windows.h>, but I think you're doing it wrong. You don't need to create a C++ wrapper to use the library from .NET. You canDllImportall the C functions you need to call, directly in C#. Using the DllImport Attribute
This question already has answers here:What is the difference between const int*, const int * const, and int const *?(23 answers)Closed10 years ago. I know thatint* foo(int)prototype means thatfoois a function that takes an integer argument and returns a pointer to an integer.But what does the following mean? ``` co...
So that value pointed by returned address can't be change via address (useful when foo() returns address of const). ``` const int* p2c = foo(int); *p2c=10; <-- "error" ```
I want to generate an array initializer with arbitrary logic that unfortunately requires some looping. ``` #define RANDOM_ARRAY(n) \ ... double array[] = RANDOM_ARRAY(10); ``` Suppose the code above generates an initializer for a 10-element array. Is it possible to define such a macro (with a loop) in C99 ? NB...
Unfortunately, it is not possible to create a recursive (or loop) macrofunction in C. Nevertheless, if you have a reasonable maximum length for your initializer, you can use this type of construct : ``` #define INITIALIZER(N) { INITIALIZER_ ## N } #define INITIALIZER_1 1 #define INITIALIZER_2 INITIALIZER_1, 2 #d...
I have a C Sockets application, different executables of which must run at same time all at once, preferably in different terminals. How do I do it? For example, there are four exes, ./one, ./two, ./three, ./four. I want them to be run in different linux terminals without slightest of time difference. How can I do it...
There will always be at least a "slightest of time difference". Just have your exe's agree on a time to proceed and just sleep until that time before doing whatever it is that they need to do.
I wrote the following simple code in c and used input redirection with a batch file. How can I pause the program inside the while loop? ``` #include <stdio.h> int main(void) { char buffer[2048]; while ( !feof(stdin) ) { gets( buffer ); printf( "%s", buffer ); //I want to pause the program here, u...
``` #include <stdio.h> #include <conio.h> int main(void){ char buffer[2048]; while ( !feof(stdin) ) { gets( buffer ); printf("%s", buffer ); while(!_kbhit()); _putch('\n'); while(_kbhit()) _getch(); } return 0; } ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question My environment is Mac OS X and my program is in C++ If a process A is accessing a file in such a way that o...
ReadBeej's Guide to Unix IPC Read also thisthread, seems that mandatory locks (what you are looking for) are platform-specific, and OS X has no support for them.
How to create a C++ single build job that will produce .dll working on windows and .so prepared to work on Unix? Suppose that our development environment is based on Windows.
On Unix or Linux your shared library would need to link against system libraries like/lib64/libc.so.6and/lib64/ld-linux-x86-64.so.2. There is no way to link against these on Windows, if that is what you are asking (unless you deployed a Linux cross-compile toolchain on Windows, if that exists). You would need to compi...
The following code ``` int i=0; while(i<10) { printf("%d\n", i++); } ``` is equivalent to ``` int i=0; while(i<10) { printf("%d\n", i); i++; } ``` But the following code ``` int i=0; while(i<10) { printf("%d\n", i+=2); } ``` is equivalent to ``` int i=0; while(i<10) { i+=2; printf("%d\n", i); } ``` ...
You can write a macro to do this too. Like this: ``` #define POSTINC(var, val) ((var) += (val), (var) - (val)) printf("%d\n", POSTINC(i,2)); ``` But better use eitherforor just increase the value in the next statement.
I am following jansson tutorial below. https://github.com/akheron/jansson/blob/master/doc/tutorial.rst#id2 while I code like tutorial, I faced a problem. this jansson thing uses curl library, and its curl_easy_perform() method returns 1. And console printed like this, "Unsupported protocol". I already saw a solu...
From the command line, run: ``` $ curl-config --protocols | grep HTTPS ``` IfHTTPSis not printed, that is that the libcurl version your are linking to has not been built with SSL support. In such a case, you must re-install it with SSL support turned on, e.gyum install libcurl-develshould do the trick. Re-verify an...
I am trying to hash anunsigned longvalue, but the hash function takes anunsigned char *, as seen in the implementation below: ``` unsigned long djb2(unsigned char *key, int n) { unsigned long hash = 5381; int i = 0; while (i < n-8) { hash = hash * 33 + key[i++]; hash = hash * 33 + key[i++]...
``` unsigned long x; unsigned char * p = (unsigned char*)&x; ``` Make sure you use all 4 bytes through thep, or whatever is the length ofunsigned longon your system.
This question already has answers here:Why is memcmp so much faster than a for loop check?(3 answers)Closed8 years ago. Which implementation is better and why? Element by Element comparison using a for loop or memcmp() implementation ``` int a[] = {1,2,3}; int b[] = {1,3,5}; memcmp(a, b, sizeof(int)*n) ``` OR ``...
memcmpis faster: it is generally heavily optimized by the compiler to use special instructions on the cpu, loop unrolling, and other "advanced" techniques that the generated code for the simple loop (generally) won't use. However,memcmpcan only compare byte values; it is fine in case of an array of integers, but it (p...
As perWhy malloc+memset is slower than calloc? malloc+memsetis slower thancallocunder certain conditions. Why wasn'tcallocwritten in such a way that it can take an extravalueargument ( likememset) to override default assignment by zero? What would have been the effect of that if it were done?
Thesecallocormemsetinitializations operate on a byte level, so evenmemsetwith a value different from0is not that usefull. At least I don't remember having it used with different values. Mostly you allocate memory for a base type that is wider thanchar. The other aspect is thatcallocis initialization and not assignmen...
For a stringname[],can we usestrlen(name)+1andsizeof(name)interchangeablyin our code without second thought?Aren't they same?I checked about it and found out even the return type for both is same,size_t.And after allsizeofcalculates the size as a multiple of bytes and a character occupies one byte, whilestrlen()calcul...
For a declared array likechar name[10],sizeof(name)is the size of the entire array, regardless of what data is stored in it.strlen(name)returns the number of characters in the array before the first0. Behavior ofstrlenis undefined if there aren't any zeros in the array.
i have got a public key with (e,n) a encrypted data and have to get the plain text via RSA and that all in C! first of all i want to know how to find out what my p and q are? i know they have to be prime numbers and p<>q!
First, factor n. This is not hard; since sqrt(3233) is 56.8…, you only need to test prime numbers up to that. That will give you p and q. Use those to calculate (p-1)•(q-1). Then find the multiplicative inverse of 17 modulo (p-1)•(q-1) using theExtended Euclidean Algorithm. You do not need C code for that; I did it b...
I want to use au_int64_tvariable as search key. Isu_int64_tavailable on 32-bit machine? If not, do I have to divide this variable into two variables? Then as a search key, it is a bit more troublesome. Are there any workarounds for this?
An unsigned 64-bit integral type is not guaranteed by the C standard, but is typically available on 32-bit machines, and on virtually all machines running Linux. When present, the type will be nameduint64_t(note one less underscore) and declared in the<stdint.h>header file.
I havedouble a=1234.5678, now I can get1234byfloor(a), but how do I get0.5678? I know I can just subtracta-floor(a), but is there a function in the runtime library?
modfbreak a double value in two parts ``` double param, fractpart, intpart; param = 3.14159265; fractpart = modf (param , &intpart); printf ("%f = %f + %f \n", param, intpart, fractpart); return 0; ``` Output: 3.141593 = 3.000000 + 0.141593 You have to includemath.h http://www.cplusplus.com/reference/cmath/modf/
I'm trying to convert an old program that is written in C99 to C11 to be compiled with MinGW. I came across this line of code here ``` contenu[/size] = buffer; ``` and this code ``` output[k] = ((S[(S[i][/i] + S[j])%SIZE]) ^ texte[k]); ``` I'm not used to c99. Where it says [/size] and [/i] are those old c99 synta...
Each of the expressionscontenu[/size]andS[i][/i]is neither C99 nor C11. Your problem is not converting from C99 to C11, which is usually quite easy (there are only a few differences between the revisions and they are well hidden) but converting for a C-like language to C.
I tried ``` printf("%s %15s", string1, string2); ``` and I found out that this kind of left padding depends the distance from the first string, what if I want an absolute left padding counting from the left most?
You want to pad the first string on the right, instead of padding the second sting on the left: ``` printf("%-15s %s",string1,string2); ```
While traversing Wikipedia following some links, I stumbled acrossthe following code examplethat initializes a char buffer to 0, but thenmemsets it to 0 before use. Is this necessary? If so, why? The reason I ask is that I am no expert, and the example clearly states that this was the coder's intention with the commen...
``` char buffer[5] = {0}; /* initialized to zeroes */ /* some declaration / statements, but no access to buffer object */ memset ( buffer, 0, sizeof buffer); /* Really initialized to zeroes */ ``` in the above code, the call tomemsetis totally useless.bufferis already guaranteed to be initialized to0.
the assert() function can print the error and where the error happens, but it will also abort the function. I want to have a assert() function without aborting. I only hope to print the error, the name of the file where error happens, etc. is there such a API or source snippets in C? thanks!
Cunit has an assert that will either be fatal (quits) or not (will continue). http://cunit.sourceforge.net/doc/writing_tests.html#tests
I need to convert a number to a percentage of my DAC's max value (0x0FFF) so my code to do that would be like this: ``` double percent; short pct; percent = (0x0FFF * pct)/100; ``` but I need a 16-bit value to send to the DAC not a 32-bit one. What is the quickest way to convert it to a 16-bit number? Can I shift i...
There is no need to use floating point for this: ``` uint16_t val = 0x0fffU * pct / 100U; // convert 0..100 value to 0..4095 ```
I want to use au_int64_tvariable as search key. Isu_int64_tavailable on 32-bit machine? If not, do I have to divide this variable into two variables? Then as a search key, it is a bit more troublesome. Are there any workarounds for this?
An unsigned 64-bit integral type is not guaranteed by the C standard, but is typically available on 32-bit machines, and on virtually all machines running Linux. When present, the type will be nameduint64_t(note one less underscore) and declared in the<stdint.h>header file.
From the "man" pages it looks like inet_ntop returns a string (const char*) which should be alright when comparing toNULL. However, in my program I get a compiler warning at the first line in this code block that says: warning: comparison between pointer and integer . Assuming the correct parameters are being passed...
Have you included the "arpa/inet.h" file? The "arpa/inet.h" contains inet_ntop declarations. If you do not include it, the compiler will assue inet_ntop returns an int.
shm_openreturns anfdassociated with a "shared memory object". And normally, this object is then mapped into virtual memory (withmmap) to access as amemory-mapped file. However, is it safe to access the shared memory objectthrough itsfd(as if it were a normal file)? And by "safe", I mean guaranteed by POSIX to have we...
Unfortunately, no.POSIX says: Iffildesrefers to a shared memory object, the result of thewrite()function is unspecified. ..and the same forread(). It does work on Linux, though, where a shared memory object is a file backed by thetmpfsfilesystem.
I'm just starting with C programming, and i'm trying to read and display files in a directory (just like the ls command). Here's a part of my code where I get a segfault, and I have no clue why: ``` void display_dir(char *dir) { DIR *strm; struct dirent *direct; if((strm = opendir(dir) == NULL)) { ...
``` if((strm = opendir(dir) == NULL)) ``` The parentheses are nested wrong. It should be: ``` if((strm = opendir(dir)) == NULL) ```
I am very new to programming and I always receive this error when defining functions: ``` The parameter IPWM_int has not been declared ``` There is no return type for the function, but it does not give any errors. Here is the function that causes the problem (this is out of main() function): ``` int IntToASCII(IPW...
The correct function definition here is presumably (based on the%dformatting specifier and the variable name): ``` int IntToASCII(int IPWM_int) ``` The only way that this function definition could compile is if it were in ANSI C, and looked like this: ``` int IntToASCII(IPWM_int) int IPWM_int; { [...] ``` Perh...
``` for(;;) { ...// CPU usage and etc... printf("Server is up: %.0f sec\n",diff_time); //seconds of running for example sleep(1); } ...//other server code ``` I'm writing a server program. I need to output information every 1 second about CPU usage, etc... Code above works, but server ...
hmmm interesting if you are in linux do the below man -a timer_create should be able to provide a solution otherwiseClick Here
I've seen this declaration in a tutorial where someone is changing the appearance of the UITabBarController. ``` UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController; ``` What does the first part after the equal sign do? To be more specific, the ``` (UITabBarController *) ``` ...
This is atypecast: the(T)valueoperator forces an explicit type conversion from the original type ofvalueto the new typeT.
I'm adding together a load of array elements from each process: ``` double rho[1024]; //Some operation to calculate rho for each process; MPI_Allreduce(rho,rho,1024,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD); ``` Will having rho as both the sendbuf and recvbuf work?
Have you checkedMPI_IN_PLACE? According toMPI_AllReduce man pageandMPI docit can be used to specify the same buffer for sendbuf and recvbuf as long as you are working inside the same group. The call would look like: ``` MPI_Allreduce(MPI_IN_PLACE,rho,1024,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD); ```
I wrote a simple program with a function that calculates the area of a circle. The program also asks to the user if he wants to calculate it again and if the input is'N', the program is supposed to stop. Here's the narrowed down test case: ``` #include<stdio.h> #include<string.h> int main(void) { float r; ...
``` scanf("%c", &f); ``` leaves a newline character in the input stream which is consumed in the next iteration. Add a space in the format string to tell scanf() to ignore whitespaces. ``` scanf(" %c", &f); // Notice the space in the format string. ```
Is there a stable and portable way to make use of PostGIS-functions in my own PostgreSQL extension? I would like to process the geometry type with functions like intersects in my c code by directly calling this functions from the postgis-$version.so (in PostgreSQL's $libdir).
You should generally do this by invoking the SQL-level PostGIS functions via either theSPIor viafmgrfast-path calls. Seethis related question about using hstore from C.
I have a c program which should take the first argument and check which function matches it. Example: ``` ./test.o blabla ``` Code: ``` main(int argc, const char* argv) { switch (argv[1]) { case "blabla": do_omething(argv[2]); break; } return 0; } void do_something(const char* par...
If youswitchon a C string, that's itsaddress,not its contents. You should use something likestrcmpto check if thecontentmatches: ``` if (strcmp (argv[1], "blabla") == 0) do_something(argv[2]); ```
From the "man" pages it looks like inet_ntop returns a string (const char*) which should be alright when comparing toNULL. However, in my program I get a compiler warning at the first line in this code block that says: warning: comparison between pointer and integer . Assuming the correct parameters are being passed...
Have you included the "arpa/inet.h" file? The "arpa/inet.h" contains inet_ntop declarations. If you do not include it, the compiler will assue inet_ntop returns an int.
I am facing problem in doing addition of long values example ``` typedef unsigned short UINT16; UINT16* flash_dest_ptr; // this is equal to in hexa 0XFF910000 UINT16 data_length ; // hex = 0x000002AA & dec = 682 //now when I add UINT16 *memory_loc_ver = flash_dest_ptr + data_length ; dbug_prin...
It's pointer arithmetic, so ``` UINT16 *memory_loc_ver = flash_dest_ptr + data_length ; ``` advancesflash_dest_ptrbydata_length * sizeof (UINT16)bytes. Typically,sizeof (UINT16)would be 2, and ``` 2 * 0x2AA = 0x554 ```
Are there any libraries out there that I can pass my .c files through and will count the visible number of, of example, "if" statements? We don't have to worry about "if" statement in other files called by the current file, just count of the current file. I can do a simple grep or regex but wanted to check if there ...
If you want to be sure it's done right, I'd probably make use of clang and walk the ast. A URL to get you started: http://clang.llvm.org/docs/IntroductionToTheClangAST.html
This question already has answers here:Is main() really start of a C++ program?(12 answers)Closed10 years ago. i have a question for you. I need find out if i can use some function before or after main() function ended. I can't find some examples for C language. Can you give me some advice or examples. Thanks a lot....
If you are using GCC, you can createconstrutors/destructorfunctions: Theconstructorattribute causes the function to be called automatically before execution entersmain(). Similarly, thedestructorattribute causes the function to be called automatically aftermain()completes orexit()is called. Functions with these attri...
I am trying to write an application for capturing stereo audio. My audio input has two channels(Stereo). I am writing this audio data into a wav file. Some times these audio channels are exchanging i.e, Left becomes right and right becomes left. This is happening only if i open and close the device file or turn off th...
stereo PCM stored in a wav file is in an LR format. 'L' stands for left channel sample and 'R' for right channel sample. I guess you have a bug in retrieving or storing the PCM. Maybe sometimes you start with the right (correct) position in buffer and sometimes you start with the second sample. It's hard to tell witho...
This question already has answers here:Are there any platforms where pointers to different types have different sizes?(7 answers)Closed10 years ago. In C and C++, do I have the guarantee that all pointers have the same size in bytes, or in other words : ``` sizeof(void*) = sizeof(char*) = sizeof(int*) = ... ``` or ...
No. There is no guarantee in the standard. There are some exception is some systems. Although it's fixed in many typical systems and depends on the architecture of that system. For example in 32-bit systems pointers are 4 bytes. By the way,uintptr_tcan hold pointers (Maybe we can assume it has the maximum size of a ...
I'm making a wrapper for a C library. There is a method that changes 2 ints by the user giving 2 int pointers to the method. So if I havevoid changenums(int* a, int* b)what is a safe way to access this method in c#?
Declare the p/invoke like this: ``` [DllImport(@"mydll.dll")] static extern void changenums(ref int a, ref int b); ``` And call it like this: ``` int a = 0; int b = 0; changenums(ref a, ref b); ```
what is the difference between this calls toimreadin openCV?On my local machine both of them work. ``` 1) cv::imread(filename.c_str(), CV_LOAD_IMAGE_COLOR); 2) cv::imread(filename, CV_LOAD_IMAGE_COLOR); ``` In the first case we convert a std::string to C style string. In the second case we just pass a std:...
The calls have the same effect.cv::imreadtakes aconst std::string&as first argument, so the first version would result in the creation of a temporarystd::stringobject, constructed from theconst char*returned byfilename.c_str().
Is there a nice way to send a SIGUSR to a grandchild directly? E.g. I have some process tree: ``` 0 / \ 1 2 \ 3 ``` and need to send a signal from0to3. I know I could save child's pid after forking and the use it withkill()like ``` pid = fork(); if (pid == 0) { pid = fork(); if (...
There is no direct communication between parent and grandchildren. The usual approach here is having the grandchild to store its PID somewhere on the filesystem (say, in /var/lib/myapp/grandchild.pid) and reading it back in the parent. You can also use process groups on Linux, but they offer a coarse-grained approach...
I am facing problem in doing addition of long values example ``` typedef unsigned short UINT16; UINT16* flash_dest_ptr; // this is equal to in hexa 0XFF910000 UINT16 data_length ; // hex = 0x000002AA & dec = 682 //now when I add UINT16 *memory_loc_ver = flash_dest_ptr + data_length ; dbug_prin...
It's pointer arithmetic, so ``` UINT16 *memory_loc_ver = flash_dest_ptr + data_length ; ``` advancesflash_dest_ptrbydata_length * sizeof (UINT16)bytes. Typically,sizeof (UINT16)would be 2, and ``` 2 * 0x2AA = 0x554 ```
Are there any libraries out there that I can pass my .c files through and will count the visible number of, of example, "if" statements? We don't have to worry about "if" statement in other files called by the current file, just count of the current file. I can do a simple grep or regex but wanted to check if there ...
If you want to be sure it's done right, I'd probably make use of clang and walk the ast. A URL to get you started: http://clang.llvm.org/docs/IntroductionToTheClangAST.html