question
stringlengths
25
894
answer
stringlengths
4
863
I'm trying to print out words stored in a BST of linked lists. When I try to print the word it gives me the "dereferencing pointer to incomplete type" error. My print function is in my header file for the BST struct. In my main function I can print out like this without an issue, but it doesn't seem to want to print ...
struct bst_nodeandstruct ll_nodeshould both be definedbeforeyou usecurrBST->words->word.
I'm currently working on a binary file format for some arbitrary values, including some strings, and string-length values, which are stored asuint32_t's. But I was wondering, if I write the string length withfwriteto a file on a little-endian system, and read that value from the same file withfreadon a big-endian sys...
Yes,fwriteandfreadon an integer makes your file format unportable to another endianness, as other answers correctly state. As of best practice, I woulddiscourage any conditional byte flipping and endianness testing at all. Decide on the endianness of yourfile format, than write and readbytes, and make integers from t...
I recently fell in love with Janus, I can't live without it anymore. I decided to do some C programming and came across this:http://www.vim.org/scripts/script.php?script_id=1000. I have absolutely no idea how to get it to work with Janus, I've spent hours experimenting and researching but to no avail. I came across ...
If you are going to use Janus then you must use Janus by itself without any additional customization. If you would like to use the plugins or themes that Janus provides it is wise to install them manually as to give yourself full control over your own Vim.
I know in C, one way to solve the "initializer element is not constant" error is to create the strcuture inside the main() function. But suppose that I have an array of structs and want to use it as a global array. How can I create and initialize it? ``` struct A *b = malloc(10*sizeof(struct A)); // Want to keep the ...
If you want an array, why don't you declare it as an array? ``` struct A { const char *str; int n; }; struct A b[3] = { { "foo", 1 }, { "bar", 2 }, { "baz", 3 } }; ``` If youwanta global pointer, thenusea global pointer: ``` struct A *b; int main() { b =...
I'm currently adding Toolbar controls to a Windows application. I noticed going through the documentation (MSDN Toolbar) that there's no message or function to remove strings from a Toolbar control, which seems strange since buttons and images can be removed. It's not exactly essential to have this feature, just wonde...
For anyone else that comes across this problem I solved it by using theTB_SETBUTTONINFOmessage to set button text. This way you don't have to add strings to a Toolbar control's string pool. ``` #define ID_BUTTONCOMMAND 101 //... TBBUTTONINFO tbButtonInfo; tbButtonInfo.cbSize = sizeof( TBBUTTONINFO ); tbButtonI...
``` static inline int my_function() __attribute__((always_inline)); static inline int my_function() { //... } ``` So I have declared my function as above although in the binary the function is branched to and not inlined, therefore a simple NOP could render the whole function useless. How can I force Xcode 4...
Your function as you give it here has no prototype: you don't provide the type of the arguments. In C just having()in the declaration means that the function receives an unknown number of arguments. Probably the compiler then supposes not to know enough about the function to inline it. Use(void)to declare a function w...
My codes are like this: ``` #include <iostream> using std::cout; using std::endl; int main(int argc, char *argv[]) { cout << (int)('\0') << endl; cout << (char)(0) << endl; return 0; } ``` I expected to see in terminal like this: ``` $ test-program 0 $ ``` However, what I saw is like this: ``` $ tes...
^@is just how your terminal emulator renders'\0'.
I am trying to write my own C floor function. I am stuck on this code detail. I would just like to know how I can zero out the bottom n bits of an unsigned int. For example, to round 51.5 to 51.0, I need to zero out the bottom 18 bits, and keep the top 14. Since it's a floor function, I want to make a mask to zero ou...
A much simpler way is doing just this: ``` value = (value >> bits) << bits ``` because the shift left will fill it in with zeroes, not whatever was in there.
In C, I encountered an error when I coded the following example: ``` int *pointer; int i = 0; pointer = malloc(10 * sizeof(int)); pointer[i - 1] = 4; ``` Clearlyiis a negative index intopointer. Even if the incorrect piece memory was altered, why was an error only triggered uponfree(pointer)[later on in the code]? ...
Most if not all memory managers (eg: malloc) allocate extra data around the memory you've requested. This extra is to help the memory manager manage the various allocations by adding some of its own data to the allocation. When you did your negative index, you overwrote this extra data. It's not invalid memory per se,...
What I want to do isNOTinitilize a pointer that aligned to a given boundary, instead, it is like some function that can transform/copy the pointer (and the contents it is pointed to)'s phyiscal address to a aligned memory address back and forth, likealignedPtr()in the following code: ``` void func(double * x, int len...
Assuming that the size of the allocated buffer is sufficiently large i.e.len+ alignment required, the implementation would require 2 steps. newPtr = ((orgPtr + (ALIGNMENT - 1)) & ALIGN_MASK);- This will generate the new pointerSince the intended design is to have an inplace computation, copy fromnewPtr + lenbackwards...
How do I open an external EXE file from inside C? I'm trying to write a C program that opens Notepad, and some other applications and I am stuck. Thanks for putting up with my noob level of C ;p
Please trysystem("notepad");which will open the notepad executable. Please note that the path to the executable should be part ofPATHvariable or the full path needs to be given to thesystemcall.
I am wondering if it is possible to connect two pipes or socket. Lets suppose that have two pipes/socketpairs. The first one has two file descriptors A and B, the second one has two file descriptors C and D. Is it possible to connect B to C to be able to write to A and read the data from D? Other then just reading for...
If you simply want to read from one socket and write to another without copying the data to user-space, look athttp://linux.die.net/man/2/sendfile. You need a fairly recent Linux.
I'm writing some self-modifying code and I want to call a C function (call itfoo) from MIPS. I've loaded the mem add offoo,&foointo$t1. Now Ijr/jalr $t1. Will C set$raas my current PC(+8) (before the jump) allowing me to useJRor will I have toJALRinstead (ie, take care of it because C won't)? I can't test this righ...
You have to useJALR. How could the C function possibly know how to set$rafor you?
Is there a way to remove the last number from an integer in C? For example, if the user entered the number: "123" is there a way to change that to just "12"? Thanks
Divide that integer number by 10. 123 / 10 == 12.
I have wrote some files: main.c, functions.c, functions2.c, and header.h. The some functions in the functions.c, and functions2 use my some enums, and structures. Where must I place my enums, and structures? How to write declarations for them in the functions.c, and functions2.c? My functions (from different files) h...
Example for functions.c: ``` #include "header.h" int func(void) { ... } void func2(int) { } ``` Example for header.h: ``` #ifndef HEADER_H #define HEADER_H int func(void); void func2(int); enum eMyEnum { eZero = 0, eOne, eTwo }; struct sMyStruct { int i; float f; }; #endif ```
This question already has answers here:How do you initialise a dynamic array in C++?(10 answers)Closed10 years ago. Is there a way in c++ to fill an array allocated like this ``` int **a = new int[4][2]; ``` so that it's filled with values in one line like this ``` int a [4][2] = {{2,3,4},{5,6,7}}; ```
You can do it in C++11 withuniversal initialization notation: ``` int(*a)[2] = new int[2][2]{{1,2},{3,4}}; ```
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. ``` int main(int argc, char * argv[...
argv[2]is achar *, so that would makeargv[2][5]achar strncatacceptschar *parameters only!
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question Can you please tell me how to start NSight in VS 2010? I have downloaded and installed correctly CUDA toolk...
Nsight Visual Studio Edition is a separate download. The current version is Nsight 3.0 RC1. The installer can be downloaded for free from NVIDIA Registered Developer Program. TheNsight Visual Studio Edition home pagehas links to download Nsight as well as links to the User Guide, Getting Started Documents, and Webina...
According tohttp://linux.die.net/man/3/sprintfandhttp://www.cplusplus.com/reference/cstdio/sprintf/sprintf()and family return the number of characters written on success. On failure, a negative value is returned. I would assume that an error could occur if the format string is malformed so a negative return value coul...
C++ defers to C and C does not require or mentionerrnoin the description ofsprintf()and family (although for certain format specifiers, these functions are defined to callmbrtowc(), which may setEILSEQinerrno) POSIX requires that errno is set: If an output error was encountered, these functions shall return a negati...
I want to define a constant depending on the OS in use.As such: ``` #include <stdio.h> #ifdef _Win32 //Used for system("cls") command #include <process.h> #define CLEAR "system(\"cls\")" #endif #ifdef __APPLE__ #define CLEAR "system(\"clear\")" #endif int main() { CLEAR; } ``` Xcode gives me an error st...
Use: ``` #define CLEAR system("clear") ``` not ``` #define CLEAR "system(\"clear\")" ``` You get the error because your macro call is substituted with: ``` "system(\"clear\")"; ``` which is a useless expression statement (the expression being the string here) like for example: ``` 0; // valid but pointless ``...
Please have a look at this code: ``` #include <stdio.h> int main(void) { short s; int i = 65696; float f = 65696.0F; printf("sizeof(short) = %lu\n", sizeof(short)); s = i; printf("s = %hd\n", s); s = f; printf("s = %hd\n", s); s = 65696; printf("s = %hd\n", s); s = 6569...
Because if the integral part of the float value is not representable in the new type, the conversion is undefined behavior. In your case,SHRT_MAXis probably 32767 and so the integral part of65696.0Fis then not representable in ashortobject.
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. I had the idea recently to write my...
TryLinux From Scratch: Linux From Scratch (LFS) is a project that provides you with step-by-step instructions for building your own custom Linux system, entirely from source code.
I need a Random Number Generator that produces same sequence of numbers both in iOS and Android if we give the same Seed in both. I tried the rand() function with the srand(1000). But it gave different outputs. Then I tried mersenne twister. But that too gave difference sequence for same seed. Could any one please h...
You can just write your own random number generator like this. The quality is low but will suit for most of the purpose. ``` // RAND_MAX assumed to be 32767. static unsigned long int next = 1; void srand(unsigned int seed) { next = seed; } int rand(void) { next = next * 1103515245 + 12345; return (unsigned in...
my question is: how to implement something like thread local storage using Lua stack (lua_State)? Some value that will be stored in the lua state, accessible to lua scripts and from C API.
There are several ways to do this. I wrote a paper about it; it's Chapter 1 inLua Programming Gems The easiest way may be to create a table in the registry whose keys are lua_States and values are your thread local data. Make the table weak in the keys so when threads are collected the thread local data is freed. If...
So I'm currently in a practical session at my university and not a single person can figure out how to add the pthread library in Eclipse. This is my first time with Eclipse though. I'm using Fedora, and when I go to Properties->C/C++ Build->Settings, all I get is a drop-down list for configurations and nothing else ...
Make sure you have in Project -> Settings -> C/C++ Build the option "Generate Makefile automatically" selected! Otherwise Eclipse assumes you are providing your own makefile and doesn't show the "Tool setting" tab. Then you need to go to Project -> Properties -> C/C++ Build dothis.
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...
Depending on the needed requirements for speed and precision, maybe you could create the functions needed by a simple lookup table, by writing a program to create the lookup table. Or useCORDIC.
I need to compute the log base 2 of a number in C but I cannot use the math library. The answer doesn't need to be exact, just to the closest int. I've thought about it and I know I could just use a while loop and keep dividing the number by 2 until it is < 2, and keep count of the iterations, but is this possible usi...
Already answered by abamert but just to be more concrete this is how you would code it: ``` Log2(x) = result while (x >>= 1) result++; ```
i have a function to create a circular list, i am having issues compiling, not sure if it is syntax, appreciate if someone can help. ``` void CreateCircularList(struct node** listRef, struct node** tailRef) { Push(&*listRef, "String 1"); *tailRef=*listRef; Push(&*listRef, "String 2"); Push(&*...
You probably want ``` (*tailRef)->next = *listRef; ``` as the last assignment. You cannot writetailRef->nextsincetailRefis a pointer to a pointer. I also suggest just codingPush(listRef, "Some string");instead of yourPush(&*listRef, "Some string");for readability reasons.
When I do: ``` t_node *node1; t_node **head; void *elem; int c = 1; elem = &c; head = NULL; node1 = malloc(sizeof(t_node)); node1->elem = elem; head = &node1; //add_node(node1,head); //substitute this with line above and it doesn't work printf("%d\n",*(int*)(*head)->elem); // prints 1 and works fine ``` BUT WHEN I ...
C is a pass by value language. Your function actually doesn't do anything at all as far asmain()is concerned. Check outthis questionin the comp.lang.c FAQ.
Consider the following scenario: ``` auto h = CreateFile(...); ReadFileEx(h, ...); // Asynchronous read for a large block of data. say, 1GB. CloseHandle(h); // If the read has not yet finished here, what will happen? Big Bang??? ```
So long as the Asyncronous handle was valid at the time of the call, the asynchronous operation will remain valid until it completes. This is because Asyncronous file IO calls hold an implicit reference count to the file object in the kernel. When the asyncronous event completes, if there are no more handles in userm...
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. The function would be something lik...
Use a hash function, e.g. ``` return std::hash<int>()(std::hash<int>()(x) + y); ```
Please have a look at this code: ``` #include <stdio.h> int main(void) { short s; int i = 65696; float f = 65696.0F; printf("sizeof(short) = %lu\n", sizeof(short)); s = i; printf("s = %hd\n", s); s = f; printf("s = %hd\n", s); s = 65696; printf("s = %hd\n", s); s = 6569...
Because if the integral part of the float value is not representable in the new type, the conversion is undefined behavior. In your case,SHRT_MAXis probably 32767 and so the integral part of65696.0Fis then not representable in ashortobject.
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. I had the idea recently to write my...
TryLinux From Scratch: Linux From Scratch (LFS) is a project that provides you with step-by-step instructions for building your own custom Linux system, entirely from source code.
I need a Random Number Generator that produces same sequence of numbers both in iOS and Android if we give the same Seed in both. I tried the rand() function with the srand(1000). But it gave different outputs. Then I tried mersenne twister. But that too gave difference sequence for same seed. Could any one please h...
You can just write your own random number generator like this. The quality is low but will suit for most of the purpose. ``` // RAND_MAX assumed to be 32767. static unsigned long int next = 1; void srand(unsigned int seed) { next = seed; } int rand(void) { next = next * 1103515245 + 12345; return (unsigned in...
my question is: how to implement something like thread local storage using Lua stack (lua_State)? Some value that will be stored in the lua state, accessible to lua scripts and from C API.
There are several ways to do this. I wrote a paper about it; it's Chapter 1 inLua Programming Gems The easiest way may be to create a table in the registry whose keys are lua_States and values are your thread local data. Make the table weak in the keys so when threads are collected the thread local data is freed. If...
So I'm currently in a practical session at my university and not a single person can figure out how to add the pthread library in Eclipse. This is my first time with Eclipse though. I'm using Fedora, and when I go to Properties->C/C++ Build->Settings, all I get is a drop-down list for configurations and nothing else ...
Make sure you have in Project -> Settings -> C/C++ Build the option "Generate Makefile automatically" selected! Otherwise Eclipse assumes you are providing your own makefile and doesn't show the "Tool setting" tab. Then you need to go to Project -> Properties -> C/C++ Build dothis.
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...
Depending on the needed requirements for speed and precision, maybe you could create the functions needed by a simple lookup table, by writing a program to create the lookup table. Or useCORDIC.
I need to compute the log base 2 of a number in C but I cannot use the math library. The answer doesn't need to be exact, just to the closest int. I've thought about it and I know I could just use a while loop and keep dividing the number by 2 until it is < 2, and keep count of the iterations, but is this possible usi...
Already answered by abamert but just to be more concrete this is how you would code it: ``` Log2(x) = result while (x >>= 1) result++; ```
i have a function to create a circular list, i am having issues compiling, not sure if it is syntax, appreciate if someone can help. ``` void CreateCircularList(struct node** listRef, struct node** tailRef) { Push(&*listRef, "String 1"); *tailRef=*listRef; Push(&*listRef, "String 2"); Push(&*...
You probably want ``` (*tailRef)->next = *listRef; ``` as the last assignment. You cannot writetailRef->nextsincetailRefis a pointer to a pointer. I also suggest just codingPush(listRef, "Some string");instead of yourPush(&*listRef, "Some string");for readability reasons.
When I do: ``` t_node *node1; t_node **head; void *elem; int c = 1; elem = &c; head = NULL; node1 = malloc(sizeof(t_node)); node1->elem = elem; head = &node1; //add_node(node1,head); //substitute this with line above and it doesn't work printf("%d\n",*(int*)(*head)->elem); // prints 1 and works fine ``` BUT WHEN I ...
C is a pass by value language. Your function actually doesn't do anything at all as far asmain()is concerned. Check outthis questionin the comp.lang.c FAQ.
Consider the following scenario: ``` auto h = CreateFile(...); ReadFileEx(h, ...); // Asynchronous read for a large block of data. say, 1GB. CloseHandle(h); // If the read has not yet finished here, what will happen? Big Bang??? ```
So long as the Asyncronous handle was valid at the time of the call, the asynchronous operation will remain valid until it completes. This is because Asyncronous file IO calls hold an implicit reference count to the file object in the kernel. When the asyncronous event completes, if there are no more handles in userm...
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. The function would be something lik...
Use a hash function, e.g. ``` return std::hash<int>()(std::hash<int>()(x) + y); ```
I am writing a simple server in C/C++. I have everything mostly complete, but there is one problem. The server fails to send the last three lines of a file to a client. I assume I am closing the socket connection prematurely, but my attempts to remedy this have failed. For example, calling ``` shutdown(clientSckt, SH...
From vague memory: a) if you want to use SO_LINGER, use close(). b) more robust is do a half shutdown ``` shutdown(clientSckt, SHUT_WR) ``` and then read() until you get a 0.
I'm trying to store a pointer initialized as: ``` int* x; ``` into a regular variable initialized as ``` int y; ``` thus: ``` y = *x; ``` In mips is it just as simple as ``` $s1 = ($a0);? ``` And vice versa?
Assembly language usually doesn't have operators. You probably want thelwinstruction: ``` lw $s1, 0($a0) ``` The use of$s1and$a0is of course context dependent. If those register match the rest of the code you're using, it'll be fine.
I am trying to write a small program where I basically count the string length in a function but for some reason it is not outputting anything to the command line. ``` #include <stdio.h> int search (char* string, char* substring){ int length = 0; while(substring){ substring++; length++; }...
You need to dereference it or you'll keep looping since there's no obvious way forsubstringto become 0. ``` while (*substring) ^ ``` That's because you're not looking for theNULLpointer but rather for the NUL (\0) character.
I am trying to initialize a 2d array with some integer.If I initialize the array to 0 I am getting correct results but If I use some other integer I get some random values. ``` int main() { int array[4][4]; memset(array,1,sizeof(int)*16); printf("%d",array[1][2]); <---- Not set to 1 } ```
memsetset every byte of your array to1not everyintelement. Use an initializer list with all values set to 1 or a loop statement to copy a value of1to all the elements.
``` typedef union { unsigned x; } T; T a; a.x = 3; int main() { return 0; } ``` Trying to compile this code, withgcc t.c, I get ``` error: expected '=', ',', ';', 'asm' or '__attribute__' before '.' token ``` using ``` gcc --version gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 ``` When I movea.x = 3;insidemain, it ...
I wish to find the passage from ISO/IEC 9899:TC3 where it is explained that it is forbidden to assign values to a union in global namespace. It is described in the 6.9p1 of C99 (syntax of a translation-unit). You cannot have a statement outside of a function.
I have downloaded both programs, but I see no instructions on google for getting Cilk to work on Cygwin. Is there a Cygwin package that would work? I'm programming in C and have gcc installed.
Build it from source. That will link thecygwin32.dllwith the binaries which are essential for it to work with cygwin. Here is a guide:http://groups.csail.mit.edu/sct/wiki/index.php?title=Cilk_Plus_Installation_Guideto build it from source withgcc.
Which port should I use if I need to get the hostname of an IP ? From where does getnameinfo() get the hostname ? ``` struct sockaddr_in sa; sa.sin_family = AF_INET; sa.sin_port = htons(?); // which port ? inet_pton(AF_INET, "x.x.x.x", &(sa.sin_addr)); char host[NI_MAXHOST]; getnameinfo((struct sockaddr *)&sa,...
If you don't useservandservlenarguments, port number is irrelevant. Otherwise it's used to look up theserviceby the port number, something like"ssh"for port 22,"smtp"for port 25, etc. (see/etc/servicesfor more). getnameinfo()can get the hostname from a number of places (withnsswitch.conf, miscellaneouslibnssmodules c...
it comes down to this code: ``` SDL_Surface *smiley = SDL_LoadBMP("./images/smileys/normal_up.bmp"); printf("Transparation worked: %i\n", SDL_SetColorKey(smiley, SDL_SRCCOLORKEY, SDL_MapRGB(smiley->format, 255, 0, 255))); SDL_BlitSurface(smiley, NULL, window, NULL); SDL_Flip(window); ``` This is theimageI used. Usin...
These lines right before the SDL_SetColorKey()-call make the whole thing work: ``` smiley->format->Amask = 0xFF000000; smiley->format->Ashift = 24; ``` Now I can use .bmp or .jpg files with 32 or 24 bpp VideoMode, everything works! Don't know why, don't know how that works.
I have a rather large ZIP file, which gets downloaded (cannot change the file). The quest now is to unzip the file while it is downloading instead of having to wait till thecentral directory endis received. Does such a library exist?
I wrote "pinch" a while back. It's in Objective-C but the method to decode files from a zip might be a way to get it in C++? Yeah, some coding will be necessary. http://forrst.com/posts/Now_in_ObjC_Pinch_Retrieve_a_file_from_inside-I54https://github.com/epatel/pinch-objc
I'm looking at something like this: ``` #define foo(x) \ (((a > b) ? \ 0 : 1), \ (c ? 2 : 3), \ (d ? 4 : 5)) ``` I'm not sure how to interpret this. Can someone help me out?
Essentially the\ignores the newline as far as terminating the#definestatement is concerned, so each time you writefoo(var)in your code it will be replaced with ``` ((((a > b) ? 0 : 1), (c ? 2 : 3), (d ? 4 : 5)) ``` The comma operator doesn't do a whole lot, except the final "returned" value of a statement...
Well the problem i have with this piece of code is that, when i debug it the value of the 5th element in k array gets instantiated with the value 0.Can anyone explain why this happens? It would be good if you could debug it too! ``` #include <stdio.h> #include <stdlib.h> main () { int k[5]={3,1,7,2,6}; float ...
k[5]doesn't exist - it would be the6thelement ofk, not the 5th. Arrays in C are zero-indexed. That meanskhas elementsk[0],k[1],k[2],k[3], andk[4], and that's it. You've caused undefined behaviour, so anything could happen.
This simple program, gives me troubles in fgets(), returning EOF, that is an error value for fgets() I don't understand where is the problem ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> FILE* openFile(const char* path) { FILE* file; file = fopen(path, "r"); if(file == NULL) { ...
You are opening the file for reading, yet trying to write data to it? That doesn't make sense.
I have the following code ``` struct Info { int age; char name[5]; } char buffer[20]; Info i; i.age = 10; sprintf(i.name, "Case"); strncpy(buffer+5, (char*)&i, sizeof(Info)); ``` Now I want to recover the record ``` Info j; strncpy((char*)&j, buffer+5, sizeof(Info)); printf("%d %s", j.age, j.name); ``` However thi...
There are two problems with your copying mechanism: You're assuming thatsizeof(Info)is 5. That's definitely not the case.You're usingstrncpy, which is for strings.Infois not a string, so you need to usememcpy. The following will work: ``` char buffer[sizeof(i)]; memcpy(buffer, &i, sizeof(i)); ... memcpy(&j, buff...
I sit on Intel MacOSX 10.6 and using GCC 4.2.1 under the hood. What I am attempting to do is to allocate a buffer, populate it with machine instructions, and run it. All in a single program. For instance, ``` typedef unsigned char byte_t; int main(int argc, char** argv) { byte_t* code = new byte_t[3]; code[...
The memory is not considered "safe" for code execution, so the operating system prevents it. Look into usingmmap()to allocate the memory, and use thePROT_EXECto ask for the memory to be made executable.
This question already has answers here:What does 'sizeof (function name)' return?(4 answers)Closed10 years ago. I triedsizeof(printf),sizeof(foobar)etc. where foobar is a user defined function. It returns 1 without any warning or error. Why 1?
The size of functions is not well defined in C, so the value is meaningless.
I need that my program shows the output using commas as decimal separator. According to this link:http://www.java2s.com/Code/Java/Development-Class/Floatingpointwithcommasf.htmyou can use in Java something like this: ``` System.out.printf("Floating-point with commas: %,f\n", 1234567.123); ``` Is there a flag or som...
If you want, you can set current locale at the beginning of your program: ``` #include <stdio.h> #include <locale.h> int main() { setlocale(LC_NUMERIC, "French_Canada.1252"); // ".OCP" if you want to use system settings printf("%f\n", 3.14543); return 0; } ```
I have an variableunsigned int x = 0b0011how can I make it to unsigned integer array, likey[0]=0 ; y[1]=0; y[2]=1; y[3]=1;?
Shifting and bitwise operations. ``` unsigned x = 0b0011; // yap this is a GNU extension, it doesn't always work even with GCC const size_t intsize = sizeof(x) * CHAR_BIT; // go go indepency-of-sizeof(int)! unsigned bits[intsize]; // that's why we love constexprs int i, j; for (i = intsize - 1, j = 0; i >= 0; i--,...
This question already has answers here:!! c operator, is a two NOT?(4 answers)Closed10 years ago. I have encountered the following snippet: ``` pt->aa[!!(ts->flags & MASK)] = -val; ``` What does!!(double exclamation marks/ exclamation points/ two NOT operators) stand for in c?Doesn't(!!NULL) == NULL?
!is negation. So!!is negation of negation. What is important is the fact that the result will be anint. !!xifx == 0is!!0, that is!1, that is0.!!xifx != 0is!!(!0), that is!!1, that is!0, that is1. !!is used commonly if you want to convert any non-zero value to 1 while being certain that 0 remains a 0. And indeed,!!N...
Is there an easier way of writing: ``` rver_t *buf = malloc(sizeof(rver_t)); rver_t tmp = (rver_t) {.op=OP_RVER, .protocol_version=1}; memcpy(buf, tmp, sizeof(rver_t)); ``` to initialise a malloc'd buffer with a struct? Note: typedef happens in a header: ``` #define OP_RVER 1 typedef struct rver_s { uint32_t o...
You could type: ``` buf -> op = OP_EVER; buf -> protocol_version = 1; ```
I have an implementation of an algorithm in C which uses floats. When I compile and run on i386 I get different results to the results I get when I compile and run on armel. In particular division-of-int-by-float, results in a different float. I've extracted some code from my algorithm to demonstrate this problem: ...
Lookup 'excess precision'. To suppress it on a modern x86, compile with-msse2 -mfpmath=sse.
Let us say I have a function in my program and somewhere in my code, that function is called through a function pointer. What happens if the compiler happened to inline that function, or would the compiler realize that there is a function pointer assigned to that function and therefore avoid inlining it.
When a pointer to a function is taken, the compiler will generate an out-of-line body for the function. It is still possible to inline the function at other call sites. Note that a function markedinlinemust have a definition available in all TUs which refer to it, and these definitions must be identical. Which means ...
everytime we write a program we need something like #include or any other #include things... Is there anyway to create alias for this, so that when I type inc in vim and press some key, then inc changes to #include
Read:h abbreviationsor try one ofthe many snippet expansion plugins available. I use the originalSnipMate, but there isa modern forkand a modern alternative calledUltiSnips.
I need that my program shows the output using commas as decimal separator. According to this link:http://www.java2s.com/Code/Java/Development-Class/Floatingpointwithcommasf.htmyou can use in Java something like this: ``` System.out.printf("Floating-point with commas: %,f\n", 1234567.123); ``` Is there a flag or som...
If you want, you can set current locale at the beginning of your program: ``` #include <stdio.h> #include <locale.h> int main() { setlocale(LC_NUMERIC, "French_Canada.1252"); // ".OCP" if you want to use system settings printf("%f\n", 3.14543); return 0; } ```
I have an variableunsigned int x = 0b0011how can I make it to unsigned integer array, likey[0]=0 ; y[1]=0; y[2]=1; y[3]=1;?
Shifting and bitwise operations. ``` unsigned x = 0b0011; // yap this is a GNU extension, it doesn't always work even with GCC const size_t intsize = sizeof(x) * CHAR_BIT; // go go indepency-of-sizeof(int)! unsigned bits[intsize]; // that's why we love constexprs int i, j; for (i = intsize - 1, j = 0; i >= 0; i--,...
This question already has answers here:!! c operator, is a two NOT?(4 answers)Closed10 years ago. I have encountered the following snippet: ``` pt->aa[!!(ts->flags & MASK)] = -val; ``` What does!!(double exclamation marks/ exclamation points/ two NOT operators) stand for in c?Doesn't(!!NULL) == NULL?
!is negation. So!!is negation of negation. What is important is the fact that the result will be anint. !!xifx == 0is!!0, that is!1, that is0.!!xifx != 0is!!(!0), that is!!1, that is!0, that is1. !!is used commonly if you want to convert any non-zero value to 1 while being certain that 0 remains a 0. And indeed,!!N...
Is there an easier way of writing: ``` rver_t *buf = malloc(sizeof(rver_t)); rver_t tmp = (rver_t) {.op=OP_RVER, .protocol_version=1}; memcpy(buf, tmp, sizeof(rver_t)); ``` to initialise a malloc'd buffer with a struct? Note: typedef happens in a header: ``` #define OP_RVER 1 typedef struct rver_s { uint32_t o...
You could type: ``` buf -> op = OP_EVER; buf -> protocol_version = 1; ```
I have an implementation of an algorithm in C which uses floats. When I compile and run on i386 I get different results to the results I get when I compile and run on armel. In particular division-of-int-by-float, results in a different float. I've extracted some code from my algorithm to demonstrate this problem: ...
Lookup 'excess precision'. To suppress it on a modern x86, compile with-msse2 -mfpmath=sse.
Let us say I have a function in my program and somewhere in my code, that function is called through a function pointer. What happens if the compiler happened to inline that function, or would the compiler realize that there is a function pointer assigned to that function and therefore avoid inlining it.
When a pointer to a function is taken, the compiler will generate an out-of-line body for the function. It is still possible to inline the function at other call sites. Note that a function markedinlinemust have a definition available in all TUs which refer to it, and these definitions must be identical. Which means ...
everytime we write a program we need something like #include or any other #include things... Is there anyway to create alias for this, so that when I type inc in vim and press some key, then inc changes to #include
Read:h abbreviationsor try one ofthe many snippet expansion plugins available. I use the originalSnipMate, but there isa modern forkand a modern alternative calledUltiSnips.
I've been reading this reference:http://www.osdever.net/FreeVGA/vga/vgafx.htmto learn VGA programming, but because I'm a student that just started learning about low level programming, I find it hard to understand. What does it mean when the reference says "scan"? Especially in the "Split-screen Operation" section in...
AScanlineis a single pass across the screen horizontally.
I came across a code that looks like this: ``` asm volatile ( # [...] "movl $1200, %%ecx;" # [...] ); ``` I know whatmovl $1200, %ecxdoes in x86. but I was confused by why there are two percent signs.
GCC inline assembly uses %0, %1, %2, etc. to refer to input and output operands. That means you need to use two %% for real registers. Check thishowtofor great information.
I am working in omap4 based system. It has 4 UART port so kernel makes: ``` /dev/ttyO0 /dev/ttyO1 /dev/ttyO2 /dev/ttyO3 ``` When I open from user space: ``` fd = open("/dev/ttyO1",O_RDONLY) ``` it succesfully open and i can peform read and write with that. But when I open: ``` fd = open("/dev/ttyO3",O_RDONLY) ``...
i have given permission to that node and now i can open that node ``` chmod 0606 /dev/ttyO3 ```
I want to know if it is posible in linux and C to find out that my programs output is redirected to a file. I want to format the output human readable when it is printed on stdout$ ./myprogramand like csv when it is redirected to a file$ ./myprogram >> data.csv is it posible?
You can use theisattyfunction for that: ``` if (isatty(STDOUT_FILENO)) { /* Standard out is an interactive terminal */ } else { /* Standard out is something else (pipe, file redirect, etc.) */ } ```
I'm trying to read in a file that contains multiple lines of the form: ``` www.someurl.com,timestamp ``` I am using the following code: ``` char url[256]; unsigned int timestamp; // Read each line from the input file. while(fscanf(inputfile, "%s,%d", url, &timestamp) == 2) { printf("%s was visited at %d\n", ur...
When processing%s,fscanfexpects a whitespace terminated string, and it's greedy as well. So the entire line is read into the url. You can specify the forbidden character set directly: ``` fscanf(inputfile, "%[^,],%d", url, &timestamp) ``` Here'sa bit more data aboutfscanfvariants and the format string.
The output of the following is "str-3," however I expect it to be "str-2,str-3," If I change snprintf to sprintf then this works how I expected it to; shouldn't snprintf and sprintf behave the same? ``` int main (int argc, char **argv) { char str[64]; str[0] = '\0'; snprintf(str, 64, "%s%s,", str, "st...
The description ofsnprintfin the C standard (C99, 7.19.6.5) says: If copying takes place between objects that overlap, the behavior is undefined. This is what happens here sincestris used as both the input and output. The same restriction applies tosprintf. The fact that it happened to work for you is just an accide...
I recently started with Java and want to understand a java module of a large app. I came across this line of java code: ``` String line = (new BufferedReader(new InputStreamReader(System.in))).readLine(); ``` What does this java code do. Is there a C/C++ equivalent of this?
System.inis the standard input. InputStreamReaderallows you to associate a stream that reads from the specified input (in this case the standard input), so now we have a stream. BufferedReaderis an "abstraction" to help you to work with streams. For example, it implementsreadLineinstead of reading character by chara...
I stumbled uponhttp://sourceware.org/ml/glibc-cvs/2013-q1/msg00115.html, which includes the line ``` #define TWO5 0x1.0p5 /* 2^5 */ ``` Apparently, TWO5 is defined as a double with the explicit value1<<5. However, this is the first time I see this notation. How has this format been in use, and what is...
This notation was introduced in C99. The advantage is that the value is expressed in hexadecimal form, so it is not subject to rounding etc. that occurs when you convert a floating-point value between the underlying representation and a decimal form. There are plenty of pages that describe this notation, for example:...
In the Linux Kernel, read/write spin lock is used to synchronize access to the list of the tasks. However whereas read_(un)lock are used for reading, write_(un)lock_irq are used for writing. Why is it needed to disable interrupts while locking for writing?
For a lock that's ever used in IRQ context, IRQs must be disabled when held. But there are different ways to achieve this. (I describe spinlocks, read/write locks are the same in this respect) spin_[un]lockdon't disable IRQs. Only use them when you know they're already disabled (e.g. in the interrupt handler).spin_[...
There isfilenoto get the file descriptor of a FILE*. How do you get the address for the FILE* given a file descriptor number, e.g. as returned frompipe? filenopipe
You want to use thefdopen()function: ``` FILE * file = fdopen(fd, "r"); ``` so you could use it in combination withpipelike this: ``` FILE * file = fdopen(pipe(..,..), "r"); ```
This question already has answers here:Why aren't pointers initialized with NULL by default?(15 answers)Closed10 years ago. Is it safe to assume that the if statement will always work if the variable is uninitialized? Assumption is yes, but I have been told that random bits of garbage in the variable does not always ...
Is it safe to assume that the if statement will always work if the variable is uninitialized? No. Reading uninitialized storage invokes undefined behavior. You can't make safe assumptions about this code. Don't do this!
I want to refactor someprintf/sprintf/fprintfstatements intoostream/sstream/fstreamstatements. The code in question pretty-prints a series of integers and floating-point numbers, using whitespace padding and fixed numbers of decimal points. It seems to me that this would be a good candidate for a Martin Fowler style ...
If refactoring is not the goal in itself, you can avoid it altogether (well, almost) by using a formatting library such astinyformatwhich provides an interface similar toprintfbut is type safe and uses IOStreams internally.
I have a gtk widget (from gtk_dialog_new()) which was created in a different function and bunch of widgets added to it. Now I want to reparent all the children of this widget to another container. Something like: ``` get_widget_get_all_childrent(list); //loop over list and reparent all children ```
Actually I found the answer after a bit of googling. First I need to get a list of children: ``` GList* list = gtk_container_get_children(); //then loop over and reparent g_object_ref(widget); gtk_container_remove(GTK_CONTAINER(old_parent), widget); gtk_container_add(GTK_CONTAINER(new_parent),...
I have an array and a variable that will hold its size. This array is global (outside of main). The thing is that I don't know the size so I would have to declare it like this (psuedo-code): ``` int a[]; // don't know the size yet (outside main) int size = [user input] // this is inside main ``` The size variable i...
In C you cannot have a variable length array with file-scope. What you can do is to use a file-scope pointer and allocate memory withmalloc. ``` #include <stdlib.h> int *a; // outside main int main(void) { a = malloc(user_input * sizeof *a); // this is inside main // ... } ```
When creating a small webserver with libev in C, what is the best strategy to serve files (open, ready, write to socket) without blocking the reactor? I have across some recommendations to read a few blocks at a time but I am not sure this would be the right approach. Thanks,
I have across some recommendations to read a few blocks at a time but I am not sure this would be the right approach. Yep, this is a pretty standard approach. If you are on Linux you may like to usesendfile(). This way you don't have to maintain a buffer into which it reads a file in blocks and then sends it through...
This question already has answers here:Closed10 years ago. Possible Duplicate:How do you generate a random double uniformly distributed between 0 and 1 from C++? I'm trying to figure out how to generate a random number between 0 and pi, but the usual method won't work because mod does integer division: ``` double n...
Generate a random number between 0 and 1, and then multiply the result by2*M_PI. If you have a uniform distribution between 0 and 1, you will also have a uniform distribution between 0 and2*M_PI, to the limit of precision available in the numeric type you are using. For generating a random uniform double between 0 a...
In the following code: ``` short = ((byte2 << 8) | (byte1 & 0xFF)) ``` What is the purpose of& 0xFF? Because sometimes, I see the above code written as: ``` short = ((byte2 << 8) | byte1) ``` And that seems to work fine too.
ifbyte1is an 8-bit integer type then it's pointless - if it is more than 8 bits it will essentially give you the last 8 bits of the value: ``` 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 & 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 ------------------------------- 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1 ```
I have two bytes containing a 14-bit left-justifiedtwo's complementvalue, and I need to convert it to a signed short value (ranging from -8192 to +8191, I guess?) What would be the fastest way to do that?
Simply divide by 4. (Note, right-shift leads to implementation/undefined behaviour.)
I've tried both a recursive and iterative method to this, but I keep running into the issue of storing a character string of an indeterminate length. If their is some sort of library or Api call that reads until the next white space that would prove extremely helpful. But essentially, I need to create an Array of Str...
use malloc and realloc for making space for your input. Pick a reasonable starting size (you must have some sort of idea how many characters to expect). Every time you realloc, double the size.
In the Linux Kernel, read/write spin lock is used to synchronize access to the list of the tasks. However whereas read_(un)lock are used for reading, write_(un)lock_irq are used for writing. Why is it needed to disable interrupts while locking for writing?
For a lock that's ever used in IRQ context, IRQs must be disabled when held. But there are different ways to achieve this. (I describe spinlocks, read/write locks are the same in this respect) spin_[un]lockdon't disable IRQs. Only use them when you know they're already disabled (e.g. in the interrupt handler).spin_[...
There isfilenoto get the file descriptor of a FILE*. How do you get the address for the FILE* given a file descriptor number, e.g. as returned frompipe? filenopipe
You want to use thefdopen()function: ``` FILE * file = fdopen(fd, "r"); ``` so you could use it in combination withpipelike this: ``` FILE * file = fdopen(pipe(..,..), "r"); ```
This question already has answers here:Why aren't pointers initialized with NULL by default?(15 answers)Closed10 years ago. Is it safe to assume that the if statement will always work if the variable is uninitialized? Assumption is yes, but I have been told that random bits of garbage in the variable does not always ...
Is it safe to assume that the if statement will always work if the variable is uninitialized? No. Reading uninitialized storage invokes undefined behavior. You can't make safe assumptions about this code. Don't do this!
I want to refactor someprintf/sprintf/fprintfstatements intoostream/sstream/fstreamstatements. The code in question pretty-prints a series of integers and floating-point numbers, using whitespace padding and fixed numbers of decimal points. It seems to me that this would be a good candidate for a Martin Fowler style ...
If refactoring is not the goal in itself, you can avoid it altogether (well, almost) by using a formatting library such astinyformatwhich provides an interface similar toprintfbut is type safe and uses IOStreams internally.
I have a gtk widget (from gtk_dialog_new()) which was created in a different function and bunch of widgets added to it. Now I want to reparent all the children of this widget to another container. Something like: ``` get_widget_get_all_childrent(list); //loop over list and reparent all children ```
Actually I found the answer after a bit of googling. First I need to get a list of children: ``` GList* list = gtk_container_get_children(); //then loop over and reparent g_object_ref(widget); gtk_container_remove(GTK_CONTAINER(old_parent), widget); gtk_container_add(GTK_CONTAINER(new_parent),...
I have an array and a variable that will hold its size. This array is global (outside of main). The thing is that I don't know the size so I would have to declare it like this (psuedo-code): ``` int a[]; // don't know the size yet (outside main) int size = [user input] // this is inside main ``` The size variable i...
In C you cannot have a variable length array with file-scope. What you can do is to use a file-scope pointer and allocate memory withmalloc. ``` #include <stdlib.h> int *a; // outside main int main(void) { a = malloc(user_input * sizeof *a); // this is inside main // ... } ```
When creating a small webserver with libev in C, what is the best strategy to serve files (open, ready, write to socket) without blocking the reactor? I have across some recommendations to read a few blocks at a time but I am not sure this would be the right approach. Thanks,
I have across some recommendations to read a few blocks at a time but I am not sure this would be the right approach. Yep, this is a pretty standard approach. If you are on Linux you may like to usesendfile(). This way you don't have to maintain a buffer into which it reads a file in blocks and then sends it through...
This question already has answers here:Closed10 years ago. Possible Duplicate:How do you generate a random double uniformly distributed between 0 and 1 from C++? I'm trying to figure out how to generate a random number between 0 and pi, but the usual method won't work because mod does integer division: ``` double n...
Generate a random number between 0 and 1, and then multiply the result by2*M_PI. If you have a uniform distribution between 0 and 1, you will also have a uniform distribution between 0 and2*M_PI, to the limit of precision available in the numeric type you are using. For generating a random uniform double between 0 a...
In the following code: ``` short = ((byte2 << 8) | (byte1 & 0xFF)) ``` What is the purpose of& 0xFF? Because sometimes, I see the above code written as: ``` short = ((byte2 << 8) | byte1) ``` And that seems to work fine too.
ifbyte1is an 8-bit integer type then it's pointless - if it is more than 8 bits it will essentially give you the last 8 bits of the value: ``` 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 & 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 ------------------------------- 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1 ```
I want to refactor someprintf/sprintf/fprintfstatements intoostream/sstream/fstreamstatements. The code in question pretty-prints a series of integers and floating-point numbers, using whitespace padding and fixed numbers of decimal points. It seems to me that this would be a good candidate for a Martin Fowler style ...
If refactoring is not the goal in itself, you can avoid it altogether (well, almost) by using a formatting library such astinyformatwhich provides an interface similar toprintfbut is type safe and uses IOStreams internally.