question
stringlengths
25
894
answer
stringlengths
4
863
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed10...
As you insert elements into the hash table, you also add the elements to a linked list. When you are asked to traverse the hash table, iterate over the linked list.
In the following code: ``` int strlen(char *s){ char *p = s; while(*p++ != '\0'); return p - s; } ``` Why does the above evaluate differently than this: ``` int strlen(char *s){ char *p = s; while(*p != '\0') p++; return p - s; } ``` It is my understanding that the expression will evalu...
in the first codepis incremented regardless of if thewhile()condition was true or false. In the second snippet of code,pis incremented ONLY ifwhilecondition was true.
How do I achieve concatenation using only pointers since the code below gives (a segmentation fault) error (at runtime)? ``` #include <stdio.h> #include <string.h> int main() { char *s1="Front"; char *s2="Back"; char *s3=strcat(s1,s2); puts(s3); return 0; } ```
Because you are trying to write to a string literal. The linechar *s1 = "Front";points to a string constant, which can't be written to. Change it tochar s1[20] = "Front";and it should work out like you expect - as long as you are adding no more than 14 characters.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions concerning problems with code you've written mustdescribe the specific problem— andinclude valid codeto reproduce it — in the question itself. SeeSSCCE.orgfor guidance.Closed10 years ago.Improve this question ...
No, they aren't.qsort()is a C standard library function."Quicksort", on the other hand, is a specific sortingalgorithm.It is often used as the backing algorithm of an actual implementation ofqsort().
How do I achieve concatenation using only pointers since the code below gives (a segmentation fault) error (at runtime)? ``` #include <stdio.h> #include <string.h> int main() { char *s1="Front"; char *s2="Back"; char *s3=strcat(s1,s2); puts(s3); return 0; } ```
Because you are trying to write to a string literal. The linechar *s1 = "Front";points to a string constant, which can't be written to. Change it tochar s1[20] = "Front";and it should work out like you expect - as long as you are adding no more than 14 characters.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions concerning problems with code you've written mustdescribe the specific problem— andinclude valid codeto reproduce it — in the question itself. SeeSSCCE.orgfor guidance.Closed10 years ago.Improve this question ...
No, they aren't.qsort()is a C standard library function."Quicksort", on the other hand, is a specific sortingalgorithm.It is often used as the backing algorithm of an actual implementation ofqsort().
I want to type "man time" and info about thetime.htime function, but instead I am getting the linux time system command. man time 2orman time 3doesn't do any different. How can I find the right man page?
How aboutman man? Then you would find out thatman 3 timeworks.
can anyone tell me how to install opencv2.4.6 using cmake, I found several tutorials but I can't find the common folder inc:\opencv\build_common_ ** to past the **tbb41_20130613ossfolder any idea can I do that. thanks in advance
You need to build the library, and then execute targetinstall. When usingmakeit will be ``` make make install ``` On visual studio You need to select the targets manually (I think).
I am getting an error when declaring an enum inside a struct in an objective-c file. I've recently upgraded to LLVM 5 and didn't have this error before. I've tried C99 and C11. Any ideas whats wrong or is this illegal syntax that was permitted previously? ``` struct LogParams { typedef NS_ENUM (int, Level) // ...
Declaring an enum or typedef inside a struct is valid in C++ and Objective-C++ translations. It is not legal in C or Objective-C.
Consider the following code: ``` extern "C" { #include <lib.h> } #include <iostream> int main() { unsigned char a='a'; unsigned char b=some_struct_in_libh->unsignedchar; cout << a << " " << b << endl; //Prints only a printf("%u\n",b); //Prints b cout << static_cast<int>(b) << endl; //Als...
It's not printing onlyaat all. What you're seeing is instead thatcoutprints character type data ascharactersnot as numbers. Yourbis some character that's non-printable socoutis helpfully printing it as a blank space. You found the solution by casting it to int. EDIT: I'm pretty sure your printf is only working by ch...
I have a function that parses a file, and puts it's data into a dynamically allocated array of structs. The function returns this dynamically allocated array of the user defined data type. I want to free this array that was used in the parsing function, how do I do this? Here is the code I use to allocate the array...
Just use: ``` free(pDownloads); ``` to free the array object. For everymalloccall, you should have exactly onefreecall.
I am using scandir() function in C, on a folder where i need to get files whose filenames are exactly = "exe". How can i filter the entries returned by scandir? Third argument of scandir is filter: ``` int scandir(const char *dirp, struct dirent ***namelist, int (*filter)(const struct dirent *), int (...
Yes, the filter argument is a function pointer that lets you pass in a function to filter the results. You might want to write a function like the one below and pass it by name as the value for filter. ``` int file_select(const struct dirent *entry) { return strcmp(entry->d_name, "exe"); } ```
In our production environment, when we are executing an .so file as part of batch we always encounter a fatal as below : calloc failed for 9088 bytes Date 12-07-2013 01:55:05 Could you please let me know the possible reasons for the calloc memory issue.
Maybe you should check how the 'maximum number of AIX data segments that a process can use' is set (enviromnent variable LDR_CNTRL). SeeIBM Performance Tuning GuideOn aixulimitlies if it tells you data size is unlimited.
``` #include <stdio.h> int main(){ float var = 0.612; printf("%f\n",var); printf("%f\n",var*100); return 0; } ``` o/p ``` 0.612000 61.199997 ``` I found that for JavaScript, we have.tofixed()method. How do we get a fix for this in C?
You can specify the precision when printing: ``` printf("%.3f\n", 100 * var); ``` Since the exact number you're having probably isn't representable in thefloatitself, there is no operation you can do on the number itself to "remove" the decimals, it's all a matter of how you choose to present the data.
This question already has answers here:what is meant by normalization in huge pointers(3 answers)Closed10 years ago. Actually i was studying about huge and far pointers. I come to know huge pointers are by default in normalized form. I want to know how can we normalize any pointer?
The huge pointer and far pointer are old concept which live in 16-bit DOS time. You can search something about DOS programming for more detail about them. In 8086 programming (MS DOS), a far pointer is normalized if its offset part is between 0 and 15 (0xF).
I have char a[4] and in it:a[0] = 0x76a[1] = 0x58a[2] = 0x02a[3] = 0x00And I want print it asint, can you tell me how to do that?
This works, but gives different results depending on the size of int, endian and so on.. ``` #include <stdio.h> int main(int argc, char *argv[]) { char a[4]; a[0] = 0x76; a[1] = 0x58; a[2] = 0x02; a[3] = 0x00; printf("%d\n", *((int*)a)); return 0; } ``` This is cleaner but you still hav...
This question already has answers here:C program to convert Fahrenheit to Celsius always prints zero(6 answers)Closed10 years ago. I am trying to implement the below formula on C Here is my code: ``` int function(int x){ return pow(10, (((x-1)/(253/3))-1)); } int main(void){ int z = function(252); printf(...
Note that in this line ``` (((x-1)/(253/3))-1)) ``` You are dividing the integer valuex - 1by an integer value253 / 3. This will truncate the value to anint, meaning that you'll be raising an integer power to an integer power. To fix this, try changing this expression to ``` (((x-1)/(253.0 / 3.0))-1)) ``` This n...
Suppose I do like this to copy the string. ``` char str[] = ""; char *str2 = "abc"; strcpy(str, str2); printf("%s", str); // "abc" printf("%d", strlen(str)); // 3 ``` Then, why it doesn't give me undefined behaviour or causing the program to fail. What are the disadvantages of doing like that ?
You are writing past the memory space allocated to str on the stack. You need to make sure you have the correct amount of space for str. In the example you mentioned, you need space for a, b, and c plus a null character to end the string, so this code should work: ``` char str[4]; char *str2 = "abc"; strcpy(str, str2...
Let's say I havechar x[3] = "123";and I would like to convert only index 1 and index2 "23" of the char array, can I do it byatoi? I know I can do it bychar z[2]; z[0]=x[1]; z[1]=x[2]; atoi(z);but it is not what I am asking for.
You can do this with ``` char x[4]; int i; strcpy(x, "123"); i = atoi(x + 1); ``` Becausexis a pointer to char,x + 1is a pointer to the next char. If you try to print with ``` printf("%s", x + 1); ``` You'l get23as the output. Note though that you need to declare the length of the char array to be one more than...
I have a long C code that is written for Linux environment. I have been adding and removing standard functions, so that I have been adding new headers, but never go through the code to find out if there is any unnecessary headers. I wonder having unnecessary headers on the code would effect anything? If it does not e...
Unnecessary headers mostly affect compilation speeds, because of how stupid C's inclusion mechanism is: the entire header is read in and copy-pasted in the source code.
I want to implement a debug code for my project which is in c. In my project i am having so many functions and function calls. I want to write code in such a way that when a function is called, It should print the function name and its caller name. Can anybody give me a clue for doing this?
Thelibunwindlibrary may be able to help you there. But it's going to be fairly slow and may give very unpredictable results in case of optimised binaries. Do you actually need to implement this in the app? Isn't running the application undergdbwith some breakpoints enough? Another way to generate the traces without ...
How can I make sure that if someone uses come specific function(say memcpy) in code, then it returns an error. We have removed all the instances of memcpy from code with some internal designed function, what I want to make sure is that whenever someone uses memcpy in future, the compiler throws an errors msg.
You can use the preprocessor for this, like ``` #define memcpy(a, b, c) do_not_use_memcpy ``` Put that in a header file that is included in all source files, and the preprocessor will replace all calls tomemcpywith the (undefined) symboldo_not_use_memcpy. As that symbol is undefined, you will get a compiler error ab...
All is in the title. How to check a possible overflow when using the two functions exp() and log()?
``` #include <errno.h> ``` When an oferflow occurs, thenerrnois set toERANGE. Next time, do your homework before asking. Googling: "c++ exp" returned this as the first resulthttp://www.cplusplus.com/reference/cmath/exp/In the middle of the page, there is EXACTLY what you're looking for.
I have char a[4] and in it:a[0] = 0x76a[1] = 0x58a[2] = 0x02a[3] = 0x00And I want print it asint, can you tell me how to do that?
This works, but gives different results depending on the size of int, endian and so on.. ``` #include <stdio.h> int main(int argc, char *argv[]) { char a[4]; a[0] = 0x76; a[1] = 0x58; a[2] = 0x02; a[3] = 0x00; printf("%d\n", *((int*)a)); return 0; } ``` This is cleaner but you still hav...
This question already has answers here:C program to convert Fahrenheit to Celsius always prints zero(6 answers)Closed10 years ago. I am trying to implement the below formula on C Here is my code: ``` int function(int x){ return pow(10, (((x-1)/(253/3))-1)); } int main(void){ int z = function(252); printf(...
Note that in this line ``` (((x-1)/(253/3))-1)) ``` You are dividing the integer valuex - 1by an integer value253 / 3. This will truncate the value to anint, meaning that you'll be raising an integer power to an integer power. To fix this, try changing this expression to ``` (((x-1)/(253.0 / 3.0))-1)) ``` This n...
Suppose I do like this to copy the string. ``` char str[] = ""; char *str2 = "abc"; strcpy(str, str2); printf("%s", str); // "abc" printf("%d", strlen(str)); // 3 ``` Then, why it doesn't give me undefined behaviour or causing the program to fail. What are the disadvantages of doing like that ?
You are writing past the memory space allocated to str on the stack. You need to make sure you have the correct amount of space for str. In the example you mentioned, you need space for a, b, and c plus a null character to end the string, so this code should work: ``` char str[4]; char *str2 = "abc"; strcpy(str, str2...
Let's say I havechar x[3] = "123";and I would like to convert only index 1 and index2 "23" of the char array, can I do it byatoi? I know I can do it bychar z[2]; z[0]=x[1]; z[1]=x[2]; atoi(z);but it is not what I am asking for.
You can do this with ``` char x[4]; int i; strcpy(x, "123"); i = atoi(x + 1); ``` Becausexis a pointer to char,x + 1is a pointer to the next char. If you try to print with ``` printf("%s", x + 1); ``` You'l get23as the output. Note though that you need to declare the length of the char array to be one more than...
I have a long C code that is written for Linux environment. I have been adding and removing standard functions, so that I have been adding new headers, but never go through the code to find out if there is any unnecessary headers. I wonder having unnecessary headers on the code would effect anything? If it does not e...
Unnecessary headers mostly affect compilation speeds, because of how stupid C's inclusion mechanism is: the entire header is read in and copy-pasted in the source code.
I want to implement a debug code for my project which is in c. In my project i am having so many functions and function calls. I want to write code in such a way that when a function is called, It should print the function name and its caller name. Can anybody give me a clue for doing this?
Thelibunwindlibrary may be able to help you there. But it's going to be fairly slow and may give very unpredictable results in case of optimised binaries. Do you actually need to implement this in the app? Isn't running the application undergdbwith some breakpoints enough? Another way to generate the traces without ...
How can I make sure that if someone uses come specific function(say memcpy) in code, then it returns an error. We have removed all the instances of memcpy from code with some internal designed function, what I want to make sure is that whenever someone uses memcpy in future, the compiler throws an errors msg.
You can use the preprocessor for this, like ``` #define memcpy(a, b, c) do_not_use_memcpy ``` Put that in a header file that is included in all source files, and the preprocessor will replace all calls tomemcpywith the (undefined) symboldo_not_use_memcpy. As that symbol is undefined, you will get a compiler error ab...
All is in the title. How to check a possible overflow when using the two functions exp() and log()?
``` #include <errno.h> ``` When an oferflow occurs, thenerrnois set toERANGE. Next time, do your homework before asking. Googling: "c++ exp" returned this as the first resulthttp://www.cplusplus.com/reference/cmath/exp/In the middle of the page, there is EXACTLY what you're looking for.
I was trying to write a package file in C for db2. But I was just wondering what all include files and functions can be used. I saw this example in this link by york university. It explains a lot but I don't know what resources are available in terms of include libraries and their functions. Your help is highly appre...
Here's a link to the PDF manuals-- see the Application Development section.
``` int a[] = {1,2,3,4}; printf("%d",sizeof(a)/sizeof(a+1)); ``` output: 4 Can anyone explain this?
It's wrong.sizeof(a)is the size of the array, andsizeof(a+1)is the size of a pointer. Dividing the two makes no sense. What the author probably intended is: sizeof a / sizeof a[0] Which will yield the number of elements in the array.sizeof a[0]is the size of anint. The reason your code gives you the right answer ...
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.Closed10 years ago.Improve this question What are configuration files? What are their use in c programs? Additional question: Wh...
A configuration file could be any file which the program uses to persistently store options, state, or data between executions. The concept is not specific to C and is probably universal to most programming languages. It is impossible, without knowing exactly what program you are dealing with, to figure out what they ...
Does anyone know what specific function is being used to determine the filter coefficients indecimate(vector, order, 'fir')? Specifically is itfir1withWn = 0.5? It says the order is 30, so that's for certain. I got these coefficients, but I can't duplicate the results indecimate. ``` C = fir1(30, 0.5) -1.6994e-03 8....
Confirmed using source code from Octave that the filter isfir1(30, 1/order).
I am using plain old c. I have a function that uses static local variables and is therefore non-reentrant. I would like to remove the use of the static locals and make the function reentrant. Any tips or design recommendations for how to do this? Is this question too vague? Does it require more details about the de...
Instead of using static locals to maintain state, have the caller pass those state variables to your function as parameters. It means your caller will have to maintain state, but that's usually what you want anyway.
``` long long encrypt(int message,int n,int e) { long long s=pow(message,e); return s%n; } ``` When I try this: ``` printf("%lli",encrypt(65,3233,17)); ``` It prints out this: -2631 Does anyone have any idea how to fix this...To be honest those are small values for now..I think I'll use larger values in the future...
Perhaps this will do: ``` int encrypt(int message,int n,int e) { int s = 1; while (e--) { s = ( s * message ) % n; } return s; } ```
I was trying to write a package file in C for db2. But I was just wondering what all include files and functions can be used. I saw this example in this link by york university. It explains a lot but I don't know what resources are available in terms of include libraries and their functions. Your help is highly appre...
Here's a link to the PDF manuals-- see the Application Development section.
I was writing some code in C# the other day and it got me thinking. If a char literal can only have 1 char (or a delimited character) then why do we need the closing delimiter? For example, currently we need to write: ``` char character = 's'; ``` And there is no circumstance where this can work (obviously): ``` c...
It's a conventionCharacters are not necessarily represented in one character, in this unicode worldControl / escape sequences can be longer than one character (e.g. '\0x1a' )
How I can improve speeds of read & write the data from standard input (terminal) in c/c++ code? I use: ``` ios::sync_with_stdio_false(); ``` Does any way exist to do that quicker?
Obtainstd::streambufreferences fromstd::cin.rdbuf()andstd::cout.rdbuf(). (Yes, it's still calledrdbufeven when used for output.) Most of the slowdown in iostream occurs in the formatting functionality. You will have to parse the bytes yourself. As with anything performance-related, don't believe, assume, or suppose ...
I'm programming in C99 and use variable length arrays in one portion of my code. I know in C89 zero-length arrays are not allowed, but I'm unsure of C99 and variable length arrays. In short, is the following well defined behavior? ``` int main() { int i = 0; char array[i]; return 0; } ```
No, zero-length arrays are explicitly prohibited by C language, even if they are created as VLA through a run-time size value (as in your code sample). 6.7.5.2 Array declarators...5If the size is an expression that is not an integer constant expression: if it occurs in a declaration at function prototype scope, it is...
I'm wondering if is it possible somehow to make something like this in C/C++: ``` int a = 5; #define A a printf("%s\n", A); // should print 5 (value of 'a' variable) ``` Ok, this code gives me segmentation fault (Windows 7, Code::Blocks): ``` #include <stdio.h> int main() { int a = 5; #define A a #if ...
You need to use%dinstead of%s: ``` printf("%d\n", A); ``` Checkthisout, it works!
I'm looking for a simple solution for stripping numbers from a string. Example: "GA1UXT4D9EE1" => "GAUXTDEE" The occurrence of the numbers inside the string is erratic hence I cannot rely on functions such as scanf(). I'm new at programming in C. Thanks for any help.
I will give you some tips: You need to creat a new string.Iterat over the original string.Check if the current character is between theascii values of numbersIf not, add it to the new string.
This question already has answers here:C macros and use of arguments in parentheses(2 answers)Closed5 years ago. I am new to c language. I just wanted to know why is my macro not working properly. It is giving me output as 13 where as my expected output is 24.? ``` #include<stdio.h> #define mult(a,b) a*b int main() ...
mult(x+2,y-1)expands tox +2 * y -1that is equals to4 + 2 * 5 -1gives output:13. You might be expecting answer(4 + 2) * (5 -1)=6 * 4=24. To make it expand like this you should write parenthesize macro as @H2Co3 also suggesting: ``` #define mult(a,b) ((a)*(b)) ``` Read aslo:So, what's wrong with using macros?by Bjarn...
I was going through the GSL documentation and was curious why there were no vector * matrix functions. I get that vector * matrix is the same as matrix_transpose * vector. Why is it done this way as opposed to writing a function to do multiplication with the vector on the left hand side?
I cannot look into the heads of GSL developers, but I imagine that they just didn't see a need for it: matrix transposition can be done in-place by iterating differently over the indices, so adding another function would just add more overhead. (In my own projects using GSL I've always wrapped GSL functions inside som...
I've got an array of sixuint16_twhich is actually threeuint32_t, with the bits in the right order and all. How can I cast the former to the latter as effectively as possible? The number of elements in the array is known at compile-time.
Like this perhaps: ``` uint16_t arr16[6]; uint32_t *parr32 = (uint32_t*)(&arr16); ``` And now you can useparr32[i]to refer to elements of the overlayedarr16array.
I have a project which includes two source files and one header file (wich contains the prototype of a function defined in one of the source files namedGet.c), the problem is: when I include theGet.cin the other source file, it gives me the error error : Get.c: No such file or directory ?, even when I have all the t...
In C you should be including the interface file (.h file), not the C source file (.c file). Create an interface for your module and include it respectively.
Can I usestrlenof aconst char*in a loop like this and expect O(n) time complexity, or would it result in O(n^2)? I think it looks cleaner than using a variable for the string length. ``` void send_str( const char* data ) { for (uint8_t i = 0; i < strlen(data); i++) send_byte( data[i] ); } ``` Does it dep...
I don't think you can everdependon an optimization happening. Why not do it like this, if you really want to avoid an extra variable: ``` void send_str(const char *data) { for(size_t i = strlen(data); i != 0; --i) send_byte(*data++); } ``` Or, less silly, and more like an actual production-quality C program: ...
I'm wondering if is it possible somehow to make something like this in C/C++: ``` int a = 5; #define A a printf("%s\n", A); // should print 5 (value of 'a' variable) ``` Ok, this code gives me segmentation fault (Windows 7, Code::Blocks): ``` #include <stdio.h> int main() { int a = 5; #define A a #if ...
You need to use%dinstead of%s: ``` printf("%d\n", A); ``` Checkthisout, it works!
I'm looking for a simple solution for stripping numbers from a string. Example: "GA1UXT4D9EE1" => "GAUXTDEE" The occurrence of the numbers inside the string is erratic hence I cannot rely on functions such as scanf(). I'm new at programming in C. Thanks for any help.
I will give you some tips: You need to creat a new string.Iterat over the original string.Check if the current character is between theascii values of numbersIf not, add it to the new string.
This question already has answers here:C macros and use of arguments in parentheses(2 answers)Closed5 years ago. I am new to c language. I just wanted to know why is my macro not working properly. It is giving me output as 13 where as my expected output is 24.? ``` #include<stdio.h> #define mult(a,b) a*b int main() ...
mult(x+2,y-1)expands tox +2 * y -1that is equals to4 + 2 * 5 -1gives output:13. You might be expecting answer(4 + 2) * (5 -1)=6 * 4=24. To make it expand like this you should write parenthesize macro as @H2Co3 also suggesting: ``` #define mult(a,b) ((a)*(b)) ``` Read aslo:So, what's wrong with using macros?by Bjarn...
Is 'for' loop in ANSI-C guaranteed to be executed in order, or can it be optimized by compiler using out-of-order execution? If so, which compilers do that? In which optimization level? How can this optimization be prevented?
The compiler has the right to execute statements out of order if it is able to determine it does not change the observable behavior of the program. Usevolatileobjects if you want to execute statements strictly according to the rules of C abstract machine.
I am using openssl/DSA to generate signature for some data using private key. and on the other side I am verify data integrity using public key. In the sample code I am able to do it successfully using DSA_sign and DSA_verify functions. But I would like to dump signature to a file and transfer it to client along wit...
DSA_signsimply puts the signature in aunsigned char*, also known as just a bunch of bytes. To write it to disk you can use any example out there.
This question already has answers here:What is the difference between NULL, '\0' and 0?(11 answers)Closed10 years ago. As far as i know, the NULL is actually not 0. So is there any difference in comparing a pointer with 0 or with NULL? Further what should be the correct usage. Thanks!
The correct usage is to useNULL: It's more readable (p == NULL-> you know thatpis a pointer)
I have a console application written in C that simply takes an integer from user, and prints a text according to number given. I'd like to have a Qt based GUI that could send an integer to a C program, and read a string sent by that program. But I don't know how could I possibly make them communicate. Any ideas? FYI:...
You could use aQProcesswhich will behave as anIODeviceallowing to write (to stdin) or read (from stdout/stderr) Check the example in the doc athttp://qt-project.org/doc/qt-5.0/qtcore/qprocess.htmlfor detailed example You Qt app would start your C program as a QProcessit will interact with it with write / readAllStan...
In a boot loader code i found that, they are using volatile keyword when accessing physical address. Is it necessary to use volatile keyword even we are accessing physical memory address?
You need to use "volatile" whenever the data can change, without the compiler being able to know about it.
I am having some problem with Coderunner. It was running with out any problem but now it is not.As you see in image below. Please, can you help me to resolve this problem. Thanks!http://yadi.sk/d/tDkp1K8v6aeby
Did you uninstall Xcode, or upgrade your OS recently ? Because Coderunner need Command Line Tool to work properly. How to install Command Line Tool for Lion and above.
Is 'for' loop in ANSI-C guaranteed to be executed in order, or can it be optimized by compiler using out-of-order execution? If so, which compilers do that? In which optimization level? How can this optimization be prevented?
The compiler has the right to execute statements out of order if it is able to determine it does not change the observable behavior of the program. Usevolatileobjects if you want to execute statements strictly according to the rules of C abstract machine.
I am using openssl/DSA to generate signature for some data using private key. and on the other side I am verify data integrity using public key. In the sample code I am able to do it successfully using DSA_sign and DSA_verify functions. But I would like to dump signature to a file and transfer it to client along wit...
DSA_signsimply puts the signature in aunsigned char*, also known as just a bunch of bytes. To write it to disk you can use any example out there.
This question already has answers here:What is the difference between NULL, '\0' and 0?(11 answers)Closed10 years ago. As far as i know, the NULL is actually not 0. So is there any difference in comparing a pointer with 0 or with NULL? Further what should be the correct usage. Thanks!
The correct usage is to useNULL: It's more readable (p == NULL-> you know thatpis a pointer)
I have a console application written in C that simply takes an integer from user, and prints a text according to number given. I'd like to have a Qt based GUI that could send an integer to a C program, and read a string sent by that program. But I don't know how could I possibly make them communicate. Any ideas? FYI:...
You could use aQProcesswhich will behave as anIODeviceallowing to write (to stdin) or read (from stdout/stderr) Check the example in the doc athttp://qt-project.org/doc/qt-5.0/qtcore/qprocess.htmlfor detailed example You Qt app would start your C program as a QProcessit will interact with it with write / readAllStan...
In a boot loader code i found that, they are using volatile keyword when accessing physical address. Is it necessary to use volatile keyword even we are accessing physical memory address?
You need to use "volatile" whenever the data can change, without the compiler being able to know about it.
I am having some problem with Coderunner. It was running with out any problem but now it is not.As you see in image below. Please, can you help me to resolve this problem. Thanks!http://yadi.sk/d/tDkp1K8v6aeby
Did you uninstall Xcode, or upgrade your OS recently ? Because Coderunner need Command Line Tool to work properly. How to install Command Line Tool for Lion and above.
According to microsoftHIWORDmacro retrieves the high-order word from the specified 32-bit value. The original definition of macro is: ``` #define HIWORD(l) ((WORD)((((DWORD_PTR)(l)) >> 16) & 0xffff)) ``` For example if the passed argument is aunsigned longvalue0x12345678, return result is0x1234 Rewrite the macro ...
What is purpose of AND operation (& 0xffff) in first macro ? It's not necessary, as the cast will eliminate the high-order bits. I guess it's just there to highlight (to the reader) the fact that bits are being removed.
I am new in AVR programming. I would like to control a variable (uint8_t received_msg) if it is equal to0xFF. would it be correct to do: ``` if (!(received_msg ^ 0xFF)) ``` or do I need to compare bit by bit ``` uint8_t test = 0; test = received_msg ^ 0xFF for (i =0; i<8; i++){ test = 0 & (1<<receive...
If you want to know if a variable is equal to0xff, just test for equality: ``` if (received_message == 0xff) ```
currently I've this but it doesn't put my window behind the desktop ``` SetWindowPos(hWnd,HWND_BOTTOM,0,0,SCREEN_WIDTH,SCREEN_HEIGHT,SWP_FRAMECHANGED); ShowWindow(hWnd,SW_SHOWNOACTIVATE); ``` i want to put my window behind every window even the taskbar and desktop icons window please help me how can i do this thank...
The Desktop is a ListView control, and the desktop icons are its list items. Top-level windows can be made children of that ListView window, but it is impossible to place a child window between the ListView's background and its list items. The only way to make anything appear behind the items is to draw directly on ...
I use macro for formatted string copy. Example is given below. Code given bellow tries to pad null characters in remaining portion of string. ``` #include <stdio.h> #define LEN 10 #define str(x) #x void main() { char a[LEN]; int b = 3445; sprintf(a, "%-"str(LEN)"d", b); // I want "%-10d" here ...
You'd have to evaluate the argument tostronce more to see the 10 inside the string ``` #define LEN 10 #define str_(x) #x #define str(x) str_(x) ``` the way you did it, the argument tostris stringyfied directly, thus theLENarrived in the format.
I have the following code: ``` int main(int argc, char *argv[]) { int i; for(i = 1; (i+1) < argc; i+=2) { // do something here } return 0; } ``` This code is based on the input for example:command -name 1 -number 2,that is why I need to have this:(i+1) < argc;in the loop, but I got the following lint...
This code is fine. There's not a single unsigned variable or literal in the 9 lines you posted. You are doing something wrong. To find out what, lint those 9 lines exactly and provide us with lint's comments.
Suppose I have dynamically allocated variables in the program run by the debugger, is it safe to press the stop button of the IDE or stop the debugger? I mean safe...will the variables get deleted/deallocated?
Yes. It is safe. When a program exits, all the allocated resources returned to the operating system.
C Language On which C Standard the following code compiles without error (C89, C99, C11) ``` for (int i = 0; i < 10; ++i) { DO SOMETHING... } ``` I understand that some C compilers won't accept the version above and the variable "i" must be declare outside the parentheses. Like so: ``` int i; for (i = 0; i <...
This is allowed since c99. So c99 and c11 support it. In c89, the first clause of aforstatement can only be an expression. In c99 and c11 it can be an expression or a declaration. Only one single declaration is allowed (though this can declare several variables).
I am java programmer and working on JNI. To generate valid DLL file i need to add -Wl,--kill-at linker option in my Eclipse CDT. But I don't know why we require --kill-at and What is it. After searching on net I got below details fromthis link. But I don't understand it properly. Can any one explain me this in deta...
By default, a__stdcallfunction will have a suffix consisting of an@followed by the number of bytes of parameters that function expects, so (for example) a functionFthat takes 3 parameters of 4 bytes apiece would get a name (in the object file) ofF@12. This flag tells the linker that when it creates a DLL, it shouldno...
My code looks like this: (n is a number among 0,1,2 and 3, and loc_A/B/C/D each represents a block of code) ``` int test(int n){ static void *jt[7]= {&&loc_A, &&loc_B, &&loc_C, &&loc_D}; goto *jt[n]; loc_A: ...... loc_B: ...... loc_C: ...... loc_D: ...... } ``` What does "&&loc_A" sta...
Yes, but it's not standard C. Instead, it's aGNU language extension. Therefore, best avoided.
So I'm writing a Unix shell in C, and have been encountering a race condition. I've determined that I can resolve it if, after one of my Fork() calls, I can ensure the parent runs before the child. Is there any way that I can do that using signaling or any other type of inter-process communication?
You could set up a signal handler and let the child wait for it, e.g. SIGUSR1.
Is there any portable way (for now on just for GNU/Linux) to always have a CLOCK_MONOTONIC defined? Or is there a similar way to have such clock which will be portable in Linux environments?I mean: is there any portable way to always have a MONOTONIC clock, not affected by settime()/settimeofday()? Now I use it with ...
In GNU/Linux with sufficiently recent kernels (somewhere in the 2.6.x series), you can use CLOCK_MONOTONIC_RAW, but other than that, portably all you have is CLOCK_MONOTONIC. In case you are unaware, some POSIX systems don't even have clock_gettime, such as OS X (seeMonotonic clock on OS Xfor the OS X way).
Using plain C, (not C++ / C# / Objective-C) how do I get the screen resolution in Windows? My compiler is MingW (not sure if relevant). All solutions I have found online are for C++ or some other C variant.
UseGetSystemMetrics() ``` DWORD dwWidth = GetSystemMetrics(SM_CXSCREEN); DWORD dwHeight = GetSystemMetrics(SM_CYSCREEN); ```
If I draw a cube on the center of my window, I can see only the front side. (OK) When I draw a cube on the bottom right side of my window, I see the front, top and left sides of the cube. (OK) I want to draw the cube on the bottom right side of the window but as my eyes where on the bottom right side (I want to see ...
Simply change the viewport to cover only the bottom right side of the window and draw the cube "in the center".
I have declared a char array like so... ``` char workingString[1032] ``` I am reading into this array with fscanf like so... ``` fscanf(ifp, " %s", &workingString); ``` I get this compile error for this particular line of code where I use fscanf ``` warning; format '%s' expects argument of type 'char *', but argu...
This is because you're taking the address of the array, which means the resulting value has type "pointer to array of 1032 character", butfscanf()needs a plain "pointer to character". Thevalueof the two pointers would be the same, but the type differs. Thus, all you need is to drop the&operator since the name of the ...
According to microsoftHIWORDmacro retrieves the high-order word from the specified 32-bit value. The original definition of macro is: ``` #define HIWORD(l) ((WORD)((((DWORD_PTR)(l)) >> 16) & 0xffff)) ``` For example if the passed argument is aunsigned longvalue0x12345678, return result is0x1234 Rewrite the macro ...
What is purpose of AND operation (& 0xffff) in first macro ? It's not necessary, as the cast will eliminate the high-order bits. I guess it's just there to highlight (to the reader) the fact that bits are being removed.
I am new in AVR programming. I would like to control a variable (uint8_t received_msg) if it is equal to0xFF. would it be correct to do: ``` if (!(received_msg ^ 0xFF)) ``` or do I need to compare bit by bit ``` uint8_t test = 0; test = received_msg ^ 0xFF for (i =0; i<8; i++){ test = 0 & (1<<receive...
If you want to know if a variable is equal to0xff, just test for equality: ``` if (received_message == 0xff) ```
currently I've this but it doesn't put my window behind the desktop ``` SetWindowPos(hWnd,HWND_BOTTOM,0,0,SCREEN_WIDTH,SCREEN_HEIGHT,SWP_FRAMECHANGED); ShowWindow(hWnd,SW_SHOWNOACTIVATE); ``` i want to put my window behind every window even the taskbar and desktop icons window please help me how can i do this thank...
The Desktop is a ListView control, and the desktop icons are its list items. Top-level windows can be made children of that ListView window, but it is impossible to place a child window between the ListView's background and its list items. The only way to make anything appear behind the items is to draw directly on ...
I use macro for formatted string copy. Example is given below. Code given bellow tries to pad null characters in remaining portion of string. ``` #include <stdio.h> #define LEN 10 #define str(x) #x void main() { char a[LEN]; int b = 3445; sprintf(a, "%-"str(LEN)"d", b); // I want "%-10d" here ...
You'd have to evaluate the argument tostronce more to see the 10 inside the string ``` #define LEN 10 #define str_(x) #x #define str(x) str_(x) ``` the way you did it, the argument tostris stringyfied directly, thus theLENarrived in the format.
I have the following code: ``` int main(int argc, char *argv[]) { int i; for(i = 1; (i+1) < argc; i+=2) { // do something here } return 0; } ``` This code is based on the input for example:command -name 1 -number 2,that is why I need to have this:(i+1) < argc;in the loop, but I got the following lint...
This code is fine. There's not a single unsigned variable or literal in the 9 lines you posted. You are doing something wrong. To find out what, lint those 9 lines exactly and provide us with lint's comments.
Suppose I have dynamically allocated variables in the program run by the debugger, is it safe to press the stop button of the IDE or stop the debugger? I mean safe...will the variables get deleted/deallocated?
Yes. It is safe. When a program exits, all the allocated resources returned to the operating system.
I was trying this code: ``` int main() { char *ch="hello"; printf("%u",&ch); return 0; } ``` From the aboveprintf()statement I have address of ch i.e65524My question is Can i find value if any address is given like*(65524)rather than*(&ch)?
Yes, you can: ``` printf("%d\n", *(unsigned char *) 65524); ``` If the address does not point to a valid object, you are invoking undefined behavior.
``` int y=1; int k=2; int *p1; int *p2; p1=&y; p2=&k; p1=p2; *p1=3; *p2=4; printf("%d",y); ``` I am getting the output as 1, can somebody explain me why !! I was expecting it to be 4.
The below comments explain how this works: ``` int y=1; int k=2; int *p1; int *p2; p1=&y; //pointer p1 holds the address of y p2=&k; //pointer p2 holds the address of k p1=p2; //pointer p1 now holds the address which p2 holds, which is the address of k *p1=3; //the value which p1 points to is now 3 (so k equals 3 ...
I'm interested in something likestrstr()function but that I could pass a formatted string as argument, like what I pass toprintf(). To be clear, let's get an example: Suppose that I want to find this text:"abc:123"whereabccould be any string with any size followed by':'and then followed by some integer number. I supp...
You can usesscanf. It takes a string and a format as input and you fill variables as a result. Regular expressions are also something to consider
According toC99standards we can do this ``` int n = 0; scanf("%d",&n); int arr[n]; ``` this is one of the way to create dynamic array in c. Now I want to initialize this array to0like this ``` int arr[n] = {0}; ``` Here my compiler producing error. I want to know can we do this? Is it according to standard? At com...
can we do this? No. But you can do this: ``` int arr[n]; memset(arr, 0, sizeof(arr)); ``` You lose the syntactic sugar for initialization, but you get the functionality.
I am encountering a problem to print multiple variables (say 25) in a function onGDB Prompt. Is there any convenient way to do this instead of printing every variables manually ? can I have a script or a simpler way which can do my job ?
You can print multiple values usingprintfcommand in gdb. ``` printf "%d,%d\n", a, b ``` To use it in future, you can either define a gdb-function or use gdb-history feature. To define a gdb-function, create/modify file$HOME/.gdbinitwith the following conten,define print_all printf "%d,%d\n", a, b end document p...
I'm having to do the following a lot in a USB (libusb) C based command line utility I am writing: ``` char pid[20]; sprintf(pid, "Product ID : %#06x", anInteger); puts(pid); ``` Is there a shorter, one-liner way to do this?
Instead of usingsprintf&puts, just change toprintf: ``` printf("Product ID : %#06x", descriptor.idVendor); ```
I'm trying to compile libzqm on windows using MinGW (GCC 4.8). Compilation terminates with this error: ``` 'strndup' was not declared in this scope ``` So,strndupshould be instring.hright? I tried to add/mingw/x86_64-w64-mingw32/includetoCXXFLAGSbut didn't work. Any suggestion ?
Try to add ``` #define _GNU_SOURCE ``` before ``` #include <string.h> ``` strndupis not standard C but if you use GNU libc, then you do get it by including the extensions as above.
I have one-dimentional array initialized globally in C++ ``` Gfloat cone1[] = { 0.0f, 2.4f, -11.0f, 30.0f, -1.5, 0.0, 0.0 }; ``` I want to update its all values with different numbers of my choice within my main function writing minimum/one line(s) of code. Is it possible? I don't want to do like :- ``` cone1[0] ...
If you are willing to switch to usingstd::vectororstd::arrayyou can use uniform initialization and an assignment. The following example usesstd::vectorfor a variable sized array. ``` #include <vector> int main() { std::vector<Gfloat> cone1 { 0.0f, 2.4f, -11.0f }; cone1 = { 30.0f, -1.5, 0.0 }; } ``` The fo...
Why when I execute this code: ``` #include <stdio.h> #include <string.h> #include <stdlib.h> int main(){ size_t size = 4; char *str = malloc(size); str = "hello"; printf("malloc %s: %d\n", str, size); printf("strlen %s: %d\n", str, strlen(str)); printf("sizeof %s: %d\n", str, sizeof("hello"))...
With your linestr = "hello", you are reassigning your pointer to point to a spot in memory where"hello"is created. What you're doing here is having a small memory leak with yourmalloc, since you no longer have a reference to the requested heap space.
Is there a good way to split a string (in C or C++) by multiple delimiters while keeping the delimiters as part of the split strings? The only way I've found to do this is using regex and I'd rather not have to pull in another library just to do this? (I'm using STL for strings, not using Boost).
Without regexp, though I'm not sure if it's faster or slower: ``` vector<string> split(string& stringToSplit) { vector<string> result; size_t pos = 0, lastPos = 0; while ((pos = stringToSplit.find_first_of(";,|", lastPos)) != string::npos) { result.push_back(stringToSplit.substr(lastPos, pos-l...
Say, I bind0.0.0.0port X, listen on it, and then accept new connection. How can my server find destination IP address the client used to connect to? Also, via which interface (assuming multihomed server) the SYN arrived?
Thegetsockname()call on the socket returned byaccept()will give you the address of the local end of the connection. The best way to determine the interface is probably just to match up the local IP address fromgetsockname()against the interface addresses.
why do i get a kernel crash ofcpuacct_chargewhen i try to allocate 600 blocks of 2 MB memory using -pci_alloc_consistent, is there a better way to do it ?
You are probably running out of 32-bit-addressable memory. If your PCIe chip actually supports larger addresses, your driver should usedma_set_maskanddma_set_consistent_maskto tell the kernel about this. (SeeDocumentation/DMA-API-HOWTO.txt.)
I tried to use an external struct but when I compile my c code I obtained this message: subscripted value is neither array nor pointer nor vector. Why? messaggio.h ``` struct Request { struct { u_int data_len; float *data_val; } data; bool_t last; }; typedef struct Request Request; ``` ...
Thex.datais a struct, so you cannot use[]with it. Maybe you wantx.data.data_val[0]. Try this code: ``` struct Request x; x.data.data_len = 5; // initialize the length, use any value you need x.data.data_val = (float *) malloc(x.data.data_len * sizeof(float)); x.data.data_val[0] = 4.6 ```
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.Closed10 years ago.Improve this question Basically I am a Java programmer, and not very well know about pointers in C. so, ``` #include<stdio.h> ...
This should print "world", yes. It looks a bit like it's trying to play with the GCC built-in preprocessor symbol__TIME__, but of course it's spelled wrong to do that.
My little program: ``` #include <stdio.h> int main() { signed char c = -128; c = -c; printf("%d", c); return 0; } ``` print: ``` -128 ``` Is minus (-) operator portable across CPU?
The operand of the unary minus first undergoes standard promitions, so it is of typeint, which can represent the value-128. The result of the operation is the value128, also of typeint. The conversion frominttosigned char, being a narrowing of signed types, is implementation-defined. (Your implementation seems to do ...
I want to send data from one file descriptor to another via linux-aio without buffering and without transferring data to and from user space. Is such a sendfile64() funktion possible with linux-aio? I looked at some linux-aio examples (in C/C++) and simple file-copy programs. All these examples do reading -> buffer -...
It's possible if you mmap the file, then you can make a aio sendfile. It's faster then sendfile via do_splice and should not sync at i_mutex. Look at the lighttp linux_aio module.
I have this byte:10111011and i want to split into 2 nibble (msb and lsb).After that i want to take the last 2 bits from the lsb (so i want11from1011).I know that:With10011011 >> 4i get the msb (1001)With10011011 & 0xfi get the lsb (1011)Now what can i do to take the11from lsb1011?
Just the same:bits = lsb & 0x03