question
stringlengths
25
894
answer
stringlengths
4
863
seeking some advice here. I have a structure which contains a pointer to another structure, something like this: ``` struct item { int type; struct user *owner; }; ``` I also have accessor functions, like this: ``` int item_get_type(const struct item * i); struct user * item_get_owner(const struct item * i...
It's absolutely fine, and it correctly indicates your stated intention.
Fromthis questionit appears it's possible (but perhaps with issues). My question is, can I do this the other way aorund, compile a C/C++ lib in Visual Studio then link it up to xcode and run it on an iOS device. Will Apple have an issue with this if it actually works? I know they're not big fans of DLLs and I'm not to...
You can't do this because the Microsoft compiler targets a different architecture from the architectures that iOS runs on. And that's just for starters. There are no doubt a gazillion other reasons that it won't work, but the architecture is the most obvious block.
see my code ``` #include<stdarg.h> #define DPRINTF(_fmt, ...) debugPrintf(_fmt,__VA_ARGS__) void debugPrintf(const char *fmt, ...) { char buf[128]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); fprintf(stderr,"%s",buf); return; } main() { int a=10; DPRINTF("a is %d...
Just use ``` #define DPRINTF(...) debugPrintf(__VA_ARGS__) ``` variadic macros, other than variadic functions, don't need a fixed argument.
By external variable I mean a variable declared with theexternmodifier (and defined elsewhere in the program). I've been told of this limitation, and couldn't find a confirmation or rebuttal on the web. Is this true? If so, which is the limit? Is it usually enforced by compilers?
The C99 standard specifies several translation limits (5.2.4.1). One of those is : 4095 external identifiers in one translation unit The C89 standard specifies this limit (2.2.4.1) : 511 external identifiers in one translation unit Note that these are minimum limits for conforming implementations, not absolute lim...
In C memory allocation/deallocation done bymallocandfree. In C++ memory allocation/deallocation done bynewanddelete. There are some solutions in C++ forautomatic memory managementlike: Smart Pointers.RAII (Resource Acquisition Is Initialization)Reference counting and cyclic references... But how can I do automatic...
You may use aBoehm garbage collector library.
I've been told this, and couldn't find a confirmation or rebuttal on the web. Is this true? If so, which is the limit? Is it usually enforced by compilers?
ANSI C doesn't concern itself with that kind of thing. There is nothing in §5Environmentin the C99 standard that even talks about "loading a program in memory". The only considerations are what the environment must provide to be conforming with the abstract state machine that is the basis for the language/standard. ...
I thought that the ternary operator returns either a value on the left side or the right side of:depending on the condition. Why does this following piece of code print 1? ``` #include <stdio.h> int main(int argc, char const *argv[]) { int c = 0; (c?c:0)++; printf("%i", c); return 0; } ```
You would appear to have a compiler bug, or perhaps a language extension, since this is not valid C. You need an lvalue in order to apply the++operator, and(c?c:0)is not an lvalue.
I am looking into clearing up my confusion on how to capture and render audio using native code on the Android platform. What I've heard is that theres an API for audio called OpenSL. Is there any recommended guides and tutorials on how to use it? Also, is there any good audio wrappers for OpenSL, such as an OpenAL w...
There's a native audio example included in the samples/ directory of recent ndk releases. It claims to use OpenSL ES
I'm currently learning x86 assembly with "Guide to assembly language in Linux" and on page 241 there is written that only 16 bit words or 32 bit words are saved onto the stack, but is this true? I mean in C a char array consists of single bytes and those are saved onto the stack as C consists of functions which use th...
Even bytes are padded with zeros and converted to 16 bit or 32 bit words before being pushed. Consider the stack as pile of plates of particular size (16 or 32). Is there a way you can push half the size plate .. No ? Even if you want to push the half the size, you would pad it to make the full size plate and then p...
I am trying to do something similar toAppending current time to a new log file each time log4j is initialized.I am usinglog4cfor logging. I would like to be able to create a new log file with each execution of the application. Is it possible to do this, by only modifying the log4crc config file. All help will be great...
Doesn't seem to be possible via any config file. I had to modify the appender used to name the log file based on the current time. I used the functionstime(),localtime()andstrftime()to create the file name
In one function I have written: ``` char *ab; ab=malloc(10); ``` Then in another function I want to know the size of memory pointed by theabpointer. Is there any way that I can know thatabis pointing to 10 chars of memory?
No, you don't have a standard way to do this. You have to pass the size of the pointed-to memory along with the pointer, it's a common solution. I.e. instead of ``` void f(char* x) { //... } ``` use ``` void f(char *x, size_t length) { //.... } ``` and in your code ``` char *ab = malloc( 10 ); f( ab, 10...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago. Could people please rank some progr...
I am assuming you are looking for this:http://en.wikipedia.org/wiki/Comparison_of_programming_languages#Type_systems
I've to deal witholdC- Sourcecode. After I managed to compile it, while running it I get the error message ``` mmap zero page: Operation not permitted ``` Sometimes followed by anSegmentation fault. I've read some stuff about the mmap() command, but I can't get around, where this error message comes from and how I ...
Mapping the zero page is disabled by default, as a security measure (doing so can make someNULLpointer dereference bugs exploitable). You can re-enable it by setting thevm.mmap_min_addrsysctl to 0 (also available at/proc/sys/vm/mmap_min_addr). You should be able to make this the default at boot on Ubuntu by addingvm...
I would like to do the following, but the compiler doesn't like it: ``` unsigned short foo = 1; // do something with foo #if sizeof(short) * CHAR_BIT > 16 foo &= 0xffff; #endif ``` I know this expression can always be fully evaluated at compile time, but maybe it's only evaluated after the preprocessor does it's ...
You can't usesizeofin a preprocessor expression. You might want to do something like this instead: ``` #include <limits.h> #if SHRT_MAX > 32767 /* do soemthing */ #endif ```
I saw some people use this structure for Trie nodes: ``` struct trie_node_st { int count; struct trie_node_st *next[TREE_WIDTH]; }; ``` Is is low efficiency, since we don't always needTREE_WIDTHas length for each array. Or am I misunderstanding something?
It's a CPU/memory trade off. By allocating it up front you use a certain minimum amount of memory to store those pointers (TREE_WIDTH * sizeof (struct trie_node_st *)) bytes, you use less CPU later because this is done at compile time (unless you allocate the struct with malloc()). However, this is hardly an overhead....
I have a number stored as adoubleand want to print it without the decimal places. So if I had the double value919545634521.000000, it is always printed with the decimal places added to it. How can I print it without it so it looks like:919545634521? ``` #include<stdlib.h> int main() { double number = 922034312...
try ``` printf("%.0lf\n",phoneNum); ``` you may also prefer ``` long long phoneNum; phoneNum = strtoll(buffer,NULL,0); printf("%lld\n",phoneNum); ``` instead. Depending on the system, though, you may need other function to convert (I think it's_strtoui64for windows).
How do I read response headers from a response using libCurl in C? The MAN page says this: ``` size_t function( void *ptr, size_t size, size_t nmemb, void *stream) ``` What is thestreamhere? Do I read headers from stream or from ptr? I am currently trying to read code from ptr and passing a struct for stream. And...
The last parameter isn't a stream, it's a void* to your userdata if used. The data to read is in *ptr, and this function will be called once for each header received. (The last parameter is often used to point back to an C++ object instance through a static method using the C-style API...) One example here: http:/...
I have a C function that returns a typefloat. When the function returns1.0f, the receiver sees1065353216, not1.0. What I mean is, the following: ``` float Function() { return 1.0f; } float value; value = Function(); fprintf(stderr, "Printing 1.0f: %f", value); ``` Displays: ``` 1065353216 ``` But not: ```...
You define your function in one source file and call it from another one not providing the signature making the compiler think that the signature isint Function(), which leads to strange results. You should add the signature:float Function();in the file where theprintfis. For example: ``` float Function(); float v...
What's a computationally sane way to, given a natural numbern, generate a random number that is relatively prime ton? I'm willing to sacrifice some randomness and coverage of all possibilities for speed. That is, if I only ever hit perhaps 75% of the possible (smaller) relative primes, that's fine.
"I'm willing to sacrifice randomness and coverage of all possibilities for speed." Given n, select n+1. You're going to need to be more specific.
At one place in a code i call an external tool with thesystem-Call. I work with Wine and program with C. The call is like this: ``` system("blabla.exe outfile"); ``` The command is dynamically generated to change the outfile. A few lines later i try to open the generated file withfopen, butfopenreturnsNULL. If i c...
systemcall is synchronous, according to the man page it returns after the execution ends. I suspect there's something with wine flushing file handles.
I have a gamepad and i want to use the buttons on the joystick to interact with my program. I have been searching for a while now for any solutions and i cant find any. I have the device id and the vendor id are there any good example as to how i can accomplish this?
You might want to look intolibusb, a C library for accessing USB devices. It is available on multiple platforms.
Is there any way (built-in or a code pattern) to ensure that a variadic function is passed the correct number of parameters? (This will be included as part of an API obviously, I can check my own internal code.) I was considering requiring a UN32 Magic Number to be the last argument passed and check that for validit...
va_*macros just pop the variables from the local stack, so you have to trust the user. passing an array/size tuple could be safer, I think.
I have: Windows OS and installed Mingw. I need: API to make console applications. I only know cstdio functions, but I want more powerful interface to control input/output. Any suggestions? Thx.
MSDN has information on all of the Win32 nativeconsole functions. Obviously, code that uses this API will not be portable.
Why does the following print1. I was expecting it to print the address of the function pointer. ``` #include <stdio.h> int main(main) { printf("%i",main); return 0; } ```
Pointers must be printed with%p. Anyway here there's an "aliasing" problem, rather odd but that's it: main gets the value of the first argument to function main that is, what usually is called "argc". if you call it with more arguments, you should see bigger number.
I'm writing a benchmark tool in C++ where I want to clear the filesystem memory cache between experiments. I'm aware of the following console commands: ``` sync echo 3 > /proc/sys/vm/drop_caches ``` My question is how can i do this programmatically directly within C++? Any help is appreciated!
Something like this should do the trick: ``` int fd; char* data = "3"; sync(); fd = open("/proc/sys/vm/drop_caches", O_WRONLY); write(fd, data, sizeof(char)); close(fd); ```
I have a question about typedef in c language. I read the following code: ``` typedef void* (*RT) (int a, int b); ``` what is typedefed in this example?
I suggest you to use the good old "spiral method": ``` +---------------------------------+ | +-------------------+ | | | +----+ | | | | | | | | V V V | | | typedef void * ( * RT | ) (int a, int ...
I'm trying to do it this way: ``` int (*p)(void); int *i; ... p = (int *(void))i; ``` But it's causing syntax error: ``` error: cast specifies function type ``` What's wrong here?
You should respect error in this case. You must not convert a pointer to function to an int pointer or other way around. That might result in undefined behavior. If you insist then, syntax should be: ``` p = (int (*)(void))i; ```
My program needs to load many big wordlist files, so it always takes a long time to start up. it's so inefficient to recover quickly in crash. I have a raw idea, but I am not sure if it's feasible. Is it possible to load the files into shared memory and just attach to it when starting up? Could you give me some idea...
If you're loading 200GB of data, you are either doing something really wrong, or your application doesn't need to startup quickly.
Please, don't misunderstand the question. I know that implementation of the pointers in these two languages is identical, as C is a subset of Objective C. My question is about the actual use of pointers in real code. Are best practices different? What is done differently and why? What should I keep in mind when I lea...
A pointer is still the same kind of pointer in C and Objective-C. The main difference is that C pointers are usually obtained directly throughmalloc/calloc/vallocand are released withfree. When an Objective-C object is being used the pointer is usually obtained by a call to alloc/init and released with a call toreleas...
I am studying the memset function now, but all the examples are regarding to char array as following: ``` char a[100]; memset(a, 0, 100); ``` it will set every element in this char array to 0. I wondered if memset can apply to int array or float array?
Yes, it can apply to any memory buffer, but you must input the correct memory buffer size ...memsettreats any memory buffer as a series of bytes, so whether it'schar,int,float,double, etc, doesn't really matter. Keep in mind though that it will not set multi-byte types to a specific non-zero value ... for example: `...
I'm using MPLAB C32. I want to map my peripherals in streams, in order to do something like: ``` FILE* uart2 = fopen("UART2", 9600, param2, param3); ``` or just ``` FILE* uart2 = fopen("UART"); ``` and then use fprintf to write on it: ``` fprintf(uart2, fmt, params); ``` What's the usual way of creating a FILE? ...
You have to write drivers for each peripheral. Also you have to redefine your FILE* so you can have enough information to call appropriate driver. And also you need to redefine fopen and fprintf functions too. But this is pointless. I don't recommend this kind of practice. There's already built libraryPIC32 Peripheral...
I'm asking the solution inc, NOT command line options. The reason I'm sure it exists is that Apache can be instructed to loaded.sodynamically: ``` load modules/mod_perl.so ``` UPDATE Isn't it too inefficient if I need to search withdlsymone by one?
If you want to load your own modules dynamically, study thedlopen/dlsymfamily of functions. That's what Apache uses to load its modules.man dlopenhas all the information. If you want to link against shared libraries, youmustuse linker command line options to specify where these libraries are. Otherwise your program w...
I am using Ubuntu and Eclipse as an IDE for C/C++. I currently have a big project in Eclipse. Sometimes, I want to test some small functions written in C/C++ but I don't want to re-create a new project in Eclipse. It is much time consuming and slow. I want to ask if there is any better way to do this ? (In the past,...
Use online compiler likeIdeoneorCodepad.Ofcourse, they dont provide you auto code completion feature & other fancy features but that is the price you pay for quick & easy way of checking stand alone functions.
I am looking for my project for a way to play audio in fast\slow motion in IPhone project, it can be also in C or C++.
You want to use a technique called granular synthesis, there are many variations of granular synthesis some can be used to create whole new sounds, but it can also be used to change the playback speed of audio without changing the pitch. It involves chopping audio up into small blocks and the looping over each block, ...
I have learnt that when we pass the array name to sizeof, the name of the array does not decay to the pointer to base address. The code below verifies this fact by giving answer 10. ``` #include <stdio.h> int main(){ int arr[10]; printf("Size of array is %d" , sizeof(arr)/sizeof(int)); return 0; ...
This signature ``` void dimension(int arr[]) ``` isabsolutelyequivalent to ``` void dimension(int *arr) ``` See alsoQuestion 6.4
I think this a silly problem but i tried for a day to resolve this with not luck, so here is. i have register of four vectors (float32x4), and i want to make some process on some of them and the other i want to set it on 0's. For example this problem in c: ``` for (int i=1; i<=4; i++) { float b = 4/i; if(b<...
Like this: ``` const float32x4_t vector_3 = vdupq_n_f32(3.0f); uint32x4_t mask = vcleq_f32(vector_b, vector_3); vector_b = (float32x4_t)vandq_u32((uint32x4_t)vector_b, mask); ```
My Linux process has 4 children. After some execution time all children adopted by the init process. How do we prevent this situation? (this is not the case with Zombie processes). The process is written in C and the OS is Linux. My code calls waitpid! What might be the problem? In 99,99% we don't have this problem....
If your processes are being reparented byinit, that means that their parent process has died. When a process' parent dies,initadopts it so that it can reap the zombie bywait()ing on the child when it (that is,init) receivesSIGCHLD. If you do not wantinitto become the parent of your children, you will have to ensure ...
I work on AS/400 which is sometimes non-POSIX. We also need to compile our code on UNIX. We have an issue with something as simple as #include. On AS/400, we need to write: ``` #include "*LIBL/H/MYLIB" ``` On UNIX, we need to write ``` #include "MYLIB.H" ``` At the moment we have this (ugly) block at the top of e...
You can simply#includesome separate header in every of your source files containing that ugly#ifndefjust once. It's a common practice anyway.
Simple question I hope. I have a function that keeps prompting for user input (characters) and returns a character once it finds that the input is valid under certain conditions. I'm writing tests for this and other similar functions, but don't know how to fake user input. By the way, I'm using scanf() to get user inp...
You can change the behaviour of standard input to read from a file withfreopen. Place the test input in a file and call this before your test. ``` freopen("filename", "r", stdin); ```
I can't achieve rounding a float with the common 0.5 rule.Let's be precise... How may I make such rounds : x.x2 -> x.xx.x5 -> x.x (or x.x+1 would be good also)x.x6 -> x.x+1 So for example : 1.12 -> 1.11.22 -> 1.21.15 -> 1.1 (or 1.2 woudl be good also)1.25 -> 1.2 (or 1.3 woudl be good also)1.16 -> 1.21.26 -> 1.3 I ...
Try this one: ``` round(x * 10.0f) / 10.0f ```
InC, is there a difference between the following declarations: ``` float DoSomething( const float arr[] ); ``` Vs. ``` float DoSomething( const float* arr ); ``` Is one preferable than the other?
No, there isn't any difference. An array is decayed into a pointer whenever it is passed as an argument to a function. I think that using the array syntax is a bit clearer, it gives a hint that it is an array and not just a pointer to one object. There is a quite detailed description of pointers and arrays athttp://...
I'm trying to do it this way: ``` int (*p)(void); int *i; ... p = (int *(void))i; ``` But it's causing syntax error: ``` error: cast specifies function type ``` What's wrong here?
You should respect error in this case. You must not convert a pointer to function to an int pointer or other way around. That might result in undefined behavior. If you insist then, syntax should be: ``` p = (int (*)(void))i; ```
My program needs to load many big wordlist files, so it always takes a long time to start up. it's so inefficient to recover quickly in crash. I have a raw idea, but I am not sure if it's feasible. Is it possible to load the files into shared memory and just attach to it when starting up? Could you give me some idea...
If you're loading 200GB of data, you are either doing something really wrong, or your application doesn't need to startup quickly.
Please, don't misunderstand the question. I know that implementation of the pointers in these two languages is identical, as C is a subset of Objective C. My question is about the actual use of pointers in real code. Are best practices different? What is done differently and why? What should I keep in mind when I lea...
A pointer is still the same kind of pointer in C and Objective-C. The main difference is that C pointers are usually obtained directly throughmalloc/calloc/vallocand are released withfree. When an Objective-C object is being used the pointer is usually obtained by a call to alloc/init and released with a call toreleas...
I am studying the memset function now, but all the examples are regarding to char array as following: ``` char a[100]; memset(a, 0, 100); ``` it will set every element in this char array to 0. I wondered if memset can apply to int array or float array?
Yes, it can apply to any memory buffer, but you must input the correct memory buffer size ...memsettreats any memory buffer as a series of bytes, so whether it'schar,int,float,double, etc, doesn't really matter. Keep in mind though that it will not set multi-byte types to a specific non-zero value ... for example: `...
I'm using MPLAB C32. I want to map my peripherals in streams, in order to do something like: ``` FILE* uart2 = fopen("UART2", 9600, param2, param3); ``` or just ``` FILE* uart2 = fopen("UART"); ``` and then use fprintf to write on it: ``` fprintf(uart2, fmt, params); ``` What's the usual way of creating a FILE? ...
You have to write drivers for each peripheral. Also you have to redefine your FILE* so you can have enough information to call appropriate driver. And also you need to redefine fopen and fprintf functions too. But this is pointless. I don't recommend this kind of practice. There's already built libraryPIC32 Peripheral...
I'm asking the solution inc, NOT command line options. The reason I'm sure it exists is that Apache can be instructed to loaded.sodynamically: ``` load modules/mod_perl.so ``` UPDATE Isn't it too inefficient if I need to search withdlsymone by one?
If you want to load your own modules dynamically, study thedlopen/dlsymfamily of functions. That's what Apache uses to load its modules.man dlopenhas all the information. If you want to link against shared libraries, youmustuse linker command line options to specify where these libraries are. Otherwise your program w...
I am using Ubuntu and Eclipse as an IDE for C/C++. I currently have a big project in Eclipse. Sometimes, I want to test some small functions written in C/C++ but I don't want to re-create a new project in Eclipse. It is much time consuming and slow. I want to ask if there is any better way to do this ? (In the past,...
Use online compiler likeIdeoneorCodepad.Ofcourse, they dont provide you auto code completion feature & other fancy features but that is the price you pay for quick & easy way of checking stand alone functions.
I am looking for my project for a way to play audio in fast\slow motion in IPhone project, it can be also in C or C++.
You want to use a technique called granular synthesis, there are many variations of granular synthesis some can be used to create whole new sounds, but it can also be used to change the playback speed of audio without changing the pitch. It involves chopping audio up into small blocks and the looping over each block, ...
I have learnt that when we pass the array name to sizeof, the name of the array does not decay to the pointer to base address. The code below verifies this fact by giving answer 10. ``` #include <stdio.h> int main(){ int arr[10]; printf("Size of array is %d" , sizeof(arr)/sizeof(int)); return 0; ...
This signature ``` void dimension(int arr[]) ``` isabsolutelyequivalent to ``` void dimension(int *arr) ``` See alsoQuestion 6.4
I think this a silly problem but i tried for a day to resolve this with not luck, so here is. i have register of four vectors (float32x4), and i want to make some process on some of them and the other i want to set it on 0's. For example this problem in c: ``` for (int i=1; i<=4; i++) { float b = 4/i; if(b<...
Like this: ``` const float32x4_t vector_3 = vdupq_n_f32(3.0f); uint32x4_t mask = vcleq_f32(vector_b, vector_3); vector_b = (float32x4_t)vandq_u32((uint32x4_t)vector_b, mask); ```
My Linux process has 4 children. After some execution time all children adopted by the init process. How do we prevent this situation? (this is not the case with Zombie processes). The process is written in C and the OS is Linux. My code calls waitpid! What might be the problem? In 99,99% we don't have this problem....
If your processes are being reparented byinit, that means that their parent process has died. When a process' parent dies,initadopts it so that it can reap the zombie bywait()ing on the child when it (that is,init) receivesSIGCHLD. If you do not wantinitto become the parent of your children, you will have to ensure ...
I work on AS/400 which is sometimes non-POSIX. We also need to compile our code on UNIX. We have an issue with something as simple as #include. On AS/400, we need to write: ``` #include "*LIBL/H/MYLIB" ``` On UNIX, we need to write ``` #include "MYLIB.H" ``` At the moment we have this (ugly) block at the top of e...
You can simply#includesome separate header in every of your source files containing that ugly#ifndefjust once. It's a common practice anyway.
Simple question I hope. I have a function that keeps prompting for user input (characters) and returns a character once it finds that the input is valid under certain conditions. I'm writing tests for this and other similar functions, but don't know how to fake user input. By the way, I'm using scanf() to get user inp...
You can change the behaviour of standard input to read from a file withfreopen. Place the test input in a file and call this before your test. ``` freopen("filename", "r", stdin); ```
I can't achieve rounding a float with the common 0.5 rule.Let's be precise... How may I make such rounds : x.x2 -> x.xx.x5 -> x.x (or x.x+1 would be good also)x.x6 -> x.x+1 So for example : 1.12 -> 1.11.22 -> 1.21.15 -> 1.1 (or 1.2 woudl be good also)1.25 -> 1.2 (or 1.3 woudl be good also)1.16 -> 1.21.26 -> 1.3 I ...
Try this one: ``` round(x * 10.0f) / 10.0f ```
InC, is there a difference between the following declarations: ``` float DoSomething( const float arr[] ); ``` Vs. ``` float DoSomething( const float* arr ); ``` Is one preferable than the other?
No, there isn't any difference. An array is decayed into a pointer whenever it is passed as an argument to a function. I think that using the array syntax is a bit clearer, it gives a hint that it is an array and not just a pointer to one object. There is a quite detailed description of pointers and arrays athttp://...
I have learnt that when we pass the array name to sizeof, the name of the array does not decay to the pointer to base address. The code below verifies this fact by giving answer 10. ``` #include <stdio.h> int main(){ int arr[10]; printf("Size of array is %d" , sizeof(arr)/sizeof(int)); return 0; ...
This signature ``` void dimension(int arr[]) ``` isabsolutelyequivalent to ``` void dimension(int *arr) ``` See alsoQuestion 6.4
I think this a silly problem but i tried for a day to resolve this with not luck, so here is. i have register of four vectors (float32x4), and i want to make some process on some of them and the other i want to set it on 0's. For example this problem in c: ``` for (int i=1; i<=4; i++) { float b = 4/i; if(b<...
Like this: ``` const float32x4_t vector_3 = vdupq_n_f32(3.0f); uint32x4_t mask = vcleq_f32(vector_b, vector_3); vector_b = (float32x4_t)vandq_u32((uint32x4_t)vector_b, mask); ```
My Linux process has 4 children. After some execution time all children adopted by the init process. How do we prevent this situation? (this is not the case with Zombie processes). The process is written in C and the OS is Linux. My code calls waitpid! What might be the problem? In 99,99% we don't have this problem....
If your processes are being reparented byinit, that means that their parent process has died. When a process' parent dies,initadopts it so that it can reap the zombie bywait()ing on the child when it (that is,init) receivesSIGCHLD. If you do not wantinitto become the parent of your children, you will have to ensure ...
I work on AS/400 which is sometimes non-POSIX. We also need to compile our code on UNIX. We have an issue with something as simple as #include. On AS/400, we need to write: ``` #include "*LIBL/H/MYLIB" ``` On UNIX, we need to write ``` #include "MYLIB.H" ``` At the moment we have this (ugly) block at the top of e...
You can simply#includesome separate header in every of your source files containing that ugly#ifndefjust once. It's a common practice anyway.
Simple question I hope. I have a function that keeps prompting for user input (characters) and returns a character once it finds that the input is valid under certain conditions. I'm writing tests for this and other similar functions, but don't know how to fake user input. By the way, I'm using scanf() to get user inp...
You can change the behaviour of standard input to read from a file withfreopen. Place the test input in a file and call this before your test. ``` freopen("filename", "r", stdin); ```
I can't achieve rounding a float with the common 0.5 rule.Let's be precise... How may I make such rounds : x.x2 -> x.xx.x5 -> x.x (or x.x+1 would be good also)x.x6 -> x.x+1 So for example : 1.12 -> 1.11.22 -> 1.21.15 -> 1.1 (or 1.2 woudl be good also)1.25 -> 1.2 (or 1.3 woudl be good also)1.16 -> 1.21.26 -> 1.3 I ...
Try this one: ``` round(x * 10.0f) / 10.0f ```
InC, is there a difference between the following declarations: ``` float DoSomething( const float arr[] ); ``` Vs. ``` float DoSomething( const float* arr ); ``` Is one preferable than the other?
No, there isn't any difference. An array is decayed into a pointer whenever it is passed as an argument to a function. I think that using the array syntax is a bit clearer, it gives a hint that it is an array and not just a pointer to one object. There is a quite detailed description of pointers and arrays athttp://...
I am new to C and C++ and I need help with arrays. I have an array initialized to zero with 500 elements(myDataBinary). Now I have one more array ith values in it say 1,2,3....Now by reading the values (1,2,3...) from(my_data[10]) i want to make the corresponding elements in myDataBinary "1" and rest should be "0". I ...
sizeof(my_data)returns the total size of the array in bytes, not the number of elements. Sinceints are (usually) 2 bytes wide, you're ending up outside the array.
TheC Operator Preference Tablenotes the higher precedence of(). Code: ``` # include <stdio.h> int main() { int temp=2; (temp += 23)++; //Statement 1 ++(temp += 23); //Statement 2 printf("%d",temp); return 0; } ``` My question is while parentheses has higher precedence than pre-fix operator...
Anlvalueis a value that some other value can be assigned to (because it is on the left side of the assignment operator).(temp += 23)is arvalue. Nothing can be assigned to it.
``` ElementObject1 *o1= // An XML document's element with some value ElementObject2 *o2= //A new element with a new value to be replaced ``` I want that "the value at the address which o1 points to" to be changed with the "value at the address which o2 points to" when I say ``` o1=o2 this does not work ``` I ...
Yes , you have to implement the method ``` - (id)copyWithZone: (NSZone *) zone ``` and then say ``` o1 = [o2 copy]; ``` Don't forget to release o1 ``` [o1 release]; ``` and to add the protocol <NSCopying> in your Model @interface
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
I just read through this yesterday. It gives great explanations about the network stack and how to program with it viaC++C. http://beej.us/guide/bgnet/output/html/multipage/index.html It's more or less an eBook, but there are a lot of tutorials and examples. Hope that helps!
Basically, I'm trying to implement the following: echo "asdf" | ./a.out where ./a.out simply prints out "asdf" I know this is probably noob C stuff, but as I'm only a novice C programmer, I thought I'd ask the community. Update: OK, I got it: ``` #include <stdio.h> #include <string.h> int main(void) { char ...
It is coming throughstdin. ``` $ cat stdin.c #include <stdio.h> int main () { int c; while (EOF != (c = fgetc (stdin))) putc (c, stdout); } $ gcc stdin.c $ echo "foo" | ./a.out foo $ ```
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
Write a program which works.Condense it all onto a single line. You don't need to have linefeeds between statements!
I am trying to figure out how to declare a function that returns a pointer to a function that returns a function. It's a circular problem and I don't know if this can be done in c. This is an illustrative example of what I'm trying to do (it does not work): ``` typedef (*)(void) (*fp)(void); fp funkA(void) { ret...
To create completely circular types like this in C, you must use astruct(orunion). In C99: ``` typedef struct fpc { struct fpc (*fp)(void); } fpc; fpc funkB(void); fpc funkA(void) { return (fpc){ funkB }; } fpc funkB(void) { return (fpc){ funkA }; } ``` In C89, you don't have compound literals, so yo...
I have a situation. I have some functions in a header file that are declared with extern keyword. I have their definition in a C file. these two files are in the same directory. I made a visual studio project and include the header file. when I use the functions declared in header file. the program gives me linking er...
Functions don't need to be declared with the extern keyword. It is redundant. Your error message is telling you that one of the functions you define (not just declare) is referencing an extern variable, but that the source file that declares that variable (i.e., where it is declared without the extern keyword) is not...
I have a C program similar in structure to:http://www.csl.mtu.edu/cs4411/www/NOTES/process/fork/exec.html(that is, it's a shell that runs one command with execvp when entered and loops indefinitely until "exit" is entered). What is the best way to kill a child process immediately if an unrecognized command is passed ...
The linked example already does the right thing: the child should unconditionally call_exit()afterexecvp(). Theexecvp()will only return if it fails. (In other words, you don't kill the child process from the parent; you wait for the child process to exit, and write the child process so that it kills itself if the ex...
I am working on a project under which i am going to control lights of one floor of building through the server pc on the same floor using JAVA and C programming.I have almost designed the things but I want to check whether my design is upto the standards or not. I would like to know if there are any such products/pro...
What do you mean by controlling lights? On/off? There are X-10 devices available in market, which can do such type of things. Most of home automation system uses those. They can easily communicate with PC. You can go though this for more details:http://en.wikipedia.org/wiki/X10_%28industry_standard%29
Suppose pidXis a process group leader andXterminates, but other processes in the process group remain running (withXas their pgid). Will Linux prevent the valueXfrom being assigned as a pid to a new process? I ask this because of a failure condition POSIX allows forsetsid: [EPERM] The calling process is already a pr...
Not a problem, becausefork guarantees: The child process ID also shall not match any active process group ID. Andforkis the only way to create new processes.
Lets say this is the time-stamp:2011-07-06T00:00:35.851-07:00 What does that tell me? This is how I am trying to understand it: ``` 2011-07-06 - date 00:00:35 - hh:mm:ss 851 - micro seconds?? 07:00 - what does that tell me? ``` I need to convert this to UTC if possible with C. Edit 0: Thanks for the ...
It says it's July 6th, 2011, 35.851 seconds past midnight, in the GMT-7 time zone. To convert to UTC (GMT-0 timezone), you'd need to add 7 hours (-7 + 7 = 0), making it2011-07-06T07:00:35.851-00:00
This question already has answers here:Closed12 years ago. Possible Duplicate:What does a type followed by _t (underscore-t) represent? I have seen many data structures in Linux environment have post-fix of '_t'. Is there a specific meaning for it?
It's an abbreviation for "type".
I want some window to never receive mouse wheel up/downs, i can control this messages trough my mouse hook fine but is there a way to make a window never receive those messages? I can validate the window trough mouse hook and check if its active then just never send that message to it. I installed mouse hook globall...
AFAIK hooks may not block the message from reaching the wndproc of the appropriate window. You may however achieve what you need by subclassing the appropriate windows. That is, replace the window procedure of the appropriate window (useSetWindowLongPtrwithGWL_WNDPROCflag) by your wndproc. It should pass all the mess...
I have some routines which make several writes to a stdio stream to make a single log message. To keep each message separate, even in multi-threaded applications, I bracket each message with calls to flockfile() and funlockfile(). In my unit tests, I would like to check that the lock hasn't been left dangling, but h...
Since you are doing this in a unit test, mockflockfile()andfunlockfile(). In your mocks you can keep track of the count and verify it is zero when you complete.
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed4 years ago. I am new to C, i have an Increment operator program in C ``` #include<stdio.h> main(){ int a, b; a = 2; b = a + ++a + ++a; printf("%d", b); getchar(); } ``` The ou...
``` a + ++a + ++a; ``` Behaviour for this isundefined. The compiler might generated code that evaluated this as 2 + 4 + 4 or 3 + 3 + 4, but any combination/ordering of incrementing and accessing is a "valid" result.
Im quite confused that what is difference between these two initializations: ``` int (*p)[10]; ``` and ``` int *p[10] ``` I know they both can point to 2D array whose element count in row is 10....
The first is a pointer to array, the second is an array of pointers.
I am new in C, trying to call a function, but it gives me error that I can not understand why int set_price(&colour->type.name); it returns meexpected ‘uint32_t’ but argument is of type ‘uint32_t *’. warning: passing argument ‘int set_price’ makes integer from pointer without a cast where the pointer is house_li...
``` set_price(&colour->type.name); ``` remove the & and you'll be fine ``` set_price(colour->type.name); ``` set_priceexpects an integer as an argument, not a pointer to integer. I suggest that you should reada good C book.
I need some confirmation. I always get correct o/p but someone told me following expression will not work Thanks in advance. ``` #define a 11 #define b 12 #define c 13 // I want if array[i] has values of any of these then do something if( array[i] == (a) ||(b) ||( c)) // some function ...
``` if (array[i] == a || array[i] == b || array[i] == c){ ... } ``` I do wish sometimes that you could sayif (array[i] == [a, b, c])or something to that effect.
I always get either malloc() error. Here is the code: ``` char *data = malloc(200); add_data(data, tableO, line); void add_data(char *data, struct ARP_entryO *tableO, int line) { int i=0; while (i < line) { strcat(data, tableO[i].IPaddr); strcat(data, " "); strcat(data, tableO[i].MACaddr); str...
It's because you dont reset the string to empty string. The malloc function just allocates some memory, you are concatenating strings, but with some "garbage". Sometimes you can receive empty string, sometimes not. The solution is to store empty string there before your loop: ``` data[0] = '\0'; //or data[0] = 0; or...
I was just readinganother questionand this code intrigued me: ``` for(i = 0; i < n; i++) { for(j = 0; j < i*i; j++) { for(k = 0; k < i*j; k++) { pseudo_inner_count++; for(l = 0; l < 10; l++); } } } ``` I don't understand how this can be O(N^6). Can someone ...
Actually it is: The i loop iterates O(N) times, so the value of i is O(N), so we can say O(I)=O(N).The j loop iterates O(I^2) = O(N^2) times (when considered on its own, without the outer loop).The k loop iterates O(I*J) = O(N*N^2) = O(N^3) times.The l loop just iterates 10 times so that is O(1). The loops are neste...
``` if ( ([mobileNumber.text hasPrefix:@"8"] == NO) || ([mobileNumber.text hasPrefix:@"9"] == NO) ) { } ``` I wanna test if mobileNumber has prefix of 8 or 9. What am I doing wrong here? ANSWER: Silly me, it should be AND condition instead of OR.
Should be ``` if(([mobileNumber.text hasPrefix:@"8"] == NO) && ([mobileNumber.text hasPrefix:@"9"] == NO)) { /* Mobile number does NOT have an 8 or 9 in the beginning */ } ``` My comment above is to make sure there isn't a(in front of the mobile number. EDIT: Did not quite understand what you were after.
I'm planning to make an application that has to save data in an SQLite database. Is there some way to make SQLite call a callback function when it has altered the database file? I want to know when the database file has changed so I can make a newversionof it.
You are probably interested in writing anRollback / Commit Hook. These are fairly well documented. You also have the option of writing aUpdate Hookas well, depending on your needs. I think you are best off using a commit hook; so that when the changes have been committed to the database, you can create a version.
please take a look at the two following c statements ``` printf("a very long string"); printf("%s","a very long string"); ``` they produce thesameresult,but there is definitely some differenceunder the hood,so what is the difference and which one isbetter? Please share your ideas!
If you know what the string contents are, you should use the first form because it is more compact. If the string you want to print can come from the user or from any other source such that you do not know what the string contents are, youmustuse the second form; otherwise, your code will be wide open toformat string ...
I am trying to figure out how to declare a function that returns a pointer to a function that returns a function. It's a circular problem and I don't know if this can be done in c. This is an illustrative example of what I'm trying to do (it does not work): ``` typedef (*)(void) (*fp)(void); fp funkA(void) { ret...
To create completely circular types like this in C, you must use astruct(orunion). In C99: ``` typedef struct fpc { struct fpc (*fp)(void); } fpc; fpc funkB(void); fpc funkA(void) { return (fpc){ funkB }; } fpc funkB(void) { return (fpc){ funkA }; } ``` In C89, you don't have compound literals, so yo...
I have a situation. I have some functions in a header file that are declared with extern keyword. I have their definition in a C file. these two files are in the same directory. I made a visual studio project and include the header file. when I use the functions declared in header file. the program gives me linking er...
Functions don't need to be declared with the extern keyword. It is redundant. Your error message is telling you that one of the functions you define (not just declare) is referencing an extern variable, but that the source file that declares that variable (i.e., where it is declared without the extern keyword) is not...
I have a C program similar in structure to:http://www.csl.mtu.edu/cs4411/www/NOTES/process/fork/exec.html(that is, it's a shell that runs one command with execvp when entered and loops indefinitely until "exit" is entered). What is the best way to kill a child process immediately if an unrecognized command is passed ...
The linked example already does the right thing: the child should unconditionally call_exit()afterexecvp(). Theexecvp()will only return if it fails. (In other words, you don't kill the child process from the parent; you wait for the child process to exit, and write the child process so that it kills itself if the ex...
I am working on a project under which i am going to control lights of one floor of building through the server pc on the same floor using JAVA and C programming.I have almost designed the things but I want to check whether my design is upto the standards or not. I would like to know if there are any such products/pro...
What do you mean by controlling lights? On/off? There are X-10 devices available in market, which can do such type of things. Most of home automation system uses those. They can easily communicate with PC. You can go though this for more details:http://en.wikipedia.org/wiki/X10_%28industry_standard%29
Suppose pidXis a process group leader andXterminates, but other processes in the process group remain running (withXas their pgid). Will Linux prevent the valueXfrom being assigned as a pid to a new process? I ask this because of a failure condition POSIX allows forsetsid: [EPERM] The calling process is already a pr...
Not a problem, becausefork guarantees: The child process ID also shall not match any active process group ID. Andforkis the only way to create new processes.
Lets say this is the time-stamp:2011-07-06T00:00:35.851-07:00 What does that tell me? This is how I am trying to understand it: ``` 2011-07-06 - date 00:00:35 - hh:mm:ss 851 - micro seconds?? 07:00 - what does that tell me? ``` I need to convert this to UTC if possible with C. Edit 0: Thanks for the ...
It says it's July 6th, 2011, 35.851 seconds past midnight, in the GMT-7 time zone. To convert to UTC (GMT-0 timezone), you'd need to add 7 hours (-7 + 7 = 0), making it2011-07-06T07:00:35.851-00:00
This question already has answers here:Closed12 years ago. Possible Duplicate:What does a type followed by _t (underscore-t) represent? I have seen many data structures in Linux environment have post-fix of '_t'. Is there a specific meaning for it?
It's an abbreviation for "type".
I want some window to never receive mouse wheel up/downs, i can control this messages trough my mouse hook fine but is there a way to make a window never receive those messages? I can validate the window trough mouse hook and check if its active then just never send that message to it. I installed mouse hook globall...
AFAIK hooks may not block the message from reaching the wndproc of the appropriate window. You may however achieve what you need by subclassing the appropriate windows. That is, replace the window procedure of the appropriate window (useSetWindowLongPtrwithGWL_WNDPROCflag) by your wndproc. It should pass all the mess...
I have some routines which make several writes to a stdio stream to make a single log message. To keep each message separate, even in multi-threaded applications, I bracket each message with calls to flockfile() and funlockfile(). In my unit tests, I would like to check that the lock hasn't been left dangling, but h...
Since you are doing this in a unit test, mockflockfile()andfunlockfile(). In your mocks you can keep track of the count and verify it is zero when you complete.
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed4 years ago. I am new to C, i have an Increment operator program in C ``` #include<stdio.h> main(){ int a, b; a = 2; b = a + ++a + ++a; printf("%d", b); getchar(); } ``` The ou...
``` a + ++a + ++a; ``` Behaviour for this isundefined. The compiler might generated code that evaluated this as 2 + 4 + 4 or 3 + 3 + 4, but any combination/ordering of incrementing and accessing is a "valid" result.
Im quite confused that what is difference between these two initializations: ``` int (*p)[10]; ``` and ``` int *p[10] ``` I know they both can point to 2D array whose element count in row is 10....
The first is a pointer to array, the second is an array of pointers.
I am new in C, trying to call a function, but it gives me error that I can not understand why int set_price(&colour->type.name); it returns meexpected ‘uint32_t’ but argument is of type ‘uint32_t *’. warning: passing argument ‘int set_price’ makes integer from pointer without a cast where the pointer is house_li...
``` set_price(&colour->type.name); ``` remove the & and you'll be fine ``` set_price(colour->type.name); ``` set_priceexpects an integer as an argument, not a pointer to integer. I suggest that you should reada good C book.
I need some confirmation. I always get correct o/p but someone told me following expression will not work Thanks in advance. ``` #define a 11 #define b 12 #define c 13 // I want if array[i] has values of any of these then do something if( array[i] == (a) ||(b) ||( c)) // some function ...
``` if (array[i] == a || array[i] == b || array[i] == c){ ... } ``` I do wish sometimes that you could sayif (array[i] == [a, b, c])or something to that effect.