question
stringlengths
25
894
answer
stringlengths
4
863
As the title suggests, I'd like to know what is Java's equivalent (or most similar) function to C'spoll()function for polling a set of file descriptors?
As @EJP has commented above forjava.nio.channels.Selector ASelectorsupports key-based, non-blocking, multiplexed I/O. In other words, selectors enable you to perform I/O through multiple channels. Selectors are most applicable to socket-backed channels. It is better to take a look at javadoc forjava.nio.channels.Sel...
I'm usingArduino-IRremotecode to read in an AC unit remote on an Arduino Uno R3. There's aunsigned int rawCodes[RAWBUF]. When I setRAWBUFto 255 it all works great. I push it to 256 and it uploads just fine, but there's no response. Is this a memory limitation?According to this, it's not. I should be able to get ~400...
You shouldn't have that limitation. You're playing with high amounts of memory. Are you sure you have enough available memory to do so? Looks like you're talking about runtime errors(of the memory leak/segfault type) here. You can checktotal availablememory or checkthis great article (and code)on how to debug AVR. ...
Here my code..it is giving segmentation fault error...please tell me why...In this small program i am taking one function add() and one variable int add. and inside the main function i am creating a function pointer of add() and trying to print the value of add variable. But it is giving error...plz tell me why?? ```...
No. Function names can be seen as global constant pointers to functions, basically. Your ``` int add = 10; ``` shadowsthe definition of theadd()function, causing your function pointer to be set to10interpreted as a function pointer, which is bad.
``` int main() { struct books { char name; float price; }b1; printf("%u %u",&b1.name,&b1.price); } ``` When I run the above code, I get the following output:- ``` 2686728 2686732 ``` As thesizeof(char)is 1, so why there is a difference of 4 in the above two addresses?
Padding. The compiler inserts 3 bytes of padding between thenameandpricefields so accessingpricedoesn't run into alignment troubles.
I assume that an internal casting happens when we write:arr[i](which is equivalent to*(arr+i)). Becauseican for example be ashort,intorlongor the unsigned variant of any of these three. So my question is simple: which type shouldibe so that no internal conversion takes place? So that the code can run most efficiently...
It's unlikely to make any significant difference to performance. In any case, you should always be using the type that'ssemanticallycorrect, not trying to make premature optimizations for things that aren't going to matter. In the case of indices,size_tis the smallest type that'sa prioricorrect, but you may be able to...
I have to return 1 if bit i in x is set, 0 otherwise in is_set function. I got stuck here. Have no idea what to do next...Any ideas?? Any help will appreciated.... ``` #include <string.h> #include <stdio.h> const char *to_binary(unsigned int x) { static char bits[17]; bits[0] = '\0'; unsigned int z; ...
``` short is_set(unsigned short x, int bit) { return x & (1 << bit) ? 1 : 0; } ``` Alternatively, ``` short is_set(unsigned short x, int bit) { return (x >> bit) & 1; } ```
Is there a way to embed version info such as a git commit hash in an ELF executable such that it can be retrieved from core dumps generated from it?
Seethis questionto get the git hash. Then, change your build procedure (e.g. yourMakefile) to include it. For instance, generate a one line C file with ``` git log --pretty=format:'const char program_git_hash[] = "%H";' \ -n 1 > _prog_hash.c ``` then link your program with_prog_hash.cand remove that file afte...
This question already has answers here:Will C++ exceptions safely propagate through C code?(6 answers)What happens if exception gets thrown "through" c code? [duplicate](5 answers)Closed9 years ago. I'm writing a shared library with a C API, but most code is written in C++. In some places I want to throw exceptions, ...
Not a good idea. You'll be sure to leak memory. A sensible alternative is for you to have a catch site within your C++ library which populates a thread specific error information object and refactor each interface function to have a return status code to signify that an error has been generated. (Cf. Microsoft's Comp...
I'm trying to use this function to remove a value from the front of a queue. It seems to work the first time (though I might be wrong about this) but when freeing a node the second time it triggers a breakpoint which crashes the program. How do I fix this? ``` printf("Value removed = %d\n", dequeue(myQueue)); int de...
You updates a local variable, instead updatingheadin your queue structureq: ``` head = temp->next; // this is local variable ``` should be: ``` q->head = temp->next; ```
As the title suggests, I'd like to know what is Java's equivalent (or most similar) function to C'spoll()function for polling a set of file descriptors?
As @EJP has commented above forjava.nio.channels.Selector ASelectorsupports key-based, non-blocking, multiplexed I/O. In other words, selectors enable you to perform I/O through multiple channels. Selectors are most applicable to socket-backed channels. It is better to take a look at javadoc forjava.nio.channels.Sel...
I'm usingArduino-IRremotecode to read in an AC unit remote on an Arduino Uno R3. There's aunsigned int rawCodes[RAWBUF]. When I setRAWBUFto 255 it all works great. I push it to 256 and it uploads just fine, but there's no response. Is this a memory limitation?According to this, it's not. I should be able to get ~400...
You shouldn't have that limitation. You're playing with high amounts of memory. Are you sure you have enough available memory to do so? Looks like you're talking about runtime errors(of the memory leak/segfault type) here. You can checktotal availablememory or checkthis great article (and code)on how to debug AVR. ...
Here my code..it is giving segmentation fault error...please tell me why...In this small program i am taking one function add() and one variable int add. and inside the main function i am creating a function pointer of add() and trying to print the value of add variable. But it is giving error...plz tell me why?? ```...
No. Function names can be seen as global constant pointers to functions, basically. Your ``` int add = 10; ``` shadowsthe definition of theadd()function, causing your function pointer to be set to10interpreted as a function pointer, which is bad.
``` int main() { struct books { char name; float price; }b1; printf("%u %u",&b1.name,&b1.price); } ``` When I run the above code, I get the following output:- ``` 2686728 2686732 ``` As thesizeof(char)is 1, so why there is a difference of 4 in the above two addresses?
Padding. The compiler inserts 3 bytes of padding between thenameandpricefields so accessingpricedoesn't run into alignment troubles.
I assume that an internal casting happens when we write:arr[i](which is equivalent to*(arr+i)). Becauseican for example be ashort,intorlongor the unsigned variant of any of these three. So my question is simple: which type shouldibe so that no internal conversion takes place? So that the code can run most efficiently...
It's unlikely to make any significant difference to performance. In any case, you should always be using the type that'ssemanticallycorrect, not trying to make premature optimizations for things that aren't going to matter. In the case of indices,size_tis the smallest type that'sa prioricorrect, but you may be able to...
I have to return 1 if bit i in x is set, 0 otherwise in is_set function. I got stuck here. Have no idea what to do next...Any ideas?? Any help will appreciated.... ``` #include <string.h> #include <stdio.h> const char *to_binary(unsigned int x) { static char bits[17]; bits[0] = '\0'; unsigned int z; ...
``` short is_set(unsigned short x, int bit) { return x & (1 << bit) ? 1 : 0; } ``` Alternatively, ``` short is_set(unsigned short x, int bit) { return (x >> bit) & 1; } ```
Is there a way to embed version info such as a git commit hash in an ELF executable such that it can be retrieved from core dumps generated from it?
Seethis questionto get the git hash. Then, change your build procedure (e.g. yourMakefile) to include it. For instance, generate a one line C file with ``` git log --pretty=format:'const char program_git_hash[] = "%H";' \ -n 1 > _prog_hash.c ``` then link your program with_prog_hash.cand remove that file afte...
This question already has answers here:Detect 32-bit or 64-bit of Windows(14 answers)Closed9 years ago. I was looking for a way to determine the above. I could not really find it easily and google somehow couldn't help me much with it too. Thanks.
You need theGetNativeSystemInfo()API Call. The information you are looking for will be returned in theSYSTEM_INFOstructure in thewProcessorArchitecturemember.
I've this code: ``` srand(time(NULL)); int n = rand() % 1 + 0; printf("%d\n", n); ``` But, if i put it (notsrand(time(NULL))) in a loop for e.g., it generates only a sequence of 0. There is another implementation for the random numbers between 0 and 1 or i've forgot something?
If you meant 0or1, your%makes some sense, but you meant% 2(or& 1). Of course, the+ 0is still rather pointless, no idea what you're aiming for there. For an integer result of 0 or 1, just do: ``` const randomBit = rand() % 2; ``` The compiler will probably"strength-reduce"that to: ``` const randomBit = rand() & 1; `...
This question already has answers here:How to undefine a define at commandline using gcc(6 answers)Closed9 years ago. ``` #include <stdio.h> #define DEBUG #ifdef DEBUG #define MAGIC 5 #endif int main(void){ printf("\n magic is %d",MAGIC); return 0; } ``` Now i want to undef DEBUG so this progra...
manGCCsays, ``` -D and -U options are processed in the order they are given on the command line. ``` Seems you cannot undefine a MACRO fromCLIwhich is defined in program.
I have the following config file: ``` [GENERAL_CONFIG] filter_subnetworks = 192.168.105.0/24 1.1.0.0/16 192.168.105.0/24 192.168.105.0/24 1.1.0.0/16 192.168.105.0/24 192.168.105.0/24 1.1.0.0/16 192.168.105.0/24 ``` and i want to read all subnetworks withg_key_file_get_string_list (gkf, "GENERAL_CONFIG",...
It looks like your input file doesn't comply with the formatting required by theglib Key-value file parserfunctions. All key values should be on a single line, and you should have an explicit list separator character (not just space) such as;or,, see theg_key_file_set_list_separator()function. Convert the file to co...
This question already has answers here:Detect 32-bit or 64-bit of Windows(14 answers)Closed9 years ago. I was looking for a way to determine the above. I could not really find it easily and google somehow couldn't help me much with it too. Thanks.
You need theGetNativeSystemInfo()API Call. The information you are looking for will be returned in theSYSTEM_INFOstructure in thewProcessorArchitecturemember.
I've this code: ``` srand(time(NULL)); int n = rand() % 1 + 0; printf("%d\n", n); ``` But, if i put it (notsrand(time(NULL))) in a loop for e.g., it generates only a sequence of 0. There is another implementation for the random numbers between 0 and 1 or i've forgot something?
If you meant 0or1, your%makes some sense, but you meant% 2(or& 1). Of course, the+ 0is still rather pointless, no idea what you're aiming for there. For an integer result of 0 or 1, just do: ``` const randomBit = rand() % 2; ``` The compiler will probably"strength-reduce"that to: ``` const randomBit = rand() & 1; `...
This question already has answers here:How to undefine a define at commandline using gcc(6 answers)Closed9 years ago. ``` #include <stdio.h> #define DEBUG #ifdef DEBUG #define MAGIC 5 #endif int main(void){ printf("\n magic is %d",MAGIC); return 0; } ``` Now i want to undef DEBUG so this progra...
manGCCsays, ``` -D and -U options are processed in the order they are given on the command line. ``` Seems you cannot undefine a MACRO fromCLIwhich is defined in program.
I have the following config file: ``` [GENERAL_CONFIG] filter_subnetworks = 192.168.105.0/24 1.1.0.0/16 192.168.105.0/24 192.168.105.0/24 1.1.0.0/16 192.168.105.0/24 192.168.105.0/24 1.1.0.0/16 192.168.105.0/24 ``` and i want to read all subnetworks withg_key_file_get_string_list (gkf, "GENERAL_CONFIG",...
It looks like your input file doesn't comply with the formatting required by theglib Key-value file parserfunctions. All key values should be on a single line, and you should have an explicit list separator character (not just space) such as;or,, see theg_key_file_set_list_separator()function. Convert the file to co...
I'm going through the C book, and I see this method declaration: ``` double sin(double x) ``` I am trying to run this example, here is what I have: ``` main() { sin(1); } ``` It prints nothing, how do I printsin(x);?
``` double sin(double x) ``` Is a function declared in the math.h header. It can be used anywhere you'd like - in main() or in any other function you write that is called within main(). However, the way you show it called in main will not do anything useful. The sin() function takes a double as an input and returns a...
Given: number of system ticks since cold start viaunsigned int systemTicks(void);number of microseconds per system tick viaunsigned int usPerTick(void); How can I create a fixed-width time stamp string in C? I can be flexible in this format, but would like to support a maximum of 100 minutes and keep millisecond res...
You want to print a fixed width, leading zeroes fractional part for the microseconds. Since there are 6 digits in microseconds, you want, ``` sprintf(timestamp,"%d:%02d.%06d",ticks/60,ticks%60,mseconds); ``` And add struct/pointer flavor to taste...
I am trying to create a simple(supposedly) single line function namedf2that takes one int argument namedx, and returns a double value equal to1.0/xbut doesn't print anything. I am getting error after error, and I am not sure what the protocols are for creating and separating different parts of a function on one line o...
Your code doesn't do any part of what you specify... There is no reason to use scanf. You also use an int to store a floating point value. You also don't return the calculated value. Here is your function, expanded for clarity: ``` double f2(int x){ double val = 1.0 / x; return val; } ``` One line: ``` do...
Given: number of system ticks since cold start viaunsigned int systemTicks(void);number of microseconds per system tick viaunsigned int usPerTick(void); How can I create a fixed-width time stamp string in C? I can be flexible in this format, but would like to support a maximum of 100 minutes and keep millisecond res...
You want to print a fixed width, leading zeroes fractional part for the microseconds. Since there are 6 digits in microseconds, you want, ``` sprintf(timestamp,"%d:%02d.%06d",ticks/60,ticks%60,mseconds); ``` And add struct/pointer flavor to taste...
I am trying to create a simple(supposedly) single line function namedf2that takes one int argument namedx, and returns a double value equal to1.0/xbut doesn't print anything. I am getting error after error, and I am not sure what the protocols are for creating and separating different parts of a function on one line o...
Your code doesn't do any part of what you specify... There is no reason to use scanf. You also use an int to store a floating point value. You also don't return the calculated value. Here is your function, expanded for clarity: ``` double f2(int x){ double val = 1.0 / x; return val; } ``` One line: ``` do...
Here is my code. ``` int main() { char *s; int i = 0; printf("%lu \n", sizeof(s)); s = malloc(sizeof(char) * 2); printf("%lu \n", sizeof(s)); /*Why is this working?*/ while (i <= 5) { s[i] = 'l'; i++; } printf("%s \n", s); printf("%lu \n", sizeof(char)); printf("%lu ...
In my opinion, this should segfault as I'm trying to write more than I allocated. Why is this working? It's not "working"; your code invokes undefined behavior. "Undefined behavior" doesn't mean "your code will segfault." That would bedefinedbehavior. UB means anything can happen. In this case, you're stomping on...
I have a C language code and I'm going to run on a PIC microcontroller.I am using a Mplab IDE 8.92 with Mplab C18 3.46.I've never done this before with microcontroller.Before I have compiled this code using Mingw.But now that the Mplab I use it I get an error:unable to locate 'inttypes.h'How do I solve this problem an...
inttypes.his a C99 file and MPLAB C18 only supports C89. How do I solve this problem and same problems? inttypes.hdefines some macros and includesstdint.hC99 header. Try to remove the include line ofinttypes.hin your source file and declares yourself the missing types (liketypedef unsigned char uint8_t;, etc.).
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do...
Only one I have ever tried with marginal success was. http://www.gnu.org/software/indent/manual/indent.html
Can the name of function and function-like macro be same?Wouldn't this cause any problem?
They could be the same. Depending on how you use the name, either it gets replaced by preprocessor or not. For example ``` //silly but just for demonstration. int addfive(int n) { return n + 5; } #define addfive(n) ((n) + 5) int main(void) { int a; a = addfive(2); //macro a = (addfive)(2); //function...
There is probably a very obvious answer to this, but I was wondering how the compiler knows which line of code my error is on. In some cases it even knows the column. The only way I can think to do this is to tokenize the input string into a 2D array. This would store [lines][tokens]. C/C++ could be tokenized into ...
actually most of it is covered inthe dragon book. Compilers do Lexing/Parsing i.e.: transforming the source code into a tree representation. When doing so each keyword variable etc. is associated with a line and column number. However during parsing the exact origin of the failure might get lost and the information m...
I have an unsigned char and i want to write0x06on the four most significant, and i want to write0x04on its 4 least significant bits. So the Char representation should be like0110 0010 Can some can guide me how i can do this in C?
``` c = (0x06 << 4) | 0x04; ``` Because: ``` 0x04 = 0000 0100 0x06 = 0000 0110 0x06<<4 = 0110 0000 or op: = 0110 0100 ```
I need to compile my C project that is developed on 64 bit Ubuntu Eclipse to 32bit one. I know that I must set -m32 switch for compiler. Is that enough? Where in Eclipse I can do that.
Where in Eclipse I can do thatIt is general way i use to add flags to compiler in eclipse: Right click on project => Properties => C/C++ Build => Settings => In Tool Settings tab choose GCC C++ Compiler or GCC C Compiler => Command (add your flag here) Also you will have to link against 32 bit libraries.
This question already has answers here:# and ## in macros(3 answers)# and ## macros in C [duplicate](1 answer)Closed9 years ago. ``` #include <stdio.h> #define foo(x, y) #x #y int main() { printf("%s\n", foo(k, l)); return 0; } ``` Output:kl I know that ## does concatenation. From the output it seems that...
#stringifiesthe parameter. Seehttp://www.cs.utah.edu/dept/old/texinfo/cpp/cpp.html#SEC15 ##concatenatesstrings. Seehttp://www.cs.utah.edu/dept/old/texinfo/cpp/cpp.html#SEC16
If type of the value cannot be analyzed or found out by looking into the bits(As written in books I have referred), how does the machine know how the value should be manipulated?
C and C++ arestatically typed, meaning that types are a compile-time concept. The compiler generates code to manipulate the bits in a manner appropriate to the type; the machine executes that code, and doesn't need to know anything about the type.
How to makeprintf("\0x41"); to rint 'A' letter. I know, that\0means end of line, but how to deal when I need to print character presented inHEX?
Drop the leading 0 in the hexadecimal character literal: ``` printf("\x41"); ``` Integer literals use0xprefix, characters use\x. You might also want to add a linefeed to make sure it appears: ``` printf("\x41\n"); ``` You can of course also print a single character: ``` printf("%c\n", 0x41); ``` or portably: `...
I am writing Linux Kernel module, where I'm creating some sysfs files to store variables. But I need to implement arrays, something like: ``` struct ats { struct attribute attr; unsigned long value[5]; }; struct ats m_ats = { .attr.name="m_ats", .attr.mode = 0644, .value[0] = 0, .value[1] = 0, ...
You have to do itmanually. You can usesscanfon the incoming string, parse the input and store each value in the array slot. Something like this: ``` sscanf(input_string, "%d %d %d", value[0], value[1], value[3]) ```
I'm looking at some C code that contains this statement. ``` if ( ((uint8_t *)row)[byte] & (1 << (8-bit)) ) value |= (value + 1); ``` What would be the meaning and purpose of putting the AND of a pointer and an integer inside the conditional parentheses?
There are meanings, in other contexts, but that's not what's happening here. It's castingrow(which I assume is a pointer of some sort) to auint8_t *, and then picking out thebyte-thuint8_tin that array.Thatis then bitwise-anded with the shifted-left stuff. It's logically the same as: ``` uint8_t shifted = (1 << (8 ...
I'm trying to reverse some pointers that were read from a binary encoded file. When I try to reverse the pointer 0xfffe0024540 stored in big endian format, I get 0xffffffffe0024540 The pointer is stored in the file in the format: 0000 ff0f 02e0 4045
The behaviour of right-shifting a negative signed integer is implementation dependent, as far as I remember. You should replacelongbyunsigned longoruint64_t.
I want to make xor of anuint16with a floating point number like the following: ``` uint16_t a=20000; double r,x,xo; r=3.8; xo=.1; x=(int) r*xo*(1-xo); c=a^x; ``` When I run the test the following error occurs: ``` invalid operand to binary ^ ``` How can I convertxto an integer value with 16 bit?
The problem is thatxis still a double value. The cast in ``` x=(int) r*xo*(1-xo); ``` truncates the number, but it's still a double number. To do what you want you need to declarexasintor cast right before xor: ``` c=a^((int)x); ```
``` #include <stdio.h> void foo(auto int i); // line 3 int main() { foo(10); } void foo(auto int i) // line 13 { printf("%d\n", i ); } ``` What is wrong in this code? This program is not compiling. Errors I am seeing are as follows: ``` main.c:3:27: error: storage class specified for parameter 'i' v...
autois a storage class specifier. This is used for local variables(automatic local variables) You can't put it in the declaration of function parameter. On compiling you should get the error: ``` [Error] storage class specified for parameter 'i' ``` In C, You are not allowed to put a storage class specifier in the ...
I am very new to programming. I have a little bit of experience with Python, and I am trying to write one of my Python programs in C. Two of the lines of code in my program are as follows: ``` if len(name) <= 20: print("text here") ``` len(name) in Python evaluates the number of characters in the string name, t...
The equivalent C code: ``` if (strlen(name) <= 20) { //code } ```
This is the warning I get. ``` copyit.c: In function ‘main’: copyit.c:15: warning: assignment makes integer from pointer without a cast copyit.c:16: warning: assignment makes integer from pointer without a cast ``` The lines of code that this corresponds to are the ones that begin with pointers (*). ``` char source...
argv is an array of string pointers. You should just changesourceandtargettochar *orconst char *instead of arrays and change the code to ``` source = argv[3]; target = argv[4]; ``` That will make it work. It will also prevent a buffer overflow had you copied the strings into the arrays. It would also mean your app w...
This question already has answers here:C - SizeOf Pointers(4 answers)Determine size of dynamically allocated memory in C(15 answers)Closed9 years ago. What is the problem with the following memory allocation? ``` char *buffer; buffer = (char*)malloc(sizeof(char)*40); printf("buffer size: %ld\n", sizeof(buffer)); ```...
``` sizeof(buffer) ``` returns the size of buffer, which is a pointer to char. Size of pointers to char on your machine is 8.
I'm looking at some C code that contains this statement. ``` if ( ((uint8_t *)row)[byte] & (1 << (8-bit)) ) value |= (value + 1); ``` What would be the meaning and purpose of putting the AND of a pointer and an integer inside the conditional parentheses?
There are meanings, in other contexts, but that's not what's happening here. It's castingrow(which I assume is a pointer of some sort) to auint8_t *, and then picking out thebyte-thuint8_tin that array.Thatis then bitwise-anded with the shifted-left stuff. It's logically the same as: ``` uint8_t shifted = (1 << (8 ...
I have to use the Curl library to send a string to a morse code translator.(http://mattfedder.com/cgi-bin/morse.pl) Then I have to take back the result and extract the translated code. My prof didn't explain curl very well at all and I cannot find any clear examples. I am not by any means asking for people to code it ...
Curl works with webpages/webservices etc. Its library you can use to interact with web apps without writing all the code. read this page. http://curl.haxx.se/libcurl/c/libcurl-tutorial.html (could not comment as i dont have 50 rep sorry)
I created simple dbus service that emits signal with dynamically allocated data argument: ``` file_name = g_strdup("myfile"); ... ... g_signal_emit_by_name (object, "mysignal", file_name); g_free(file_name); ``` In this case signal listeners may receivefile_namestring that was already destroyed. So is it safe to fr...
GSignal emission is synchronous, i.e. all the connected callbacks to a signal are run sequentially byg_signal_emit(), which will return control to you once all callbacks return. thus, it is safe to emit a signal and free the arguments of the signal afterg_signal_emit()returns. if you're using DBus then it's still saf...
New to both python, and fairly beginner in C. Why will the subject code return an error in python? Does the assignment not have a return value?
This is simply not valid in Python. You can't use an assignment as an expression.
I went through the documentation, but still didn't get what does optlen do ingetsockopt(int s, int level, int optname, void *optval, socklen_t *optlen), can anyone explain?
You set it to the size of the data item you're receiving the option value into. On return the size may have been adjusted. The documentation does say that.
This is just an example, but what actually does logical and (&&) operator in this loop (or any other loop). And what means (&&) in this line "equal=equal&&(first->number==end->number)", knowing that equal is an int that is used like boolean - it stores 0 or 1. ``` for(i=1; i<=n/2 && equal; i++){ equal=equal&&...
The loop will continue only if bothi<=n/2ANDequalare true (equalis considered true if != 0). ``` equal=equal&&(first->number==end->number); ``` This line means thatequalwill be true only if it was already true and the conditionfirst->number==end->numberis also true. So, your code is moving the beginning of the list...
As it is stated in the Linuxmanpage Use this constant as the level argument togetsockoptorsetsockoptto manipulate the socket-level options described in this section But I don't get this explanation. What is the purpose ofSOL_SOCKET? What does it do?
When retrieving a socket option, or setting it, you specify the option name as well as the level. When level =SOL_SOCKET, the item will be searched for in the socket itself. For example, suppose we want to set the socket option to reuse the address to 1 (on/true), we pass in the "level"SOL_SOCKETand the value we want...
This question already has an answer here:How to copy a tetrahedron tree structure to CUDA device memory?(1 answer)Closed9 years ago. I have a tree structure like this: ``` struct TetrahedronStruct { int index; int region; TriangleFaces Faces[4]; Vertex Vertices[4]; struct TetrahedronStruct *adjTetrahedrons...
You create an array of TetrahedronStruct, root is the first element, index 0. For an index i, the children are located at4 * i + j, with j in the range [0..4]
``` #include <stdio.h> void main() { int k = m(); printf("%d", k); } void m() { printf("hello"); } ``` Outputhello5 What is the void function returning here? If there is no printf() then the output is1. What is happening here?
Avoidfunction does not return anything. Your program invokes undefined behavior because it implicitly definesmto have return typeint(in C89, if a function is called before it is declared, it's implicitly assumed to have return typeint), but then defines it with return typevoid. If you add a forward-declaration form, ...
I have a dataset composed of n Elements of a fixed size (24 bytes). I want to create an index to be able to search as fast as possible a random element of 24 bytes in this dataset. What algorithm should I use ? Do you know a C library implementing this ? fast read access/search speed is the priority. Memory usage and...
If there's a logical ordering between the elements then aquick sortof the data is a fast way to order the data. Once it's ordered you can then use abinary searchalgorithm to look for elements. This is a O(log N) search, and you'll be hard pressed to get anything faster! std::sortcan be used to sort the data, andstd::...
I created a char array like so: ``` char arr[3] = "bo"; ``` How do I free the memory associated with array I named "arr"?
Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g usingmalloc) as it's allocated on the heap: ``` char *arr = malloc(3 * sizeof(char)); strcpy(arr, "bo"); // ... free(arr); ``` More about dynamic memory allocation:...
``` ADT is the set of operations. ADT's are mathematical abstractions. ``` Does this mean that ADT are same as classes or am i confusing both together ?
The key to the difference isabstract. Think of an ADT more like an interface - a class with only method declarations, no implementation details. As an example, a Stack ADT defines the basic stack operations like push and pop (but says nothing of how these operations should be implemented), while a Stack class would u...
I have to clear the last 5 characters from a string using memset in c; I know only to set the first characters from a string using this function. For example: ``` #include <stdio.h> #include <string.h> int main () { char str[] = "almost every programmer should know memset!"; memset (str,'-',6); puts (str); ...
Use: ``` char str[] = "EVERY C programmer should know memset!"; memset (&str[strlen(str) - 5],'-',5); ``` This will overwrite the last 5 characters with-. Beware that the string hast to have at least 5 characters for this to work correctly.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question I ask this because i'm a beginner in CS and i have this doubt. So it would be nice if pee...
A Pythonlistis essentially an array of object references that keeps track of how many elements it contains. (Conceptually, a Python reference is somewhat similar to a C pointer.) Read more here:Internals of Python list, access and resizing runtimes
I am using Ubuntu disk image for ARM architecture in Qemu and trying to compile a c language program. It produces the following error message during its compile: ``` collect2: ld terminated with signal 11 [Segmentation fault], core dumped qemu: uncaught target signal 11 (Segmentation fault) - core dumped make: *** [m...
Any help? This is a bug in eitherld, or inqemu. You'll need to contact your upstream toolchain provider with a bug report, or try newer versions of binutils andqemu(and hope the bug has been fixed).
Givennandmunsigned integral types, will the expression ``` (n & m) <= m ``` always be true ?
Yes, it is true. It should be readily apparent that a necessary condition fory > xis that at least one bit position is set to1inybut0inx. As&cannot set a bit to1if the corresponding operand bits were not already1, the result cannot be larger than the operands.
I created simple dbus service that emits signal with dynamically allocated data argument: ``` file_name = g_strdup("myfile"); ... ... g_signal_emit_by_name (object, "mysignal", file_name); g_free(file_name); ``` In this case signal listeners may receivefile_namestring that was already destroyed. So is it safe to fr...
GSignal emission is synchronous, i.e. all the connected callbacks to a signal are run sequentially byg_signal_emit(), which will return control to you once all callbacks return. thus, it is safe to emit a signal and free the arguments of the signal afterg_signal_emit()returns. if you're using DBus then it's still saf...
New to both python, and fairly beginner in C. Why will the subject code return an error in python? Does the assignment not have a return value?
This is simply not valid in Python. You can't use an assignment as an expression.
I went through the documentation, but still didn't get what does optlen do ingetsockopt(int s, int level, int optname, void *optval, socklen_t *optlen), can anyone explain?
You set it to the size of the data item you're receiving the option value into. On return the size may have been adjusted. The documentation does say that.
This is just an example, but what actually does logical and (&&) operator in this loop (or any other loop). And what means (&&) in this line "equal=equal&&(first->number==end->number)", knowing that equal is an int that is used like boolean - it stores 0 or 1. ``` for(i=1; i<=n/2 && equal; i++){ equal=equal&&...
The loop will continue only if bothi<=n/2ANDequalare true (equalis considered true if != 0). ``` equal=equal&&(first->number==end->number); ``` This line means thatequalwill be true only if it was already true and the conditionfirst->number==end->numberis also true. So, your code is moving the beginning of the list...
As it is stated in the Linuxmanpage Use this constant as the level argument togetsockoptorsetsockoptto manipulate the socket-level options described in this section But I don't get this explanation. What is the purpose ofSOL_SOCKET? What does it do?
When retrieving a socket option, or setting it, you specify the option name as well as the level. When level =SOL_SOCKET, the item will be searched for in the socket itself. For example, suppose we want to set the socket option to reuse the address to 1 (on/true), we pass in the "level"SOL_SOCKETand the value we want...
This question already has an answer here:How to copy a tetrahedron tree structure to CUDA device memory?(1 answer)Closed9 years ago. I have a tree structure like this: ``` struct TetrahedronStruct { int index; int region; TriangleFaces Faces[4]; Vertex Vertices[4]; struct TetrahedronStruct *adjTetrahedrons...
You create an array of TetrahedronStruct, root is the first element, index 0. For an index i, the children are located at4 * i + j, with j in the range [0..4]
``` #include <stdio.h> void main() { int k = m(); printf("%d", k); } void m() { printf("hello"); } ``` Outputhello5 What is the void function returning here? If there is no printf() then the output is1. What is happening here?
Avoidfunction does not return anything. Your program invokes undefined behavior because it implicitly definesmto have return typeint(in C89, if a function is called before it is declared, it's implicitly assumed to have return typeint), but then defines it with return typevoid. If you add a forward-declaration form, ...
I have a dataset composed of n Elements of a fixed size (24 bytes). I want to create an index to be able to search as fast as possible a random element of 24 bytes in this dataset. What algorithm should I use ? Do you know a C library implementing this ? fast read access/search speed is the priority. Memory usage and...
If there's a logical ordering between the elements then aquick sortof the data is a fast way to order the data. Once it's ordered you can then use abinary searchalgorithm to look for elements. This is a O(log N) search, and you'll be hard pressed to get anything faster! std::sortcan be used to sort the data, andstd::...
I created a char array like so: ``` char arr[3] = "bo"; ``` How do I free the memory associated with array I named "arr"?
Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g usingmalloc) as it's allocated on the heap: ``` char *arr = malloc(3 * sizeof(char)); strcpy(arr, "bo"); // ... free(arr); ``` More about dynamic memory allocation:...
``` ADT is the set of operations. ADT's are mathematical abstractions. ``` Does this mean that ADT are same as classes or am i confusing both together ?
The key to the difference isabstract. Think of an ADT more like an interface - a class with only method declarations, no implementation details. As an example, a Stack ADT defines the basic stack operations like push and pop (but says nothing of how these operations should be implemented), while a Stack class would u...
I have to clear the last 5 characters from a string using memset in c; I know only to set the first characters from a string using this function. For example: ``` #include <stdio.h> #include <string.h> int main () { char str[] = "almost every programmer should know memset!"; memset (str,'-',6); puts (str); ...
Use: ``` char str[] = "EVERY C programmer should know memset!"; memset (&str[strlen(str) - 5],'-',5); ``` This will overwrite the last 5 characters with-. Beware that the string hast to have at least 5 characters for this to work correctly.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question I ask this because i'm a beginner in CS and i have this doubt. So it would be nice if pee...
A Pythonlistis essentially an array of object references that keeps track of how many elements it contains. (Conceptually, a Python reference is somewhat similar to a C pointer.) Read more here:Internals of Python list, access and resizing runtimes
I am using Ubuntu disk image for ARM architecture in Qemu and trying to compile a c language program. It produces the following error message during its compile: ``` collect2: ld terminated with signal 11 [Segmentation fault], core dumped qemu: uncaught target signal 11 (Segmentation fault) - core dumped make: *** [m...
Any help? This is a bug in eitherld, or inqemu. You'll need to contact your upstream toolchain provider with a bug report, or try newer versions of binutils andqemu(and hope the bug has been fixed).
Givennandmunsigned integral types, will the expression ``` (n & m) <= m ``` always be true ?
Yes, it is true. It should be readily apparent that a necessary condition fory > xis that at least one bit position is set to1inybut0inx. As&cannot set a bit to1if the corresponding operand bits were not already1, the result cannot be larger than the operands.
last week asked a question here about having two main(). Last night tried it and getting this error. Take a look please. my header file(top.h): ``` #ifndef TOP_H_ #define TOP_H_ #include <stdio.h> #include <string.h> #define onemain main() #define twomain main() void print(); #endif /* TOP_H_ */ ``` c source file on...
``` #define onemain main() int onemain() ``` This will be pre-processed to: ``` int main()() ``` You need to drop one of the pairs of parens.
I have a code: ``` int double(int *x) { *x = (*x) + (*x); return *x; } int main() { int i = 10; int j; j = double(&i); printf("i= %d, j = %d\n", i, j); return 0; ``` } The output is i = 20, j = 20. Why does the value of i change?
Because you are passing a pointer to i to the double function, which allows it to change it's value. This is known as "pass by reference". If you had just used ints instead of pointers, the value of i would not have changed. This is called "pass by value".
Here's my function. ``` char * substring(int begin, int end, char * string) { int size = end - begin + 1; char * s = (char *)malloc (sizeof(size)); int i; for (i = 0; i < size; i++) { s[i] = string[begin++]; } return s; } ``` So let's say my string was only supposed to be "I". But when I try to print out the...
First, change the line ``` char * s = (char *)malloc (sizeof(size)); ``` to ``` char * s = malloc( size + 1 ); // + 1 for null terminator ``` sizeof (size)gives you the number of bytes in an integer (2 to 4 to 8 depending on your platform), which is not necessarily what you want. Next, use thestrncpyfunction to c...
Suppose I have ``` char *t = "XX"; ``` I am wondering what is the type of &t. Is it char or array?
The type of&tfor any expression is a pointer to the type oft. In this case the type oftischar*hence the the type of&tischar**
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question I was wondering what happens internally so that using Python you don't need to declare a ...
If you look deep down at the C level, all Python objects are of typePyObject*, and allocated on the heap. Variables are just names (usually implemented as hash map entries) you bind to these objects.
``` #include <stdio.h> int main(void) { int w=2*3/2; //1 int x=5%2*3/2; //2 printf("%d %d",w,x); return 0; } ``` OUTPUT 3 1 In (1); it is giving higher precedence to multiplication than division while in (2) its vice versa. Why so?
They have the same precedence and are always executed left to right. ``` 2*3/2 = (2*3)/2 => 3 6/2 => 3 ``` and ``` 5%2*3/2 = ((5%2)*3)/2 => 1 (1*3)/2 => 1 3/2 => 1 (integer gets truncated) ```
I've a function like this (in a filefile_name.c): ``` char function_name(multi_array[][10]) { /*change some character of multi_array*/ return multi_array; } ``` That takesmulti_array, a multidimensional array of characters, changes some characters of the given parameter, and than returnsmulti_arraymodified....
You don't need to return anything. Change: ``` char function_name(multi_array[][10]) ``` To: ``` void function_name(multi_array[][10]) ``` And your code should work fine (function_namewill update whatever array it receives as an argument, as long as the dimensions are correct).
I am working in the some ntfs hardlinks projects. I want to known how to determine if two files (with full path) belongs to the same volume.
A couple of options to find the volume information associated with a file: Find the root path for the two files, and useGetVolumeInformationto find the volume name.Open a handle to the file and pass that toGetVolumeInformationByHandleW. Note thatGetVolumeInformationByHandleWrequires Vista, that is it is not availabl...
``` typedef unsigned char Set; Set s1,s2; s1 = 0xda; PRINT(s1); printf("%d\n", s1); s2 = -s1; printf("%d\n", s2); PRINT(s2); ``` // PRINT shows the binary output What I don't understand is the reason for this output -> 11011010 218 38 00100110 How can the negotiation of s1 saved on s2 (which was obvio...
I'm sure I'm not the only one who didn't get it on the first sight so I'll try to answer it myself. If you do this : s2 = 256-s1; or this: s2 = 0-s1; instead of s2 = -s1; you'll see that it's still the same result. So if you assign it the way I did in my question you've to consider the implicit calculation.
Can I use#include <stdatomic.h>andatomic_thread_fence()withmemory_orderfrom C11 in Linux driver (kernel-space), or do I must to use Linux functions of memory-barriers: http://lxr.free-electrons.com/source/Documentation/memory-barriers.txthttp://lxr.free-electrons.com/source/Documentation/atomic_ops.txt Using: Linux...
If you are writing kernel code, you should do it in C, and do it in the version of C required by the current kernel (shipping gcc). If you want to get it accepted into mainline (or write it as if it were going to get accepted), you should use the Linux functions. You will also find that they work without unexpected su...
I've a function like this (in a filefile_name.c): ``` char function_name(multi_array[][10]) { /*change some character of multi_array*/ return multi_array; } ``` That takesmulti_array, a multidimensional array of characters, changes some characters of the given parameter, and than returnsmulti_arraymodified....
You don't need to return anything. Change: ``` char function_name(multi_array[][10]) ``` To: ``` void function_name(multi_array[][10]) ``` And your code should work fine (function_namewill update whatever array it receives as an argument, as long as the dimensions are correct).
I am working in the some ntfs hardlinks projects. I want to known how to determine if two files (with full path) belongs to the same volume.
A couple of options to find the volume information associated with a file: Find the root path for the two files, and useGetVolumeInformationto find the volume name.Open a handle to the file and pass that toGetVolumeInformationByHandleW. Note thatGetVolumeInformationByHandleWrequires Vista, that is it is not availabl...
``` typedef unsigned char Set; Set s1,s2; s1 = 0xda; PRINT(s1); printf("%d\n", s1); s2 = -s1; printf("%d\n", s2); PRINT(s2); ``` // PRINT shows the binary output What I don't understand is the reason for this output -> 11011010 218 38 00100110 How can the negotiation of s1 saved on s2 (which was obvio...
I'm sure I'm not the only one who didn't get it on the first sight so I'll try to answer it myself. If you do this : s2 = 256-s1; or this: s2 = 0-s1; instead of s2 = -s1; you'll see that it's still the same result. So if you assign it the way I did in my question you've to consider the implicit calculation.
Can I use#include <stdatomic.h>andatomic_thread_fence()withmemory_orderfrom C11 in Linux driver (kernel-space), or do I must to use Linux functions of memory-barriers: http://lxr.free-electrons.com/source/Documentation/memory-barriers.txthttp://lxr.free-electrons.com/source/Documentation/atomic_ops.txt Using: Linux...
If you are writing kernel code, you should do it in C, and do it in the version of C required by the current kernel (shipping gcc). If you want to get it accepted into mainline (or write it as if it were going to get accepted), you should use the Linux functions. You will also find that they work without unexpected su...
This question already has answers here:What should main() return in C and C++?(19 answers)Closed9 years ago. When writing a C/C++ program, specifically with latest compilers, why do we need to return an integer from the main() method? Like int main() and we return "return 0" from it. So what is the exact reason behin...
The return value of main() becomes the exit status of the process. Traditionally, an exit status of zero usually means “OK,” while any non-zero value indicates some kind of error. This is analogous with how many system calls likewise return zero or an error code. Even more information at J. Leffler's epic answer to t...
If I have ``` a = 3; b = 5; ``` How can I make it so that double result = 3e5, but only using variables? I know aeb won't work, obviously.
Try: ``` double result = a * pow(10.0,(double)b); ``` Or, with GNU extensions: ``` double result = a * exp10((double)b); ``` In either case, #include math.h and link with the math library (eg.-lm). This is likely much more efficient than piecing together a string and converting to double.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do...
Cocoa and Objective-C: Up and Running That's a good book I've read. It's available in Canada among other countries.
Im trying to call a C function from C# but im getting a BadImageFormatException. Here is by C function header: ``` extern "C" { __declspec(dllexport) bool validate(char key[]); } ``` Here is how im calling it from C# ``` [DllImport("MyDll.dll")] static extern bool validate(char[] key); ``` Whats wrong here.
When calling native methods, you should compile your c# code to 64 or 32 bit explicitely. ``` project/properties/build/Platform target ```
I have a C struct that is defined as follows: ``` typedef struct { unsigned long int a; } TEST; ``` I want to create a C# equivalent of this struct? Any help? What is confusing me is that "unsigned long int" isat least 32-bit, what does that mean, it's either 32-bit, 64-bit or 16-bit, right?
You want anuintorulongdepending on what anintorlongwason your native C platform: C#uintis 32 bitsC#ulongis 64 bits Theat leastand platform dependency is a necessary concern in C because it is actually translated into machine code and C was developed for many architectures with varyingword sizes. C# on the contrary i...
My program receives arguments from the user ``` int main(int argc, char *argv[]) ``` and I have this function inside some thread (I can't change the function): ``` func(&argc, &argv); ``` As you can see, I need to call the thread, and inside this thread, to callfuncwith those parameters. I saw that there is a way ...
``` struct arg_holder { int argc; char ** argv; }; void * thread_caller(void * arg) { struct arg_holder arg_struct = *(struct arg_holder *)arg; free(arg); return func(arg_struct->argc, arg_struct->argv); } ``` inmain: ``` struct arg_holder * arg_struct = malloc(sizeof(*arg_struct)); arg_struct->...
I've a source code that was written with wrappers to dynamic memory allocation. something like: ``` wrapper_free(void *ptr); wrapper_malloc(size_t size); ``` this was done to ensure portability, and as the code is third-party the problem is to fix the bugs and not rewrite it all. I want to verify the code with cpp...
It should be possible using cppcheck config files, like: ``` <?xml version="1.0"?> <def> <resource> <alloc>wrapper_malloc</alloc> <dealloc>wrapper_free</dealloc> </resource> </def> ```
``` #include<stdio.h> #include<conio.h> int main() { printf("Hello world"); getch(); return 0; } ``` I am writing a simple hello world application using C language but when i run the program the output screen flashes and disappears suddenly??
getch() ( even though _getch() should be used ) will read the stdin. But it is possible that the compiler is optimizing the function out, and it never gets called ending the program. edit: The function getch() is deprecated and _getch() should be used, according tomsdn.
I know it is probably silly and easy question,but I am pretty new to programming.I have the following question about an if operator I saw in one program.Here is the code: ``` d= -12.4; if(d) printf("%d \n", abs((int)d)); else printf("%d \n",(int)(d)); ``` Why does it print 12 instead of -12. I mean why is this s...
Basically ``` if(d) ``` is the same as ``` if(d != 0) ``` it is perfectly valid code.