question
stringlengths
25
894
answer
stringlengths
4
863
I have a lots of short programs in C. Each program realize simple operation for example: include library, load something (ex matrix) from file, do simple operation, write matrix to file end. I want to measure real time of excecution a whole program (not only fragment of code). My simple idea is using htop or ps aux ...
If your program is named foo, then simply typing ``` ~$ time foo ``` should do exactly what you want.
I want to know howls -Rimplemented in C language. Is it use the recursion algorithm?
"ls" (at least the implementations that I know of) usefts_open,fts_read... to traverse a file hierarchy. These are "non-recursive" methods which maintain a list of the visited directories internally. Use "man fts_read" orhttp://linux.die.net/man/3/fts_readto get more information about these functions.
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. My file A.txt reside in particular ...
If the whole file won't fit in memory, don't slurp the whole file into memory; process it one line at a time. Or get more memory.
I have these variables: ``` char* name = "bobsux"; int score = 100; char* scoreHash = "f899139df5e1059396431415e770c6dd"; ``` Printing these using format specifiers and printf, returns this: ``` printf("name=%s&score=%d&score_hash=%s", name, score, scoreHash); => name=bobsux&score=100&score_hash=f899139df5e1059...
You usesnprintf()to format the text into a character array: ``` char scoreData[128]; snprintf(scoreData, sizeof scoreData, "name=%s&score=%d&score_hash=%s\n", name, score, scoreHash); ```
In C (before C99), booleans are usually represented as ``` typedef int bool; #define true 1 #define false 0 ``` Why it is represented as 'int' rather than 'float'? This is an interview question, even I wonder why such question is asked! Any convincing answers?
boolvalues are mostly used in comparisons, and using theinttype uses theinteger ALUfor these comparisons. It is very fast, as it's in the CPU's normal pipeline. If you were to use thefloattype, then it would have to use the floating-point unit, which would take more cycles. Also, if you wanted to support using your...
I get this problem while compiling my code. ``` Error 14 error LNK2019: unresolved external symbol _findFuncs referenced in function _main H:\pshtoolkit_v1.4-src\whosthere\whosthere.obj whoisthere-alt ``` What libraries should I link with visual studio in order to resolve the error?
What libraries should I link with visual studio: The library containing _findFuncs. OK, not helpful I know, but presumably you know what findFuncs is and you are calling it for a reason. Where did you find out about it? Do you have any documentation? Maybe you have a typo calling this function (case?), e.g. should...
I have a lots of short programs in C. Each program realize simple operation for example: include library, load something (ex matrix) from file, do simple operation, write matrix to file end. I want to measure real time of excecution a whole program (not only fragment of code). My simple idea is using htop or ps aux ...
If your program is named foo, then simply typing ``` ~$ time foo ``` should do exactly what you want.
I want to know howls -Rimplemented in C language. Is it use the recursion algorithm?
"ls" (at least the implementations that I know of) usefts_open,fts_read... to traverse a file hierarchy. These are "non-recursive" methods which maintain a list of the visited directories internally. Use "man fts_read" orhttp://linux.die.net/man/3/fts_readto get more information about these functions.
I'm trying to add all the files in the current directory to my implemented archive. What function(s) could I use to access all these files? After doing some research online and in the man pages, all I have found is simple I/O like read, write, close, etc.
You can try with this. ``` main() { DIR *d; struct dirent *e; e=malloc(sizeof(struct dirent)); d=opendir("<your_directory_name>"); while ((e = readdir(d)) != NULL) { printf("%d %s\n", e->d_type, e->d_name); } closedir(d); } ```
Just wondering if it possible. If yes, are there other ways besides compiler emulation layer? Thanks
It's processor-dependent. Some processors have special instructions to manipulate register pairs (e.g. the 8-bit AVR instruction set has instructions for 16-bit register pairs). On processors without such native support, the compiler usually emits instructions that work with pairs of registers at a time (this is what ...
I'm trying to read a file byte by byte and write it to another file. I have this code: ``` if((file_to_write = fopen(file_to_read, "ab+")) != NULL){ for(i=0; i<int_file_size; i++){ curr_char = fgetc(arch_file); fwrite(curr_char, 1, sizeof(curr_char), file_to_write); } } ``` whereint_file_sizeis the amo...
You should pass theaddressofcurr_char, not thecurr_charitself: ``` fwrite(&curr_char, 1, sizeof(curr_char), file_to_write); // ^------ Here ```
I'm playing around with a tiny app (in C) that, when run, creates a directory tree which it populates with files. It does this by using a series of lines of the form system("echo \"lump = \" >> ./newdirectory/newfile.c"); This is working fine, except for when I try to have it write a line of C into the new file whi...
Since you want the escape characters to appear as-is, you need to escape them too. Yes, you can escape escape characters. Something like: ``` "\\\"" ``` This results in outputting a\followed by an".
I have a library that written mostly in C, Some parts of it should be thread safe and I use global spinlock to protect the critical section of the code. Now my problem is:I should call some callback of the user from inside of a critical section that protected by a spinlock and in case that those callbacks generate an...
This is called structured exception handling. It can be accomplished by usingsetjmpandlongjmp. It has been used in C for a long time. See this for details:http://www.freetype.org/david/reliable-c.html
How can I get a version of language C/C++(downloaded??) where the functions sound, nosound, delay are present in the library DOS.H? For example it doesn't exist in the version c/c++ on code::blocks. What have I to do in order to use/find the functions sound/nosound/delay? thank you for your help !
download (sigh) a copy of TurboC/TurboC++.
In C [not C++]: How can I copy aconst char*into a string (char array)? I have: ``` const char *d="/home/aemara/move/folder" char tar[80] ; int dl=strlen(d); int x=0; while (x<dl){tar[x]=d[x]; x++; } printf("tar[80]: %s\n",tar); ``` Prints out:tar[80]: /home/aemara/move/folderøèBThe problem is that this way, adds g...
strlenreturns the length without the null terminator. You need to copy one more byte.
Here is my data structure ``` struct Node{ int x; Node *next; Node *prev; } ``` If I allocate memory ``` Node *A = malloc (sizeof (Node) * 10); ``` How can I access each box in the array using array index in this case? or it's not possible? My goal just want to make a linked list in this chunk o...
This gives you an array of 10Nodes, accessible throughA. Now, all you have to do is e.g. ``` A[0].next = &A[1]; ``` to set thenextvalue of the first node.
I have a program that implements an archive and I need to extract files from the created archive. I intend on doing so by creating a new file. I already have the file name/user id/group id/ date/ mode (permissions)/ etc. So how would I create a file with these given attributes?
On creating a File, certain properties are automatically set. This includes the Owner & Time/Date. You can specify the name of the file to be created, but the file is automatically owned by you and inherits your user ID and group ID (i.e.. of the one executing the program) - This is system generated and is done so for...
``` q_node * pop(Queue * que) { if ((que->size == 0) || (que == NULL)) return null; q_node * item = que->head; if (freeNode(que)) { que->size--; return item; } else return null; } ``` When I try to compile I get the above warning for the bottom line of this function. The structs q_node and Que...
``` q_node * pop(Queue * que) { if ((que->size == 0) || (que == NULL)) return NULL; q_node * item = que->head; if (freeNode(que)) { que->size--; return item; } return NULL; } ``` remove the else statement is useless. No warnings now ^_^ Gcc see you miss a return statement at the end and is ...
Is there a way to get the gcc preprocessor to replace a type with what defined by the typedef, i.e. something like this: ``` typedef unsigned char Uint8 int main(void) { Uint8 a = 1; Uint8 b = 2; Uint8 c; c = a + b; return 0; } ``` Would get preprocessed into something like this: ``` int mai...
No, there isn't, because type aliasing is part of compilation stage and not a pre-processing stage. Therefore pre-processor cannot know anything about types by design and cannot perform any operations on those types. Also, you forgot to put;at the end of typedef statement.
Is it possible to verify the type and number of arguments supplied to a variable length argument?(...)?
At runtime? The type, no. The number, only if the caller places a NULL (or something recognisable) at the end, which is unreliable. At compile time, you can get the compiler to check the arguments in the same way that it will check the args to printf. Google for gcc __attribute__ format
``` #include <stdio.h> #include <sys/types.h> #include <unistd.h> int main() { int p; p = fork(); if (fork()==0) { if (execl("/bin/echo", "/bin/echo", "foo", 0) == -1) { fork(); } printf("bar\n"); } else { if (p!=0) execl("/bin/echo", "/bin/echo", "baz", ...
Theexec*functionsreplacesthe process with the new program, so the code after theexeclcall you do never runs.
..then to an array, or along those lines. I'm so confused on what I'm supposed to do. Here are the structs: ``` typedef struct { char name[30]; } PersonType; typedef struct { PersonType *personInfo; } StudentType; typedef struct { StudentType students[30]; } GraduateType; ``` I want to get the name of the P...
You were almost there.personInfois a pointer, so you should treat it as such: ``` gptr[i].students[j].personInfo->name ```
I have twoGtkWindows, when a button is clicked the window1 must free all object inside on it and close, but calling the associated-function with thedestroyevent.gtk_main_quit()can't be used, it doesn't call associated-function withdestroyevent. I have triedgtk_widget_destroy()but I get the error message(at run-time) ...
Tryg_signal_emit_by_name(G_OBJECT(window),"destroy"); It works?
I have started working with dirent.h library and I came across a very useful member of "struct dirent" structer which struct dirent *p->d_name in my book. But unfortunatly it doesn't states any other members of this structure; I was wondering what else are the members of this structure and what are they used for? Re...
The structure,struct direntrefers to directory entry. http://www.gnu.org/software/libc/manual/html_node/Directory-Entries.html In linux it is defined as: ``` struct dirent { ino_t d_ino; /* inode number */ off_t d_off; /* offset to the next dirent */ unsigned short d_reclen...
``` #include <stdio.h> main() { int a[] ={ 1,2,3,4,5,6,7}; char c[] = {' a','x','h','o','k'}; printf("%d ", (&a[3]-&a[0])); } ``` The output of the program is 3. However , the difference in the outputs of values obtained below is 12.Can someone please explain the ambiguity. ``` #include <stdio.h> main() ...
This is called pointer arithmetics. The result is the values divided bysizeof(int) If the difference in bytes is 12, and the size ofintis 4, than the result is12/4=3 BTW, when printing addresses use the format specifier%p: ``` printf("%p %p ", &a[3],&a[0]); ```
I am getting aparameter name omittederror with this code ``` #include <GL3/gl3w.h> void f(int near, int far) { } int main() { return 0; } ``` Fromthisquestion I suspected gl3w included WinDef.h but I am not able to find it included in the sources. What is the source of this problem and how can it be corrected...
To be sure the problem do not come fromWinDef.h, you can try to undefinenearandfar, to see if it works. ``` #undef far #undef near ``` The error seems to match with the behavior of this definitions. Isnearandfarare defined as empty macros, your parameters won't have identifiers.
I am trying to list files in the parent directory of the current directory, but when I try to execute this program from terminal I get Segmentation Error.. What am I doing wrong? Here is the code: ``` #include <stdio.h> #include <stdlib.h> #include <dirent.h> int main(int argc, char *argv[]) { struct dirent *dirp...
``` dirpent=readdir(dirp) !=NULL ``` should be ``` (dirpent = readdir(dirp)) != NULL ``` Your current expression is parsed asdirpent = (readdir(dirp) != NULL), which will setdirpentto either 0 or 1.
Say I have two threads that print something (relatively long) either tostderrorstdout, is the function to both these streams thread-safe in the sense that they will never "interleave" characters? So, for example, if I have "Hello, World", I will never get "HHellllo,, WorldWorld" Or whatever other interleaving? This is...
I took a look at glibc, and each call tovfprintfwill call the POSIXflockfile(_IO_flockfile) andfunlockfile(_IO_funlockfile) on the stream. So, the characters within a call won't get interleaved with characters from a call from another thread as only one thread can hold the lock onstdoutorstderr. All bets are off as ...
I have n oftype unsigned long longand a loop in c/c++ ``` while( n < ULLONG_MAX ){ ... n += revert( n ); } ``` I need to output the last n before it goes really big, is there a way I can verify and break loop? Because all the time I get outputted big same number but less then ULLONG_MAX
Ifnisunsigned long longthenn <= ULLONG_MAXis always true. If you know thatrevertalways returns a positive number you can check ifn + revert( n )is< n(i.e., check a wrap around). Or also check thatrevert(n) < ULLONG_MAX - n.
I have the following Structs ``` struct node{ int value; struct node *next; struct node *prev; }; ``` And I think that the size must be greater than sizeof(integer). But it's confusing how to calculate the whole size of this struct. So how to caculate the size? I mean I want to calculate it manually b...
The size is at leastsizeof(int) + sizeof(struct node *) + sizeof(struct node *). But it may be more as the compiler is allowed to addpadding bytesto your structure if it wishes. How bigsizeof(int)andsizeof(struct node*)are depends on your system. They are likely to be 4 bytes each if you have a 32-bit system, or they...
I have hosted my web-application on google appengine. I had to put up some java code on my website.So I am looking for a java parser for the website. Please suggest some. Actually I wanted to put up a project that usedCandJavaso I am looking for a parser that can parse both the languages.Are there available parser or...
If you just need code highlighting, there are tons of stuff out there. You could, for instance, usehighlight.js, or evenGoogle's own code prettifier. At this moment, that is what I can get from your question, so until further clarification, I won't be able to give a more precise answer.
I have a two struct, one is linked list. ``` typedef struct Mark{ int people; Node *nodeyy; }Mark typedef struct Node{ struct node next; int value; }Node ``` if i allocated memory for a node, let say ``` Node *node1=malloc( sizeof(struct Node)); ``` And I also allocated memory for a b...
change the int* in struct Mark to Node* ``` typedef struct Mark{ int people; Node *nodeyy; }Mark ``` then you can do ``` mark -> nodeyy = (Node *) malloc(sizeof(Node)) ```
Why does the following segfault? I am using standard c99, icc compiler with unix. I can't get this to not segfault, and I am curious why. I am not familiar with strcat/strcpy very much. ``` char *first = "First"; char *second = "Second"; char *both = (char *)malloc(strlen(first) + strlen(second) + 2); strcpy(both, ...
``` sprintf("%s %s", first, second); ``` The first parameter ofsprintfis a destination buffer. You have given it a constant string as a destination buffer. If you're just trying to print out something, did you meanprintf? Otherwise, correct use would be something like: ``` // declaration of "dest" left as exercis...
I am learning about Operating System programming and I need to assume I have few resources. Then how should I, for example, compute 2 / 3 and truncate that to two decimal places? Are there any math algorithms or bit manipulation tricks I can possibly use?
You can't round floating point number to base 10 two places or any number of base 10 places, floating point numbers are just approximations. There are lots of base 10 number which just can not be represented exactly as base 2 number with a finite number of decimal places, this is for the exact same reason you can not ...
I am doing research on data types and I started with INT and Float. I did a simple loop that has an equation inside it. The loop is first executed with int data type and then with float . The code is done in objective c but the idea is that they take the same time. However, while checking the instruments tool in the ...
Floating-point arithmeticsis by far more complicated than integer arithmetics. Usually, CPUs even have a dedicatedFPUcircuitry to perform floating-point operations. Thus, what you have observed is to be expected.
This question already has answers here:Closed10 years ago. Possible Duplicate:What is the difference between new/delete and malloc/free? Are they functionally equivalent, and is the only difference that you need to use the [] operator when calling delete, or is there something else I'm missing? Thanks
As Mehrdad says inthis question: malloc allocates uninitialized memory. The allocated memory has to be released with free.new initializes the allocated memory by calling the constructor (if it's an object). Memory allocated with new should be released with delete (which in turn calls the destructor). It does not need...
I have aGtkEntry, in which the user must provide the password. I did ``` gtk_entry_set_visibility(GTK_ENTRY(password_entry), FALSE); ``` to use another symbol instead of real password in pure text, but I want theGtkEtrynot to show the text while the user is typing the passord, like the su program does. How can I d...
In thedocs, right belowgtk_entry_set_visibility, there isgtk_entry_set_invisible_char, which has following notes: [...] If you set the invisible char to 0, then the user will get no feedback at all; there will be no text on the screen as they type.
I am writing a C daemon, which depends on the existence of two kernel modules in order to do its job. The program does not directly use these (or any other) modules. It only needs them to exist. Therefore, I would like to programmatically check whether these modules are already loaded or not, in order to warn the user...
There is no such function. In fact, the source code of lsmod (lsmod.c) has the following line in it which should lead you to your solution: ``` file = fopen("/proc/modules", "r"); ``` There is also a deprecatedquery_modulebut it appears to only exist in kernel headers these days.
According to C11, an object is: #C11 § 3: Terms, definitions, and symbolsobject: region of data storage in the execution environment, the contents of which can represent values. A bitfield can represent a value, so it should be an object. But, I have been told it was not the case. What is the correct answer?
6.2.6.1p2 says "Except for bit-fields, objects are composed of contiguous sequences of one or more bytes [...]", so it seems clear that bit-fields are objects. Similarly, 6.2.6.1p4 refers to "non-bit-field objects". 3.5p1 defines the bit as the unit of data storage; a bit field is a region of bits so must be a regio...
I have a project which uses gcc version 4.6.3, and I'm forced to compile with "-Wall -Werror -Wconversion". The following simple example shows an error I can't get rid of: ``` #include <stdint.h> int main(void) { uint32_t u = 0; char c = 1; u += c; return (int)u; } ``` Compiling it with the above flags gi...
The issue is with signed (negative) character. You might try ``` u += (unsigned) (c&0xff); ```
I have been working with JNI for a while, however what I am attempting now requires me to initialize some JNI variables from one class and set them from another. My question is, does JNI work the same for every class(i.e no private address space for every class). I.e, I allocate memory for one file scope variable in ...
The only one mechanism I know giving private space is Thread Local Storage. static allocation or heap allocation (malloc) are shared by all the pieces of code into an executable. Windows API offers some variation but we use it explicitly.
This question already has answers here:Closed10 years ago. Possible Duplicate:Undefined Behavior and Sequence Points the output of the programme ``` #include<stdio.h> main() { int i = 10; printf("%d %d %d\n", ++i, i++, ++i); } ``` is 13 11 13. Can someone please explain this ?
It's the oldest question ever. Why do people find this so fascinating? This is undefined behavior; you're relying on side-effects without asequence pointbetween modifications.
This question already has answers here:Closed10 years ago. Possible Duplicate:Working of fork() in linux gccWhy does this code print two times? ``` #include<stdio.h> main() { printf("hello\n"); fork(); } ``` The above code prints "hello" one time.The code below prints "hello" two times. ``` #include<stdio.h> m...
It's not guaranteed to behave in this way, but the usual behaviour is: With ``` printf("hello"); ``` the"hello"is printed to the output buffer, but that buffer is not yet flushed. Then upon the ``` fork(); ``` the program state is copied to the child process, including the non-empty output buffer. Upon exit, the o...
I'm trying to understand what this code does (and if it's even allowed): ``` int * A; int * B; A = (int *)malloc( size_t somenumber ); B = A; // bunch of stuff using B, B++, etc. ``` Everything I've read always shows equating things to pointers either using the reference operator (&) or the derefernce operator (*)....
This is not equating two pointers, it is apointer assignment. Once ``` B = A; ``` is executed, both pointers point to the same area of memory: accessing*Bbecomes exactly the same as accessing*A,B[i]becomes equivalent toA[i], and so on. Note that freeingAleavesBdangling, and vice versa. In other words, after calling...
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 have started working with C langu...
``` 8000 / 65535 = 0,122072175 0,122072175 - 1 = -0,877927825 -0,877927825 / 0,245 = -3,58337888 ``` If-3,5833is the value you are getting, then you are getting the correct result.
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. ``` #include<stdio.h> typedef ...
Heretypedefdefines a new type,node, which is a pointer to the structure. The code in the question may not compile sincestruct nodedoesn't appear to be defined anywhere and yet it's used inside of the structure.
When I compile a C-Program with MinGW and I want to remove the exe-file it disappears. But when I hit F5 it is still there. Unlocker can't find any handles and also can't remove it. I can't modify the permissions and can't change the owner. After about 2 minutes the file gets removed. It also appears before the file w...
A file can be deleted while open, but will not actually be removed from the filesystem until the last handle is closed. I suspect in your case it is a virus scanner keeping the file open. EDIT See also: Visual Studio output file permissions? Apparrently this is a known issue when disabling the "Application Experie...
I would like to write a function : ``` inline char separator() { /* SOMETHING */ } ``` that returns the file separator of the system in standard C/C++/C++11 ? (I mean slash or backslash depending on the system). Is there a way to achieve this ?
I'm not sure how to do it other than by checking ifdefs ``` inline char separator() { #ifdef _WIN32 return '\\'; #else return '/'; #endif } ``` or (as suggested by PaperBirdMaster) ``` const char kPathSeparator = #ifdef _WIN32 '\\'; #else '/'; #endif `...
I write simple console functions and use freopen to redirect printf statements to a file. Can the output to the file be "turned off" and the printf outputs redirected back to the console window later in the code?
fprintflets you to print to a specific file stream. For example, ``` fprintf(stdout, "message"); ``` printmessagein the standard output (the console), so... as you see,printfis just an specialization offprintf. I hope this help.
I was reading JS manual, and found nice trick, that~val === (val != -1). I found it nice, and want to use it in my C code. Is it portable? I checked on my GNU/Linux box, it work. EDIT: Seems I asked not too clearly. Of course, I know, there is no===in C. Question is, are both conditionals ``` int val; if (~val) {.....
The following answer was written for the question as it was originally phrased, which led myself and others to think that he was asking whether~ansand(ans ^ -1)are equivalent. This trick is not as portable as~valbecause it assumes that-1 == 0b111111111..., which is true only on a two's complement machine (granted, th...
The variable 'value' is uint32_t ``` value = htonl(value); printf("after htonl is %ld\n\n",value); This prints -201261056 value = htons(value); printf("after htons is %ld\n\n",value); This prints 62465 ``` Please suggest what could be the reason?
I guess your input is 500, isn't it? 500 is2**8+2**7+2**6+2**5+2**4+2**2or0x00 0x00 0x01 0xF4in little endian order. TCP/IP uses big endian. So after the htonl, the sequence is0xF4 0x01 0x00 0x00. If you print it as signed integer, since the first digit is 1, it is negative then. Negative numbers are regarded as co...
My program must detect when an ethernet interface turn toRUNNINGstate. I can poll the running flag by usingioctl(): ``` if( ioctl( dummy_fd, SIOCGIFFLAGS, &ifr ) != -1 ) return ifr.ifr_flags & IFF_RUNNING; ``` But want the information immediately without polling. Currently the program usesselect()for waiting ot...
the kernel sends information about network interface changes over netlink; see e.g. here for an examplehttp://softengcrunch.blogspot.cz/2010/12/communicating-with-kernel-via-netlink.htmlA quick and dirty hack would be to do the polling after any netlink event (when select wakes up on the netlink socket), without actu...
I see two option to assign a pointer 1. ``` int p=5; int *r=&p ``` 2. ``` int p int *r; r=&p; ``` Why do they use in 1 with asterisk and in two without?
You should read this: ``` int *r [...] ``` as: ``` (int *) r [...] ``` The type ofrisint *. If you look at it that way, you'll see that both versions are identical.
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. charis 1 byte incremnt.intis 2 byte...
Try this one: ``` int i; ... printf("%d",sizeof(i)); ``` What did you get? Most likely 4. Why? Because your CPU is most likely a 32bit one. The 2 byte int was true on older CPUs... Never assume sizes of variables based on "should be", always use sizeof()!
I need my program go to some specific directory then run system( ... );there and get me back where I was before. How can I do it?
Just do thecdin yoursystemcall: ``` system("cd wherever; command"); ``` The whole string gets passed tosh(1), so you can do any normal shell things in there. Since it's in a subshell, the working directory of your program won't be changed.
Is it guaranteed that this piece of code print always values from 0 to 15 on any platform? ``` #include <stdio.h> typedef struct UI4{ unsigned value: 4; } ui4; int main(void) { ui4 u; u.value = 0; while (1) { printf("%u\n", u.value++); } return 0; } ```
Yes, unsigned integer overflows are guaranteed to "wrap around" by the standard.
This question already has answers here:Closed10 years ago. Possible Duplicate:What is the difference between new/delete and malloc/free? Are they functionally equivalent, and is the only difference that you need to use the [] operator when calling delete, or is there something else I'm missing? Thanks
As Mehrdad says inthis question: malloc allocates uninitialized memory. The allocated memory has to be released with free.new initializes the allocated memory by calling the constructor (if it's an object). Memory allocated with new should be released with delete (which in turn calls the destructor). It does not need...
I have aGtkEntry, in which the user must provide the password. I did ``` gtk_entry_set_visibility(GTK_ENTRY(password_entry), FALSE); ``` to use another symbol instead of real password in pure text, but I want theGtkEtrynot to show the text while the user is typing the passord, like the su program does. How can I d...
In thedocs, right belowgtk_entry_set_visibility, there isgtk_entry_set_invisible_char, which has following notes: [...] If you set the invisible char to 0, then the user will get no feedback at all; there will be no text on the screen as they type.
I am writing a C daemon, which depends on the existence of two kernel modules in order to do its job. The program does not directly use these (or any other) modules. It only needs them to exist. Therefore, I would like to programmatically check whether these modules are already loaded or not, in order to warn the user...
There is no such function. In fact, the source code of lsmod (lsmod.c) has the following line in it which should lead you to your solution: ``` file = fopen("/proc/modules", "r"); ``` There is also a deprecatedquery_modulebut it appears to only exist in kernel headers these days.
According to C11, an object is: #C11 § 3: Terms, definitions, and symbolsobject: region of data storage in the execution environment, the contents of which can represent values. A bitfield can represent a value, so it should be an object. But, I have been told it was not the case. What is the correct answer?
6.2.6.1p2 says "Except for bit-fields, objects are composed of contiguous sequences of one or more bytes [...]", so it seems clear that bit-fields are objects. Similarly, 6.2.6.1p4 refers to "non-bit-field objects". 3.5p1 defines the bit as the unit of data storage; a bit field is a region of bits so must be a regio...
I have a project which uses gcc version 4.6.3, and I'm forced to compile with "-Wall -Werror -Wconversion". The following simple example shows an error I can't get rid of: ``` #include <stdint.h> int main(void) { uint32_t u = 0; char c = 1; u += c; return (int)u; } ``` Compiling it with the above flags gi...
The issue is with signed (negative) character. You might try ``` u += (unsigned) (c&0xff); ```
I have been working with JNI for a while, however what I am attempting now requires me to initialize some JNI variables from one class and set them from another. My question is, does JNI work the same for every class(i.e no private address space for every class). I.e, I allocate memory for one file scope variable in ...
The only one mechanism I know giving private space is Thread Local Storage. static allocation or heap allocation (malloc) are shared by all the pieces of code into an executable. Windows API offers some variation but we use it explicitly.
This question already has answers here:Closed10 years ago. Possible Duplicate:Undefined Behavior and Sequence Points the output of the programme ``` #include<stdio.h> main() { int i = 10; printf("%d %d %d\n", ++i, i++, ++i); } ``` is 13 11 13. Can someone please explain this ?
It's the oldest question ever. Why do people find this so fascinating? This is undefined behavior; you're relying on side-effects without asequence pointbetween modifications.
This question already has answers here:Closed10 years ago. Possible Duplicate:Working of fork() in linux gccWhy does this code print two times? ``` #include<stdio.h> main() { printf("hello\n"); fork(); } ``` The above code prints "hello" one time.The code below prints "hello" two times. ``` #include<stdio.h> m...
It's not guaranteed to behave in this way, but the usual behaviour is: With ``` printf("hello"); ``` the"hello"is printed to the output buffer, but that buffer is not yet flushed. Then upon the ``` fork(); ``` the program state is copied to the child process, including the non-empty output buffer. Upon exit, the o...
I'm trying to understand what this code does (and if it's even allowed): ``` int * A; int * B; A = (int *)malloc( size_t somenumber ); B = A; // bunch of stuff using B, B++, etc. ``` Everything I've read always shows equating things to pointers either using the reference operator (&) or the derefernce operator (*)....
This is not equating two pointers, it is apointer assignment. Once ``` B = A; ``` is executed, both pointers point to the same area of memory: accessing*Bbecomes exactly the same as accessing*A,B[i]becomes equivalent toA[i], and so on. Note that freeingAleavesBdangling, and vice versa. In other words, after calling...
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 have started working with C langu...
``` 8000 / 65535 = 0,122072175 0,122072175 - 1 = -0,877927825 -0,877927825 / 0,245 = -3,58337888 ``` If-3,5833is the value you are getting, then you are getting the correct result.
What I am trying to do is add a command line argument into an array as indvidual characters. So when the user runs the program./program bacon"bacon" is stored in an array as ``` array k[]= {'b', 'a', 'c', 'o', 'n'}; ``` I hope I explained it well enough I am new to programming.
Effectively, "bacon" will be passed to you through argv1which is achar *and a null terminated string. Now your array which you want to create should also be a char array. Logically you should just be copying the input (argv1) into the new array. You can use string manipulation functions likestrcpyorstrncpy Note:I a...
I’m about to deploy an application without a GUI or console-output. It works flawless but the application icon bounces for like 5 minutes after launching in the dock. I want to keep the dock-icon (so no LSUIElement=1) but get rid of the bouncing. Any ideas?
If you your application to appear in the Dock, it will need to have a Cocoa event loop and some amount of GUI (I believe it'll need at a menu bar, at a minimum, and should be able to at least handle a quit event). Depending on what your application is and how it works, this may or may not be feasible. You'll have to ...
Assume that I have a structure as below: ``` struct line { int length; char contents[]; }; struct line *thisline = (struct line *) malloc (sizeof (struct line) + this_length); thisline->length = this_length; ``` Where is the allocated space forcontents? In heap or in the coming address afterlength?
The flexible arraycontents[]is by definition located inside the variable sized structure, after thelengthfield, so you are right inmalloc-ing space for it, so of coursep->contentsis sitting inside a zone that youmalloc-ed (so inside the heap).
i have looked through other scanf posts but i cant seem to find the issue i have here with this short code. The thing is when i enter a b or c, it doesnt go to the if or else if statements, i cant really figure out how to fix it, any help would be lovely! thank you! ``` #include <stdio.h> int main(void) { char bog...
You should initialize your variablesa,bandc.
I am writing a custom "vector" struct. I do not understand why I'm getting aWarning: "one" may be used uninitializedhere. This is my vector.h file ``` #ifndef VECTOR_H #define VECTOR_H typedef struct Vector{ int a; int b; int c; }Vector; #endif /* VECTOR_ */ ``` The warning happens here on lineone->a ...
onehas not been assigned so points to an unpredictable location. You should either place it on the stack: ``` Vector one; one.a = 12; one.b = 13; one.c = -11 ``` or dynamically allocate memory for it: ``` Vector* one = malloc(sizeof(*one)) one->a = 12; one->b = 13; one->c = -11 free(one); ``` Note the use offreei...
I'm having trouble to understand how multibyte character are represented in the ascii table : decimal format and then in hexadecimal. For instance: ``` char *c = "é"; printf("%d\n%d", c[0], c[1]); ``` It will display : ``` -61 -87 ``` In the ascii table, "é" in decimal is 130, and 82 in hex. I understand 82 is t...
According to UTF-8 charset (used, among other, by many GNU/Linux distributions), the value of'é'character constant is0xC3A9, which is equivalent to11000011 10010101in binary. Here we can understand the results, assuming two complement representation. The sequence11000011is equal to-61in decimal.The sequence10010101is...
I am trying to design an artificial learning unit. Naturally I want to simulate the model before microcontroller implementation. The main issue with simulation is trying to simulate microcontroller sensor interrupts (say with a PIC18). I'm not so much looking at actually causing an interrupt as I am trying to simu...
You can use signals See here:http://en.cppreference.com/w/cpp/utility/program/signal You can use your operational system to send the signals.
I fork() a parent process to a child, the PID returned by fork() is stored in the parent's memory, then time passes and the child terminates; Now can I determine if the PID value stored in the parent's memory still refers to the same forked child, and how can I ensure that this PID doesn't refer to a different process...
The operating systemcannotreuse the child's PID until the parent has acknowledged that it knows the child has stopped executing. The parent makes the acknowledgment using thewaitandwaitpidcalls. The children that terminate are kept in a "zombie" state while the parent doesn't call these functions. After these calls r...
What are the correct JNA mappings of the C types uint8_t and int8_t? Thank you!
The only 8-bit integer data type in Java isbyte, so you would use that. Unfortunately it is signed, souint8_tvalues over 127 will be seen as negative when converted into Javabyte. This is not really a problem because the stored bits are the same.
So I was looking at some c++ source code and wanted to know just what the heck this meant. I think it means call tmp as a function but I'm not sure. ``` char* tmp; ///stuff filling tmp with values ((void (*)())tmp)(); ```
Yes, it's castingtmpas pointer to a function that accepts no arguments and returns nothing, then calling it. Looks like a recipe for disaster, if you ask me.
I have a string which may contain either single integers between0-9or mathematical operators(+, -, *, /). Basically, I need to read in all characters / numbers. I am checking if the character is either +,-,* or /. If not, then I know it is either a number or an invalid character. I am using atoi to convert it to an i...
Check each character with standard isdigit() function before using atoi
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 Can a Windows application be certified for the Windows Store if itONLYusesthe allowed Win32 subsetand is written inplain C...
No. Among other reasons, a Windows Store app must have a user interface, and the Win32 APIs callable from a Windows Store app do not include the functionality required to build a user interface. You can certainly build a Windows Store app using C, though doing so does not sound like fun.
So lately I've been writing stuff where I have to use a lot of uint8/uint16 and mix them with each other and integer literals. So I'm getting warnings such as: ``` warning: conversion to 'u16int' from 'int' may alter its value ``` Code: ``` u16int attr = attr_byte << 8; ``` I like compiling with lots of warnings o...
You can always cast: ``` u16int attr = (u16int)(attr_byte << 8); ``` I.e. you tell the compiler you know what you are doing.
I am writing a simple program in which parent and child process are alternatively printing into a file. I have managed to do this using user defined signals. Now I want to handle theSIGINTsignal. Oncectrl-cis received the parent must send termination signal to child,the child should then should terminate and finally t...
Call: ``` signal(SIGINT, SIG_IGN); ``` from the child process which will make the child process ignore theSIGINTsignal. Fromman signal: If the disposition is set to SIG_IGN, then the signal is ignored.
I am reading some tutorials on embedded programming and one of them saysintandsigned intare different but does not explain how or why. I understand whyunsigned intandintare different butintandsigned intbeing different is a new one for me.
It is for historical reasons only. Today whenever you declareintyou get asigned int. The only point where you might see a difference even with today's compilers is withcharversussigned charwhich are different by specification (and notable when assigning a literal string) but not withint.
I have awhileloop as below. ``` while (*d++ = *sc++) ``` As I wish to understand pointers in dept I would like to enter thewhileloop and understand how thewhileloop is working with the pointers. I usedstepingdbbut it does not go into thewhileloop completely. Is there any way to get into thewhileloop and understand ...
*binds tighter then postfix++.++on the right side will be applied last, so: ``` while (*d++ = *sc++) ``` is the same as: ``` while (*d = *sc) { d++; sc++; ``` The modification is much better to be traced ingdb. Update: Don't code like this OP! Although it might look cool, and prove you are smart. It's diffi...
I am getting an error when trying to call the method: ``` int box(int rows, int cols, int [rows][cols]) ``` from the main method using this call: ``` box(arrayDimensions, arrayDimensions, array); ``` But i am not sure what the problem is. Thanks.
``` int box(int rows, int cols, int [rows][cols]) ``` needs to be ``` int box(int rows, int cols, int something[rows][cols]) ```
I was refered by a member of community to analyse the below to understand systemcall issued in ARM architecture. I have a doubt that how to get program in this structure. I already tried gdb disas command, but sections are not visible. Pls help. ``` .data HelloWorldString: .ascii "Hello World\n" .text .glo...
``` gcc -S filename.c -o filename.S ```
I fork() a parent process to a child, the PID returned by fork() is stored in the parent's memory, then time passes and the child terminates; Now can I determine if the PID value stored in the parent's memory still refers to the same forked child, and how can I ensure that this PID doesn't refer to a different process...
The operating systemcannotreuse the child's PID until the parent has acknowledged that it knows the child has stopped executing. The parent makes the acknowledgment using thewaitandwaitpidcalls. The children that terminate are kept in a "zombie" state while the parent doesn't call these functions. After these calls r...
What are the correct JNA mappings of the C types uint8_t and int8_t? Thank you!
The only 8-bit integer data type in Java isbyte, so you would use that. Unfortunately it is signed, souint8_tvalues over 127 will be seen as negative when converted into Javabyte. This is not really a problem because the stored bits are the same.
I want to make the code of my application compile differently for windows mobile, since it has fewer features. To that end, i want to write code like this: ``` #ifndef (_windows_mobile_) //define avaiabilty of features thatare not supported in windows mobile #endif ``` What is the macro i should use? Target plarfo...
You should properly define the project and the build target so that the needed macros and headers from Windows CE platform SDK are pulled in, otherwise if building with a bare x86 desktop build target it won't work.
I want to access certain data which basically looks like this: ``` char* a[]={ "0000000000", "0000000000", "0011111100", "0000100100", "0000100100", "0011111100", "0000000000", "0000000000", }; ``` I have around 200 of those data sets and want to access it in the way. fooBar[23];--> ...
Just use a two dimensional array. Like: ``` char a[][]={ "0000000000", "0000000000", "0011111100", "0000100100", "0000100100", "0011111100", "0000000000", "0000000000", }; ```
"Monitors are language specific constructs" - What does this mean? Does this mean they are compiler/programming language dependent? If so,they can't be implemented in C right? I was asked to implement a monitor in C.Initially though of a monitor struct ..but as it cannot hold functions,it is of no use.Any ideas someo...
Some languageshave built-in support for the synchronization primitive known as the monitor. Others don't. C does not. It may be implemented in C, but its implementation will ultimately depend on the CPU and/or the OS.
I can't get the 2-complement calculation to work. I know C compiles ~b that would invert all bits to -6 if b=5. But why? int b=101, inverting all bits is 010 then for 2 complement's notation I just add 1 but that becomes 011 i.e. 3 which is wrong answer. How should I calculate with bit inversion operator ~?
Actually, here's how 5 is usually represented in memory (16-bit integer): ``` 0000 0000 0000 0101 ``` When you invert 5, you flip all the bits to get: ``` 1111 1111 1111 1010 ``` That is actually -6 in decimal form. I think in your question, you were simply flipping the last three bits only, when in fact you have ...
I'm beginner. I don't know why? I'm using Code::Blocks.Please read the following code: If q='W', it prints outW.If q="W", it prints out$.
The literal"W"is not a singlechar, but a null-terminated string consisting of'W'and'\0'. One way to get the desired behaviour by assigning to aconst char*and printing that with%s ``` const char* q = "W"; printf("%s", q); ``` As pointed out in comments, you could catch this type of error by increasing your compiler'...
I have a trigger on a table that I dont want to trigger during specific contexts. In order to do this, I plan on: locking the databasedropping the triggerperforming my operationsadding the triggerunlocking the database Locking the database is necessary so that any operations that other threads attempt to perform wi...
Perform your work ina transactionby using theBEGIN TRANSACTIONandCOMMIT TRANSACTIONSQL: ``` BEGIN TRANSACTION; DROP TRIGGER dbname.triggername; (do other stuff) CREATE TRIGGER ...; COMMIT TRANSACTION; ```
what does this do ``` while(*string) { i = (i << 3) + (i<<1) + (*string -'0'); string++; } ``` the *string -'0' does it remove the character value or something?
This subtracts from the character to whichstringis pointing the ASCII code of the character'0'. So,'0'-'0'gives you0and so on and'9'-'0'gives you9. The entire loop is basically calculating "manually" the numerical value of the decimal integer in the stringstringpoints to. That's becausei << 3is equivalent toi * 8and...
This question already has answers here:Closed10 years ago. Possible Duplicate:Postfix to Infix conversation What would be the prefix notation of this expression? I can not solve this expression ``` 6 a b 7 * + - c d g / + e ^ f * + ``` Any suggestion will be appreciated.
The in-order expression will be ``` [6-(a + b*7)] + [(c + d/g) ^ e]*f ``` from that you can find the pre-order, which is + -6 + a * b 7 * ^ + c / d g e f
I am just wondering why does copy_from_user(to, from, bytes) do real copy? Because it just wants kernel to access user-space data, can it directly maps physical address to kernel's address space without moving the data? Thanks,
copy_from_user()is usually used when writing certain device drivers. Note that there is no "mapping" of bytes here, the only thing that is happening is the copying of bytes from a certain virtual location mapped in user-space to bytes in a location in kernel-space. This is done to enforce separation of kernel and user...
I have written a C++ function to convert a string in markdown format to a string in html format wrapping the C library libmarkdown2 (Discount) on linux: ``` string markdown2html(const string& markdown) { auto m = mkd_string(&markdown[0], markdown.size(), 0); mkd_compile(m, 0); char* text; int len = ...
As far as I know the only thing that might not be re-entrant in Discount is themkd_initialize()function, though I did a small redesign in 2.1.{mumble} to try to keep the globals static.
Im trying to create a program using Windows sockets and i am getting an error code 0 when trying to create the socket ``` int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != NO_ERROR) { wprintf(L"WSAStartup function failed with error: %d\n", iResult); } csocket = socket(AF_INET, SOCK_STREAM, IPPRO...
Theifcondition is wrong and the socket descriptor is actually being created as it does not equalINVALID_SOCKET. Change to: ``` if (csocket == INVALID_SOCKET){ wprintf(L"socket function failed with error: %ld\n", WSAGetLastError()); } ```
I find myself typing ``` double foo=1.0/sqrt(...); ``` a lot, and I've heard that modern processors have built-in inverse square root opcodes. Is there a C or C++ standard library inverse square root function that uses double precision floating point?is as accurate as1.0/sqrt(...)?is just as fast or faster than th...
No. No, there isn't. Not in C++. Nope.
Consider this code: ``` struct s { /* ... */ }; void f(struct s x) { /* ... */) /* (1) */ /* or */ void f(const struct s *x) { /* ... */ } /* (2) */ ``` Whenstruct shas a decent size, in which case should we prefer the first form?
Are you asking which is better? It depends what you are trying to do - the second form with a pointer will be more efficient. But if you just want to pass a value tofand not have to worry about side-effects then you might go with the first signature - as long as thestructis not too large.
Any way to convert a a 2 byte short (normal short) into just a 2 byte string (char*) after using htons on that short. The thing is that the htons method returns an int (4 bytes), how do I put it into a 2 byte string ??? Note: I need to be able to use ntohs on the result to get the original value. Thanks in advice :D...
Ahm, how do you say htons returns a 4-byte integer, on my linux, htons has the prototype of ``` uint16_t htons(uint16_t hostshort); ``` Thus you can do ``` uint16_t value; value = htons(hostshort); char *bytes = &value; // now the first 2 bytes pointed to by "bytes" are the value in network byte order ``` Which me...