question
stringlengths
25
894
answer
stringlengths
4
863
Verbatim fromLinux'man shmat: RETURN VALUE[...] on error (void *) -1 is returned, anderrnois set to indicate the cause of the error. (POSIX tells the same using aslightly different wording.) Is there any mandatory rule or definition (standard?) that(void *) -1may not be a valid address?
0xffffffffis technically a valid address in a 32 bit environment but on most operating systems (Certainly Linux/Windows) will be in the reserved kernel part of the address space. That means that in user mode processes it's safe to use it as a error code since no user mode allocation function would return this as a us...
I know that JPG, BMP, GIF and others formats compress image. But can I get snapshot of display and save it without compressing(in binary file) in programming way (using c/c++ for example or other stuff)?
BMP files aren't compressed by default. See here:https://en.wikipedia.org/wiki/BMP_file_format
I m developing an application in which I launch a fork to execute a child process. In the child process I want to create a linked list with many nodes and each node should created withmalloc()and then copy the linked list to the parent. because the linked list is created only in the child and it does not exist in the...
You must use some inter-process communications method, like shared memory, pipes, files on disk, sockets, and so on. Since processes are typically isolated from each other, you can't just pass the pointers around.
I developed a program which create a thread at the beginning. And then I want to kill the thread withpthread_cancel()when the thread is running. BUt if I do this I get a crash. this crash is not always reproduced. some time the program avoid the crash. I see some where thatpthread_cancel()could cause a crash if the ...
I suspect it to be a synchronization problem. What i mean is in a different thread which is dependent on the thread you are terminating, you might be accessing something which might be invalid and causing the crash. Unless you have the whole code to execute we cannot point out the crash. At least try running your cod...
I'm trying to read a text file but before that I want to know how many elements I'm going to read. So I need to count the lines of a text file. So far, I have this: ``` int getLinecount (char *file) { int ch, count = 0; FILE *fp = fopen(file, "r"); if(fp == NULL) { return -1; } while(...
You have a trailing semicolon;after yourifstatement. Then, the block is always executed: ``` { count++; } ```
I declared a variable in this way: ``` int i = 0; ``` I get the warning: ISO C90 forbids mixed declarations and code How can I fix it?
I think you should move the variable declaration to top of block. I.e. ``` { foo(); int i = 0; bar(); } ``` to ``` { int i = 0; foo(); bar(); } ```
I'm currently usingfgetc()in loop for reading whole file. But I need to detectEOFin two iterations of this loop. I know thatEOFcan't be returned to stream usingungetc(). What about using ``` fseek(file, -1, SEEK_CUR) ``` Is it safe and portable to get beforeEOFusingfseekand read it again? Thanks.
You can use ``` fseek(file, 0, SEEK_END) ``` If you try to read from it, you'll get your second EOF. EDIT: Reading the reference more carefully:"Library implementations are allowed to not meaningfully support SEEK_END (therefore, code using it has no real standard portability)." I guess your solution is the best ...
I want to measure memory usage for each thread within process. Is it possible? I'm trying to figure out which thread leaks memory. Edit 1. The pmap for leaking process shows ~600 allocation by [ anon ] ``` ... 63b00000 772K rw--- [ anon ] 63bc1000 252K ----- [ anon ] 63c00000 772K rw--- [ anon ] 63...
No this isn't possible, because memory isn't attached to a thread but to the process. There is no link between a thread and some part of the memory. What you seem to need is a profiler, which would point to the allocation points. One of them (didn't use it in the last decade) isRational Purify.
I want to write an app that receive data from RS232(sometimes using usb connector) port using C/C#. I have searched the web but found nothing. Do u have anything interesting? Articles, tutorials, tips, code snippets, everything is very much appreciated. I have got transmission protocol, but have no idea how to read ...
Take a look at this really great tutorial:http://www.codeproject.com/Articles/8605/Serial-Communication-using-C-and-Whidbey. It offers not only a whole small project but it also explains the basics of serial communication. As for the USB-to-Serial-connector or real RS232 - it doesn't really matter because Windows rec...
I am trying to do something in C and I need an algorithm that returns the largest dimension wise sorted array contained in another array. So, for example if I have the following array: ``` A[5] = {5, 2, 3, 1, 4} ``` it should return: ``` 2, 3, 4 ``` and I can't think of any efficient implementation. Got any ideas?...
Your problem is known as "longest increasing subsequence". An algorithm utilizingdynamic programmingcan befound here, with a good explanation. It has optimal asymptotic complexity ofO(nlogn). The basic idea is, that you keep track of the best possible last element (or rather the index thereof) for a subsequence with...
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.Closed10 years ago. Like in C, can I use a string as an...
Actually yes, but you have to use another syntax: ``` $a = "abcd"; for ($b = 0; $b <= 3; $b++) { echo $a{$b}; } ```
``` FILE * in; in = fopen("file1.bmp", "rb"); if (in == NULL) { perror("file1.bmp"); return ; } ``` Why is it that I am not able to open the *.bmp file.fopen() is returning NULL. Can anyone kindly help me how to successfully open a BMP file. Should I use some other C++ function. If yes, plz let me know. An ...
The file does not exist, or you can't read from it (maybe file permissions)?You might have a working directory issue. Try opening the file with a fully qualified path.Also this is a plain C question
I have developed a library using C++ and C; and the library is working fine with my C++ test program; but it gave me a segmentation fault when the library is used in Python usingc_types. Also,my library works fine under 64 bit OS when I use c_types or C++ test program, it crashes when I switched to 32 bit OS. And my ...
The right is to do it is to launchgdbwithpdb. An example here :calling functions returned as pointers from other functions in ctypes
i just want to know is there any method in current programming languages where a variable name like an array can be generated dynamically for example., ``` for(i=1;i<10;i++) { int a <concatenation operator> i = <some logic on variable i>; printf("the value generated in the logic is %d",a <concatenation operat...
eval perhaps, but I wouldn't use it. To add to Jon Skeet's comment, doing this sort of thing may be possible but is ill-advised for many reasons.
How to be sure what is end of an AT command send to GSM module? I need some character or string that represent end of AT command for every case due to finding when whole response is received. I guess it have something with "\r\n" sequence but, this sequence could be at the beginning of AT command response?
Like you suppose it's\r\n.This defines the end of a line. And it makes only sense to process complete lines. Some commands respons with onlyOK\r\n, some with some data.So you should build at first a parser, who can detect complete lines, so they can be processed with a function that handles responses. Sometimes yo...
I'm expecting h here.But it is showing g. Why? ``` char *c="geek"; printf("%c",++*c); ```
You are attempting to modify a string literal, which isundefined behaviour. This means that nothing definite can be said about what your program will print out, or indeedwhetherit will print anything out. Try: ``` char c[]="geek"; printf("%c",++*c); ``` For further discussion, see theFAQ.
Readingthis Skip List implementationI came across this code fragment: ``` typedef struct nodeStructure{ keyType key; valueType value; node forward[1]; /* variable sized array of forward pointers */ }; ``` To me it seems thatforward[1]denotes a one element array. And the comment calls it avariable siz...
It is called thestruct hack. It is theoldform of theflexible array memberintroduced in C99. This has been used in the past to mimic a variable array in the last member of a structure but it is not a strictly conformning construct in C.
The following code should be working (it's an accepted answer in stackoveflow), but somehow I get two warnings and as a consequence I get a segmentation fault. What's wrong? ``` time_t timer; char buffer[25]; struct tm* tm_info; time(&timer); tm_info = localtime(&timer); strftime(buffer, 25, "%Y:%m:%d%H:%M:%S", tm_...
So... The compiler thinkslocaltimereturns an integer andstrftimedoes not exist? Are you sure you're including<time.h>?
I want to save about 20 country names into one string and then copy them to another but it always do me some mistake, can anybody help me with it? This is my code: ``` char array1[30][30], array2[30][30]; ``` This is how i put them into first array: ``` fscanf(fr, "%s", array1[i]); ``` This all works but when i w...
Did you try passing character by character? ``` for( i = 0; i < 30; i++ ){ for( j = 0; j < 30; j++ ){ targetArray[ i ][ j ] = sourceArray[ i ][ j ]; /* End of the string, stop copying */ if ( sourceArray[ i ][ j ] == '\0' ){ break; } } } ```
Can if defined (XX) be placed inside a struct/union in aheader file? ``` struct { int i; #if defined(xx) int j; #endif }t; ``` I am dealing with a large file base of .c and .h files and I need to know the possible cons of this type of usage.
While completely valid, a definite con to using this is any time you need to uset.jyou would also have to surround it with your#if defined(xx)otherwise you will invoke compiler errors
I have a struct like this: ``` typedef struct { int a; int b; int c; int d; } Hello; ``` then I declare it in this way: ``` Hello hello[6] = {}; ``` Then I got this warning: ISO C forbids empty initializer braces, anyhow I think I need to initialize it, how to do it in the right way?
That's not valid C. The universal zero initializer in C is{0}, not{}.
This question already has answers here:Closed10 years ago. Possible Duplicate:Alternate C syntax for function declaration use cases I see this very different definition ofmain()in an old C-program. (Itdoes compile, with gcc) ``` main(argc, argv) int argc; char *argv[]; { ... ... } ``` What kind...
This is old style of function definition in C. This non-prototype style is marked as obsolescent in the C Standard and should not be used. And omitting the return type (implicitlyint) is no longer permitted in C.
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.Closed10 years ago. How to initialise an element of arr...
To initialise an array ofchar*to allNULLs: ``` char* array[10] = { NULL }; /* The remaining elements are implicitly NULL. */ ``` If you want to provide initial elements forexecv(): ``` char* array[10] = { "/usr/bin/ls", "-l" }; /* Again, remaining elements NULL. */ ``` or if you wish to omit the dimension from the...
I know that JPG, BMP, GIF and others formats compress image. But can I get snapshot of display and save it without compressing(in binary file) in programming way (using c/c++ for example or other stuff)?
BMP files aren't compressed by default. See here:https://en.wikipedia.org/wiki/BMP_file_format
I m developing an application in which I launch a fork to execute a child process. In the child process I want to create a linked list with many nodes and each node should created withmalloc()and then copy the linked list to the parent. because the linked list is created only in the child and it does not exist in the...
You must use some inter-process communications method, like shared memory, pipes, files on disk, sockets, and so on. Since processes are typically isolated from each other, you can't just pass the pointers around.
I developed a program which create a thread at the beginning. And then I want to kill the thread withpthread_cancel()when the thread is running. BUt if I do this I get a crash. this crash is not always reproduced. some time the program avoid the crash. I see some where thatpthread_cancel()could cause a crash if the ...
I suspect it to be a synchronization problem. What i mean is in a different thread which is dependent on the thread you are terminating, you might be accessing something which might be invalid and causing the crash. Unless you have the whole code to execute we cannot point out the crash. At least try running your cod...
I'm trying to read a text file but before that I want to know how many elements I'm going to read. So I need to count the lines of a text file. So far, I have this: ``` int getLinecount (char *file) { int ch, count = 0; FILE *fp = fopen(file, "r"); if(fp == NULL) { return -1; } while(...
You have a trailing semicolon;after yourifstatement. Then, the block is always executed: ``` { count++; } ```
I declared a variable in this way: ``` int i = 0; ``` I get the warning: ISO C90 forbids mixed declarations and code How can I fix it?
I think you should move the variable declaration to top of block. I.e. ``` { foo(); int i = 0; bar(); } ``` to ``` { int i = 0; foo(); bar(); } ```
I'm currently usingfgetc()in loop for reading whole file. But I need to detectEOFin two iterations of this loop. I know thatEOFcan't be returned to stream usingungetc(). What about using ``` fseek(file, -1, SEEK_CUR) ``` Is it safe and portable to get beforeEOFusingfseekand read it again? Thanks.
You can use ``` fseek(file, 0, SEEK_END) ``` If you try to read from it, you'll get your second EOF. EDIT: Reading the reference more carefully:"Library implementations are allowed to not meaningfully support SEEK_END (therefore, code using it has no real standard portability)." I guess your solution is the best ...
I want to measure memory usage for each thread within process. Is it possible? I'm trying to figure out which thread leaks memory. Edit 1. The pmap for leaking process shows ~600 allocation by [ anon ] ``` ... 63b00000 772K rw--- [ anon ] 63bc1000 252K ----- [ anon ] 63c00000 772K rw--- [ anon ] 63...
No this isn't possible, because memory isn't attached to a thread but to the process. There is no link between a thread and some part of the memory. What you seem to need is a profiler, which would point to the allocation points. One of them (didn't use it in the last decade) isRational Purify.
I want to write an app that receive data from RS232(sometimes using usb connector) port using C/C#. I have searched the web but found nothing. Do u have anything interesting? Articles, tutorials, tips, code snippets, everything is very much appreciated. I have got transmission protocol, but have no idea how to read ...
Take a look at this really great tutorial:http://www.codeproject.com/Articles/8605/Serial-Communication-using-C-and-Whidbey. It offers not only a whole small project but it also explains the basics of serial communication. As for the USB-to-Serial-connector or real RS232 - it doesn't really matter because Windows rec...
I am trying to do something in C and I need an algorithm that returns the largest dimension wise sorted array contained in another array. So, for example if I have the following array: ``` A[5] = {5, 2, 3, 1, 4} ``` it should return: ``` 2, 3, 4 ``` and I can't think of any efficient implementation. Got any ideas?...
Your problem is known as "longest increasing subsequence". An algorithm utilizingdynamic programmingcan befound here, with a good explanation. It has optimal asymptotic complexity ofO(nlogn). The basic idea is, that you keep track of the best possible last element (or rather the index thereof) for a subsequence with...
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.Closed10 years ago. Like in C, can I use a string as an...
Actually yes, but you have to use another syntax: ``` $a = "abcd"; for ($b = 0; $b <= 3; $b++) { echo $a{$b}; } ```
``` FILE * in; in = fopen("file1.bmp", "rb"); if (in == NULL) { perror("file1.bmp"); return ; } ``` Why is it that I am not able to open the *.bmp file.fopen() is returning NULL. Can anyone kindly help me how to successfully open a BMP file. Should I use some other C++ function. If yes, plz let me know. An ...
The file does not exist, or you can't read from it (maybe file permissions)?You might have a working directory issue. Try opening the file with a fully qualified path.Also this is a plain C question
I have developed a library using C++ and C; and the library is working fine with my C++ test program; but it gave me a segmentation fault when the library is used in Python usingc_types. Also,my library works fine under 64 bit OS when I use c_types or C++ test program, it crashes when I switched to 32 bit OS. And my ...
The right is to do it is to launchgdbwithpdb. An example here :calling functions returned as pointers from other functions in ctypes
i just want to know is there any method in current programming languages where a variable name like an array can be generated dynamically for example., ``` for(i=1;i<10;i++) { int a <concatenation operator> i = <some logic on variable i>; printf("the value generated in the logic is %d",a <concatenation operat...
eval perhaps, but I wouldn't use it. To add to Jon Skeet's comment, doing this sort of thing may be possible but is ill-advised for many reasons.
How to be sure what is end of an AT command send to GSM module? I need some character or string that represent end of AT command for every case due to finding when whole response is received. I guess it have something with "\r\n" sequence but, this sequence could be at the beginning of AT command response?
Like you suppose it's\r\n.This defines the end of a line. And it makes only sense to process complete lines. Some commands respons with onlyOK\r\n, some with some data.So you should build at first a parser, who can detect complete lines, so they can be processed with a function that handles responses. Sometimes yo...
I'm expecting h here.But it is showing g. Why? ``` char *c="geek"; printf("%c",++*c); ```
You are attempting to modify a string literal, which isundefined behaviour. This means that nothing definite can be said about what your program will print out, or indeedwhetherit will print anything out. Try: ``` char c[]="geek"; printf("%c",++*c); ``` For further discussion, see theFAQ.
If I use onlyunsignedtypes in ternary operator condition, will theseunsignedvariables be automatically converted tosignedtypes? Simple example: ``` unsigned int prevTickSeconds = 48; unsigned int currentTickSeconds = 5; unsigned int secondsLeft = (currentTickSeconds - prevTickSeconds ) ? ...
No, there's no such conversion, as all types areunsigned intand there will be "underflow". NOTE: ``` 60 - prevTickSeconds + currentTickSeconds ``` will be executed if and only ifcurrentTickSeconds - prevTickSecondsis0.
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.Closed10 years ago. Is there a way to perform addition(...
You can search for some hardware designs for arithmetic operators. For addition example, you can find full adder, half adder, then ripple carry adder, carry save adder, carry lookahead adder. Then you can generate lots of code to use bit-wise operators to do those arithmetic operations.
My registry.arm.bin is 600 KB large, and every time my application starts, it takes ~ 0.25 seconds to read and parse it. The problem is that i don't need all the plugins that are located there. I only want almost all of the plugins for AUDIO, and none for VIDEO. How can i trim down my registry, so i reduce it size a...
Just remove the plugins you don't need from your system. They are in /usr/lib/gstreamer-0.10 (or -1.0).
I know how monitor two file descriptors but how about 4 or 5 file descriptors? Here's how I do it with 2 file descriptors. ``` fd_mon = (fd1 > fd2 ? fd1 : fd2) + 1; select(fd_mon, &readfds, NULL, NULL, NULL); ``` How can monitor 3 or more file descriptors?
Use theFD_SETmacro to add file descriptors to the set you're passing toselect. You'll need its palsFD_ZERO,FD_ISSETandFD_CLRtoo. In your case above, just keep calling FD_SET for each file descriptor and the same set. Google - "man select", it even has an example! I don't know how familiar you are with *NIX, butman(sh...
I scan through the byte representation of an int variable and get somewhat unexpected result. If I do ``` int a = 127; cout << (unsigned int) *((char *)&a); ``` I get 127 as expected. If I do ``` int a = 256; cout << (unsigned int) *((char *)&a + 1); ``` I get 1 as expected. But if I do ``` int a = 128; cout << ...
For the same reason that(unsigned int)(char)128is 4294967168:charis signed by default on most commonly used systems. 128 cannot fit in a signed 8-bit quantity, so when you cast it tochar, you get -128 (0x80 in hex). Then, when you cast -128 to anunsigned int, you get 232- 128, which is 4294967168. If you want to ge...
I am reading 512 chars into a buffer and would like to display them in hex. I tried the following approach, but it just outputs the same value all the time, despite different values should be received over the network. ``` char buffer[512]; bzero(buffer, 512); n = read(connection_fd,buffer,511); if (n < 0) printf("ER...
This will read the same 512 byte buffer, but convert eachcharacterto hex on output: ``` char buffer[512]; bzero(buffer, 512); n = read(connection_fd,buffer,511); if (n < 0) printf("ERROR reading from socket"); printf("Here is the message:n\n"); for (int i = 0; i < n; i++) { printf("%02X", buffer[i]); } ```
I'm trying to determine if RAND_MAX can fit inside an unsigned int variable. After looking through the C99 standard, I have only found that RAND_MAX is guaranteed to have a value of at least 32767. While I know that RAND_MAX expands to int value, I'm not sure if it's a long int. Right now I'm working with unsigned lon...
RAND_MAXis the maximum value that can be returned byrand(). Sincerand()is defined as returningint,RAND_MAXwill be no more thanINT_MAX, and therefore also no more thanUINT_MAX.
if I wrote like this: ``` typedef enum { foo_1, foo_2 }foo ; ``` I found that I can use int footype = foo::foo_1in c++ and I can directly use int footype = foo_1in c, so is there a way that can write same code that works both in c++ and c? the code is inside one header file with only one structure.
``` int footype = foo_1; ``` That will compile in both C and C++. ``` int footype = foo::foo_1; ``` This syntax is only necessary for C++11's strongly typed enums.
I'm programing a multithreaded program that needs to intercept system signals (such as SIGINT). I would like to know if there is a normalized way to "catch" these signals like: A Signal is sent, may any thread receive it or only the main() one ?Is there a Posix rule or a programming idiom that specifies how to handle...
It is guaranteed that precisely one thread receives the signal, but it is also unspecifiedwhichthread that is. The proper thing to do is to block signals on all threads but one, so that that thread alone deals with signal handling; or on Linux specifically block threads everywhere and set up a signalfd to catch signa...
I found a very strange behaviour when using gcc's-O3or-O2option. When my program is running under debug mode (-g), it is fine; but it raises a segmentation fault when I turned on-O3or-O2. The segmentation happens when it is running a function withSSE2macro inside; like ``` _m128i polynomial = _mm_set1_epi8(0x1d) ``...
http://gcc.gnu.org/bugzilla/buglist.cgi?bug_status=RESOLVED&resolution=FIXED&target_milestone=4.4.4 Update to a newer version of GCC.
This question already has answers here:Closed10 years ago. Possible Duplicate:Why do I get a segmentation fault when writing to a string? I am new to C/C++, I'm trying to learn it, I have created the following function but it throws an exception, when I'm trying to assign the uppercase value to *string: Unhandled ex...
change ``` char* x = "text"; ``` to ``` char x[] = "text"; ``` DONE
I have been performing bitwise operation on a variable. ``` int p=3,q=5; int a=~p,b=~q; //complement a and b printf("%d %d\t%d %d",p,a,q,b); ``` The theoretical output for 'b' is 10 and in case if it's signed, it has to be -2. But the output is -6. Can someone explain me the working of it?
~is the bitwise complement operator in c (or python) which essentially calculates-x - 1. So a table would look like: ``` 0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 ``` In two's complement representation, if a number x's most significant bit is 1, then the actual value would be −(~x + 1). For instance, ``` 0b11110000 =...
How are called these "widgets" in Gtk+: the widget with blue border and the widgets inside on it? is there equivalent in Gtk+? Note: I'm calling "widget" by following Gtk terminology, because I don't know what its real nomenclature in the KDE environment.
That is called aTreeView­­­­­­­, inside it you will findTreeViewColumnandCellRenderer. The documentation ishere.
I know that both of the functions can be used to output to the console.I readthat question, but no one didn't tell which is prefered to be used when outputing to the console. So which function is better, are there any major differences?
To quote the standard (7.21.6.3 in n1570): Theprintffunction is equivalent tofprintfwith the argumentstdoutinterposed before the arguments toprintf. Soprintfis more convenient when printing to the console, otherwise, there's no difference. Butfprintfis a bit easier to modify if you want to change the output target...
Is there anything you could supply to the atoi function that would produce an error (that may or may not crash the program)? EDIT: An error is defined as anything that would produce a compilation error, or something that would cause the program to terminate during execution.
anything that would produce a compilation error If the argument you supply toatoi()is of an incompatible type, you'll get a compile-time error. something that would cause the program to terminate during execution If you supplyatoi()with an invalidconst char*pointer, the behaviour of your code will be undefined. Whi...
I'm trying to list all the symbols inside a dylib in order to know which one needs to be updated inside my app (as my app store all links to function as well as their name , to create a dynamic module mechanism that auto detect/update functions automatically at runtime). Basically what Im searching for is similar as ...
I thinkrsym_macosxcould give you some helps to do something likenm. I don't know what kind of symbols you really want to do within your code, but you could modify it based on that and Mach-O format.
Does anyone know where can I find a simple client/server WinAPI message queue example? I'd like to create a program that sends data from a client to a server using message queues and I can't find anything useful on the web. Thank you.
TheWM_COPYDATAmessage can be used, but only synchronously. Without usingMSMQ, you'd have to implement your own message queue using named shared memory & named semaphores for asynchronous queues.
Leta,bbe positive integers with different values. Is there any way to simplify these expressions: ``` bool foo(unsigned a, unsigned b) { if (a % 2 == 0) return (b % 2) ^ (a < b); // Should I write "!=" instead of "^" ? else return ! ( (b % 2) ^ (a < b) ); // Should I write "(b % 2) == (a < b...
How is it different from ``` (a%2)^(b%2)^(a<b) ``` which in turn is ``` ((a^b)&1)^(a<b) ``` or, indeed ``` ((a ^ b) & 1) != (a < b) ``` Edited to add:Thinking about it some more, this is just the xor of the first and last bits of(a-b)(if you use 2's complement), so there is probably a machine-specific ASM sequen...
I need a way to have gdb like output for a pointer to a structure which shows all the fields and its addresses and the corresponding values. Is there a clean way to do this instead of printing it member by member. I cannot use any other external tool like pstruct or libgdb. I want to do it from within our C program. I...
Your options are: a) Read the debug symbols from binary and interpret them in the same way as GDB does to determine what the structure members are, and pass that info to a generalized printing routine. b) Compile metadata about your structures into your C program, either manually or with a custom build stage. c) Pr...
Code copy string in C ``` #include <stdio.h> char *copyString(char *,char *); void main() { char *first = (char *)calloc(sizeof(char),10); char *second = (char *)calloc(sizeof(char),10); printf("Enter first string:\t"); scanf("%s",first); printf("%s",copyString(first,second)); } char *copyString(c...
By default,scanfstops reading the standard input stream when a space character' 'is encountered. To fix it, you can use a scanset. ``` scanf("%[^\n]", first); ```
This question already has answers here:Closed10 years ago. Possible Duplicate:How to reverse a singly linked list using only two pointers? This is C code to reverse a linked list. But this isn't producing the desired output. ``` struct node *temp,*prev; while(head->next!=NULL) { temp=prev=head; while(temp...
You will ask yourself this question often in your career, so it's important that you come up with a solution for this. Here are some pointers: Write unit testsfor your code. Start with an empty list, a list with one element, then two, then three.Run the code in a debugger.Add debugprintf()statements which show you wh...
In reading the book "Writing Scientific Software" by Oliveira and Stewart, I came across this interesting passage: "Shared variables are dangerous and should be avoided in shared librariesSo if you are writing a shared or dynamically linked library, avoidstaticorsavedlocal variables and avoid global variables."(page ...
But what aboutstaticmember functions? Are these equally as dangerous in a shared library? Not at all:staticmember functions should not be avoided: unlikestaticvariables that represent shared state,staticmember functions represent shared computations. As long as these computations arestateless, they are not dangerous ...
This question already has answers here:Closed10 years ago. Possible Duplicate:C and C++ : Partial initialization of automatic structure I'm looking for a fast way to init local array with zeros. (By "Fast", I mean "Fast to type.") When I do the following: ``` HANDLE hHandles[32] = {0}; ``` does it zero out the fir...
It initializes all the 32 elements to zero.
I'm looking for an example of 'pure pointer notation' in C. I have an assignment to convert a program to pure pointer notation and it uses a lot of arrays. Also, can you give an example of what would not constitute as pure pointer notation? Thank you in advance for the help.
Pure pointer notation basically just means using pointer arithmetic to address the elements of the array, rather than the[...]array index operator. For example: ``` someArray[10] = newValue; ``` is the same as ``` *(someArray + 10) = newValue; ```
I just want to output 3 integers from the file. Why this doesn't work? I get -1079184140 and similar. ``` int main(int argc, char *argv[]) { FILE* stream = fopen(argv[2], "r"); char line[80]; for (int i = 0; i < 3; i++) { fgets(line, 80, stream); printf("%d \n", line); } fclose(streamForI...
I would usesscanf. ``` int number; sscanf (line, "%d", &number); printf ("%d \n", number); ``` That will pull the first integer on a line. This is not the most secure or robust way, but that is out of scope. PS: ``` fclose(streamForInput); ``` Should be: ``` fclose(stream); ```
I have two integers (gmpz_t), and I need to express them as a fraction (one being the numerator, the other the denominator). The only solution I found is usingchar* mpz_get_str (char *str, int base, mpz_t op)to convert them both tochar*, then concatenate them with a "/" inbetween, and then useint mpq_set_str (mpq_t ro...
Why not convert each tompq_tviampq_set_z, then divide?
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed10 years ago.Improve this question I need a simple version control, practical and preferably free, I count on the help?
You have come to the right place. Go here...its free for 5 users and its in the cloud so you will never lose your code. http://tfs.visualstudio.com/en-us/pricing/information# Otherwise there is GITHUB free for open source https://github.com/ And if you want a local source control there is Subversion or SVN http:...
Let's say I have astructwith a fieldxthat is also astruct(not a pointer to astruct). If I sayobject.x = 0, what is actually happening under the hood?
You'll get a compile error. ``` error: incompatible types in assignment ``` You can't assign anintto a struct variable.
``` int status=0; int PID = fork(); if(PID == 0) { char *path = strcat(pathToken,strcat("/",command)); printf("path: %s\n",path); execl(path,command,"-l",NULL); } else if(PID>0) { printf("pid: %d. ",PID); printf("I'm parent process\n"); wait(&status); } ``` Output: ``` pid: 20027. I'm parent proces...
You are trying to modify a string literal in: ``` strcat("/",command) ``` which leads to undefined behavior. The declaration for strcat is: ``` char * strcat ( char * destination, const char * source ); ``` And it appends a copy of the source string to the destination string.
while calling this function: ``` static inline void writel(unsigned int v, volatile void __iomem *addr) { *(volatile unsigned int __force *)addr = cpu_to_le32(v); } ``` Does the address is absoulute or pass through the MMU?DMA - does writing to address is translated by the MMU?Why the registers address in the sy...
Here is my answers, hope they help you: Yes, address is translated by the MMU. Address passed towritelshould be Virtual Address (VA) obtained viaioremapcall.ioremapwill take Physical Address (PA).No, address is not translated by the MMU. Address passed to DMA should be Physical Address. A typical DMA is a dedicated p...
In reading the book "Writing Scientific Software" by Oliveira and Stewart, I came across this interesting passage: "Shared variables are dangerous and should be avoided in shared librariesSo if you are writing a shared or dynamically linked library, avoidstaticorsavedlocal variables and avoid global variables."(page ...
But what aboutstaticmember functions? Are these equally as dangerous in a shared library? Not at all:staticmember functions should not be avoided: unlikestaticvariables that represent shared state,staticmember functions represent shared computations. As long as these computations arestateless, they are not dangerous ...
This question already has answers here:Closed10 years ago. Possible Duplicate:C and C++ : Partial initialization of automatic structure I'm looking for a fast way to init local array with zeros. (By "Fast", I mean "Fast to type.") When I do the following: ``` HANDLE hHandles[32] = {0}; ``` does it zero out the fir...
It initializes all the 32 elements to zero.
I'm looking for an example of 'pure pointer notation' in C. I have an assignment to convert a program to pure pointer notation and it uses a lot of arrays. Also, can you give an example of what would not constitute as pure pointer notation? Thank you in advance for the help.
Pure pointer notation basically just means using pointer arithmetic to address the elements of the array, rather than the[...]array index operator. For example: ``` someArray[10] = newValue; ``` is the same as ``` *(someArray + 10) = newValue; ```
I just want to output 3 integers from the file. Why this doesn't work? I get -1079184140 and similar. ``` int main(int argc, char *argv[]) { FILE* stream = fopen(argv[2], "r"); char line[80]; for (int i = 0; i < 3; i++) { fgets(line, 80, stream); printf("%d \n", line); } fclose(streamForI...
I would usesscanf. ``` int number; sscanf (line, "%d", &number); printf ("%d \n", number); ``` That will pull the first integer on a line. This is not the most secure or robust way, but that is out of scope. PS: ``` fclose(streamForInput); ``` Should be: ``` fclose(stream); ```
I have two integers (gmpz_t), and I need to express them as a fraction (one being the numerator, the other the denominator). The only solution I found is usingchar* mpz_get_str (char *str, int base, mpz_t op)to convert them both tochar*, then concatenate them with a "/" inbetween, and then useint mpq_set_str (mpq_t ro...
Why not convert each tompq_tviampq_set_z, then divide?
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed10 years ago.Improve this question I need a simple version control, practical and preferably free, I count on the help?
You have come to the right place. Go here...its free for 5 users and its in the cloud so you will never lose your code. http://tfs.visualstudio.com/en-us/pricing/information# Otherwise there is GITHUB free for open source https://github.com/ And if you want a local source control there is Subversion or SVN http:...
Let's say I have astructwith a fieldxthat is also astruct(not a pointer to astruct). If I sayobject.x = 0, what is actually happening under the hood?
You'll get a compile error. ``` error: incompatible types in assignment ``` You can't assign anintto a struct variable.
I have one doubt if i declared global variable with static. file1.c ``` static int a=5; main() { func(); } ``` can it be access in another file2.c using extern ? file2.c ``` func() { extern int a; printf(a); } ``` or only global variable declared without static can be access using extern?
No!staticlimits the scope of the variable to sametranslation unit.staticgives the variable anInternal Linkageand this variable cannot be accessed beyond the translation unit in which was created. If you need to access a variable accross different files just drop thestatickeyword.
``` #define ext4_debug(f, a...) \ do { \ printk(KERN_DEBUG "EXT4-fs DEBUG (%s, %d): %s:", \ __FILE__, __LINE__, __func__); \ printk(KERN_DEBUG f, ## a); \ } while (0) ``` what I dont understand is this ``` ...
Its a token for variadic macros(macros with multiple, variable arguments). Its gcc specific directive that allows 0 or more arguments as an input to, afterfinext4_debug(). Which means,fargument is mandatory,amay or maynot exist. This is same asprintf(const char *fmt,...)where,fmtis mandatory, other arguments are opti...
I have a stringinputwhich contains words separated by white-space. I want to usesscanf()to split the words, store each word ininput_wordand print it, but I'm not sure how to put it in a while loop. This is what I have: ``` char input[max]; char split_input[max]; /* input gets populated here */ while (sscanf(inp...
you're using the wrong function there. Might I suggeststrtok()instead? Read here forstrtok
GCC treatsint i=048;as an error because of048should be octal number, but8can't appear in an octal number. But why couldn't GCC be more intelligent and treat is as a decimal number?
Because it would go against the syntactic rules of the language 'C' if it had interpreted 048 as a decimal. Any number that starts with 0 should be interpreted as "octal". And that's a good thing, because compilers strive hard to be standard-compliant. Also assume you're writing a C parser for your own C compiler th...
Real short and simple: saycol = 10,size = 8. Then the following is executed: ``` col -= size--; ``` So does size get subtracted to 7 before doing the subtraction on col (so col = 3)? Or col = 2? Thanks
size--yields the previous value ofsize, so this is equivalent to: ``` col -= size; -- size; ```
I'm not fairly familiar in C++ stream API and I want to convert a C code using stream in C++, ``` char sHex[20] = {0}; int numid = 2; snprintf( sHex, sizeof(sHex) - 1, "%X", numId ); ```
``` stringstream ss; ss << uppercase << hex << numId; string res = ss.str(); ```
Using fscanf I want to process text that contains two floats, an arbitrary amount of whitespace before, between, or after the floats (including newlines/returns), and a newline character at the very end. If there are more/fewer than two numbers, then I want to detect that and report an error. This seems to work for h...
``` fscanf(f, "%f%f", &one, &two); while (1) { ch = fgetc(f); if (ch == EOF) /* end of input whithout a line break */break; if (ch == '\n') /* input ok */break; if (!isspace((unsigned char)ch)) /* bad input */break; } ```
This question already has answers here:Closed10 years ago. Possible Duplicate:Macro for concatenating two strings in C I have a function that looks something like this: ``` bool module_foo_process(void* bar) { return doMagic(bar); } ``` Now, I'd like to generate it with a macro. For instance, the macro for the ab...
``` #define MY_AMAZING_MACRO(name) \ bool module_##name##_process(void* bar) { return doMagic(bar); } ```
I seem to be more of a noob in C++ than I originally thought. As far as my knowledge of C/C++ goes, this should work. I define a character array then try to assign a pointer to the beginning... What am I doing wrong? ``` // Create character array char str[] = "t xtd 02 1CF00400 08 11 22 33 44 55 66 77 88 0 0 1234.5...
The type ofstrischar[63]. For reference, note that the type of the string literal itself isconst char[63], notconst char *. You take the address of that, which gives you a pointer tochar[63], orchar (*)[63]. You then try to assign that to achar *. What you should do is not take the address and let the array decay int...
I have a for loop of about 100 odd values. I want to have a breakpoint where I can set some value for the iterator variable and then directly go on that program execution state. For example ``` for(int i=0;i<500;i++) { doSomething(); } ``` Here I want to have a breakpoint oni=100;and step through all values from...
Ingdbyou can set conditions on breakpoints. ``` break line if i == 100 ``` Where "line" is the appropriate line number.
``` gcc 4.7.2 c89 ``` Hello, I am getting the following warning: ``` pointer/integer type mismatch in conditional expression ``` I am compiling with the followingCFLAGS -Wall -Wextra ``` fprintf(stderr, "'Failed to open file' Error [ %s ]\n", (errno == 0) ? "None" : strerror(errno)); ``` The program runs...
Check whether you have included<string.h>header. If not, the return value ofstrerrormay be considered as an integer value. It would explain why the program runs ok (the linker can find a matched function namedstrerror, because the C standard library is linked by default), whereas the compiler reports a warning.
I am using POSIXmandatoryfile locks throughfcntl. I'm wondering if those locks are reentrant, ie. can a process acquire a lock it already owns ?
Advisory locks throughfcntlare on a per process base and just accumulate locked intervals on the file for the given process. That is, it is up to the application to keep track of the intervals and any unlock call for an interval will unlock it, regardless on how many lock calls had been made for that interval. Even w...
I'm trying to create an array of threads. In Linux, I did it this like: ``` pthread_t thr[MAXCONNECTIONS]; ``` On Windows, I don't find any replacement for this. Is there anyway to create an array or something that replaces this?
``` HANDLE threads[ThreadCount]; for (int i=0; i < ThreadCount; ++i) { threads[i] = (HANDLE)_beginthreadex( NULL, 0, &ThreadFunc, NULL, 0, &threadID ); } ``` I've left out some stuff but you get the jist. You have an array of HANDLE's instead of physical threads. You can then pass a HANDLE to various functions to...
What can I use instead to write custom streams?
fmemopenis POSIX but not part of the C standard.fopencookieis not part of any standard; it's a GNU function. tmpfilemakes a good portable replacement forfmemopen. These functions are nearly identical except thattmpfiletends to be slower and requiresfreadto get the data back out. In general, if you might need your ou...
Using fscanf I want to process text that contains two floats, an arbitrary amount of whitespace before, between, or after the floats (including newlines/returns), and a newline character at the very end. If there are more/fewer than two numbers, then I want to detect that and report an error. This seems to work for h...
``` fscanf(f, "%f%f", &one, &two); while (1) { ch = fgetc(f); if (ch == EOF) /* end of input whithout a line break */break; if (ch == '\n') /* input ok */break; if (!isspace((unsigned char)ch)) /* bad input */break; } ```
This question already has answers here:Closed10 years ago. Possible Duplicate:Macro for concatenating two strings in C I have a function that looks something like this: ``` bool module_foo_process(void* bar) { return doMagic(bar); } ``` Now, I'd like to generate it with a macro. For instance, the macro for the ab...
``` #define MY_AMAZING_MACRO(name) \ bool module_##name##_process(void* bar) { return doMagic(bar); } ```
I seem to be more of a noob in C++ than I originally thought. As far as my knowledge of C/C++ goes, this should work. I define a character array then try to assign a pointer to the beginning... What am I doing wrong? ``` // Create character array char str[] = "t xtd 02 1CF00400 08 11 22 33 44 55 66 77 88 0 0 1234.5...
The type ofstrischar[63]. For reference, note that the type of the string literal itself isconst char[63], notconst char *. You take the address of that, which gives you a pointer tochar[63], orchar (*)[63]. You then try to assign that to achar *. What you should do is not take the address and let the array decay int...
I have a for loop of about 100 odd values. I want to have a breakpoint where I can set some value for the iterator variable and then directly go on that program execution state. For example ``` for(int i=0;i<500;i++) { doSomething(); } ``` Here I want to have a breakpoint oni=100;and step through all values from...
Ingdbyou can set conditions on breakpoints. ``` break line if i == 100 ``` Where "line" is the appropriate line number.
``` gcc 4.7.2 c89 ``` Hello, I am getting the following warning: ``` pointer/integer type mismatch in conditional expression ``` I am compiling with the followingCFLAGS -Wall -Wextra ``` fprintf(stderr, "'Failed to open file' Error [ %s ]\n", (errno == 0) ? "None" : strerror(errno)); ``` The program runs...
Check whether you have included<string.h>header. If not, the return value ofstrerrormay be considered as an integer value. It would explain why the program runs ok (the linker can find a matched function namedstrerror, because the C standard library is linked by default), whereas the compiler reports a warning.
I am using POSIXmandatoryfile locks throughfcntl. I'm wondering if those locks are reentrant, ie. can a process acquire a lock it already owns ?
Advisory locks throughfcntlare on a per process base and just accumulate locked intervals on the file for the given process. That is, it is up to the application to keep track of the intervals and any unlock call for an interval will unlock it, regardless on how many lock calls had been made for that interval. Even w...
I'm trying to create an array of threads. In Linux, I did it this like: ``` pthread_t thr[MAXCONNECTIONS]; ``` On Windows, I don't find any replacement for this. Is there anyway to create an array or something that replaces this?
``` HANDLE threads[ThreadCount]; for (int i=0; i < ThreadCount; ++i) { threads[i] = (HANDLE)_beginthreadex( NULL, 0, &ThreadFunc, NULL, 0, &threadID ); } ``` I've left out some stuff but you get the jist. You have an array of HANDLE's instead of physical threads. You can then pass a HANDLE to various functions to...
What can I use instead to write custom streams?
fmemopenis POSIX but not part of the C standard.fopencookieis not part of any standard; it's a GNU function. tmpfilemakes a good portable replacement forfmemopen. These functions are nearly identical except thattmpfiletends to be slower and requiresfreadto get the data back out. In general, if you might need your ou...
When I initialize an arraya[][]: ``` int a[2][5]={(8,9,7,67,11),(7,8,9,199,89)}; ``` and then display the array elements. Why do I get: ``` 11 89 0 0 0 0 0 0 0 0 ``` What happens if you use curly braces instead of the first brackets here?
``` (8,9,7,67,11) ``` is an expression using thecomma operatorthat evaluates to 11. The same holds for the other initialiser. So you only initialise the first two elements explicitly, all others are then initialised to 0. Your compiler should warn about a missing level of braces in the initialiser. If you use curly ...
Problem is - I have to implement my own exit(status) with setjmp and longjmp. Maybe someone could give some pointers?
The only solution I think of right now, is to callsetjmpearly inmain, and then create aMyExitfunction which does alongjmpto thesetjmpinmainand does areturnwith some value (provided from thelongjmpcall).
In a generated piece of c code I found something like this (edited): ``` #include <stdio.h> int main() { (void) ( { int i = 1; int y = 2; printf("%d %d\n", i,y); } ); return 0; } ``` I believe I have never seen the construct(void) ( { CODE } )before, nor am I able to figure out wh...
({ })is agccextension called astatement expression. http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html A statement expression yields a value and the(void)cast is probably here to remove the compiler warning or to make explicit that the value of the statement expression is not used. Now(void) ({ })is the same as...