question
stringlengths
25
894
answer
stringlengths
4
863
Consider the following program: ``` #include <stdio.h> int main(void) { return 0; } ``` When i run the following commands: ``` gcc memory-layout.c -o memory-layout size memory-layout ``` I get the output as: ``` text data bss dec hex filename 960 248 8 ...
The reason is probably because theactualstart of a program isn't really themainfunction, but a piece of code added in the linking stage. This code setup the libraries, clears theBSSsegment, and other initialization before calling yourmainfunction. There is also code to make sure that everything is cleaned up properly ...
Difference between start-pointers and interior-pointers and in what situation we should prefer one over other?
As a complete guess, a "start-pointer" is a pointer returned bymallocornew[], whereas an "interior-pointer" is a pointer to the middle of the allocation. If so, then the important difference is that you need tofreethe start-pointer, not an interior-pointer. This isn't terminology from the standard, though. "Interior...
I'm trying to figure out how it is that two variable types that have the same byte size? If i have a variable, that is one byte in size.. how is it that the computer is able to tell that it is a character instead of a Boolean type variable? Or even a character or half of a short integer?
The processor doesn't know. The compiler does, and generates the appropriate instructions for the processor to execute to manipulate bytes in memory in the appropriate manner, but to the processor itself a byte of data is a byte of data and it could be anything. The language gives meaning to these things, but it's an...
How does Matlab/C generates Sine wave, I mean do they store the values for every angle ? but if they do then there are infinite values that are needed to be stored.
There are many, many routines for calculating sines of angles using only the basic arithmetic operators available on any modern digital computer. One such, but only one example, isthe CORDIC algorithm. I don't know what algorithm(s) Matlab uses for trigonometric functions. Computers don't simply look up the value o...
In object type macro it is possible below, ``` #define str "this is a string" ``` I want to know is it possible to use this type of string literal in function type macro like following, ``` #define mkstr(a) #a #define str(s1,s2) mkstr(s1 ## s2 ## "extra") ``` I run this and got error and now i want to know is ther...
Yes. Just place the strings together: the C language accepts that as string constant concatenation. ``` #define str(s1,s2) s1 s2 "extra" ```
I've an array of fixed size inC. There I might have any number (less than the array size) of useful element. Now I need only my useful element. So I'm thinking of using anend of arraymarker for integer array. First of all a) Is this possible? b) If possible, How?
I would take a slightly different approach ``` struct IntArray { int data[N]; int size; // <-- use this to keep track of the size. } ```
I want to use a global variable in inline assembly. asm(" LDR R0,g_TsInitStackPointerAddress"); Here g_TsInitStackPointerAddress is a global variable. While compiling its not showing any error . But while linking it shows the following error [elxr] (error) out of range: 0x1001326 (unsigned) didn't fit in 12 b...
Got the Solution __asm("g_TsInitStackPointerAddress_a: DCD g_TsInitStackPointerAddress "); Give this statement inside that function then it'll take that variable in the inline assembly
I've embedded a Lua interpreter into my C program, and I've got a simple question that I can't seem to find a clear answer to. Suppose I have a C function that I expose to Lua as follows: ``` static int calculate_value(lua_State *L) { double x = luaL_checknumber(L, 1); return 0; } ``` How can I determine (...
In general, you don't. Lua functions that throw errors usesetjmp/longjmp(or exceptions if compiled as C++) to return control to the calling Lua runtime. The error will be presented to the Lua function thatcalledyourcalculate_valuefunction. If you want to handle parameter errors differently, you cannot use Lua'sluaL_c...
Almost every pseudorandom generator in C/C++ (Mersenne, ...) uses some kind of internal state, usually a short vector of bytes. My question is, when such a random generator is used and shared in a multithreaded environment is it "much" better to have it thread-safe or letting "race conditions" to occur can only increa...
Letting "race conditions" occur can mess up everything. Technically, adata raceis undefined behaviour, so it could order pizza. But even if that doesn't happen, the internal state is likely to get corrupted and all important properties of the random sequence will just be lost. You can no longer guarantee uniformity, ...
I am using the GCC compiler but I want the to code the actually run after compilation. Is there a flag I can use for this? Right now I am just doing ``` gcc code.c ``` There is no code.exe being generated...
The file created by default is called a.out. If you want to name it code.exe, the correct line should begcc -o code.exe code.c
I am a little bit confused about the difference between ``` leal -4(%ebp), %eax ``` and ``` movl -4(%ebp), %eax ``` Can someone explain this to me?
LEA(load effective address) just computes theaddressof the operand, it does not actually dereference it. Most of the time, it's just doing a calculation like a combined multiply-and-add for, say, array indexing. In this case, it's doing a simple numeric subtraction:leal -4(%ebp), %eaxjust assigns to the%eaxregister ...
Consider the following program: ``` #include <stdio.h> int main(void) { return 0; } ``` When i run the following commands: ``` gcc memory-layout.c -o memory-layout size memory-layout ``` I get the output as: ``` text data bss dec hex filename 960 248 8 ...
The reason is probably because theactualstart of a program isn't really themainfunction, but a piece of code added in the linking stage. This code setup the libraries, clears theBSSsegment, and other initialization before calling yourmainfunction. There is also code to make sure that everything is cleaned up properly ...
Difference between start-pointers and interior-pointers and in what situation we should prefer one over other?
As a complete guess, a "start-pointer" is a pointer returned bymallocornew[], whereas an "interior-pointer" is a pointer to the middle of the allocation. If so, then the important difference is that you need tofreethe start-pointer, not an interior-pointer. This isn't terminology from the standard, though. "Interior...
I'm trying to figure out how it is that two variable types that have the same byte size? If i have a variable, that is one byte in size.. how is it that the computer is able to tell that it is a character instead of a Boolean type variable? Or even a character or half of a short integer?
The processor doesn't know. The compiler does, and generates the appropriate instructions for the processor to execute to manipulate bytes in memory in the appropriate manner, but to the processor itself a byte of data is a byte of data and it could be anything. The language gives meaning to these things, but it's an...
How does Matlab/C generates Sine wave, I mean do they store the values for every angle ? but if they do then there are infinite values that are needed to be stored.
There are many, many routines for calculating sines of angles using only the basic arithmetic operators available on any modern digital computer. One such, but only one example, isthe CORDIC algorithm. I don't know what algorithm(s) Matlab uses for trigonometric functions. Computers don't simply look up the value o...
In object type macro it is possible below, ``` #define str "this is a string" ``` I want to know is it possible to use this type of string literal in function type macro like following, ``` #define mkstr(a) #a #define str(s1,s2) mkstr(s1 ## s2 ## "extra") ``` I run this and got error and now i want to know is ther...
Yes. Just place the strings together: the C language accepts that as string constant concatenation. ``` #define str(s1,s2) s1 s2 "extra" ```
I've an array of fixed size inC. There I might have any number (less than the array size) of useful element. Now I need only my useful element. So I'm thinking of using anend of arraymarker for integer array. First of all a) Is this possible? b) If possible, How?
I would take a slightly different approach ``` struct IntArray { int data[N]; int size; // <-- use this to keep track of the size. } ```
Difference between start-pointers and interior-pointers and in what situation we should prefer one over other?
As a complete guess, a "start-pointer" is a pointer returned bymallocornew[], whereas an "interior-pointer" is a pointer to the middle of the allocation. If so, then the important difference is that you need tofreethe start-pointer, not an interior-pointer. This isn't terminology from the standard, though. "Interior...
I'm trying to figure out how it is that two variable types that have the same byte size? If i have a variable, that is one byte in size.. how is it that the computer is able to tell that it is a character instead of a Boolean type variable? Or even a character or half of a short integer?
The processor doesn't know. The compiler does, and generates the appropriate instructions for the processor to execute to manipulate bytes in memory in the appropriate manner, but to the processor itself a byte of data is a byte of data and it could be anything. The language gives meaning to these things, but it's an...
How does Matlab/C generates Sine wave, I mean do they store the values for every angle ? but if they do then there are infinite values that are needed to be stored.
There are many, many routines for calculating sines of angles using only the basic arithmetic operators available on any modern digital computer. One such, but only one example, isthe CORDIC algorithm. I don't know what algorithm(s) Matlab uses for trigonometric functions. Computers don't simply look up the value o...
In object type macro it is possible below, ``` #define str "this is a string" ``` I want to know is it possible to use this type of string literal in function type macro like following, ``` #define mkstr(a) #a #define str(s1,s2) mkstr(s1 ## s2 ## "extra") ``` I run this and got error and now i want to know is ther...
Yes. Just place the strings together: the C language accepts that as string constant concatenation. ``` #define str(s1,s2) s1 s2 "extra" ```
I've an array of fixed size inC. There I might have any number (less than the array size) of useful element. Now I need only my useful element. So I'm thinking of using anend of arraymarker for integer array. First of all a) Is this possible? b) If possible, How?
I would take a slightly different approach ``` struct IntArray { int data[N]; int size; // <-- use this to keep track of the size. } ```
I want to use a global variable in inline assembly. asm(" LDR R0,g_TsInitStackPointerAddress"); Here g_TsInitStackPointerAddress is a global variable. While compiling its not showing any error . But while linking it shows the following error [elxr] (error) out of range: 0x1001326 (unsigned) didn't fit in 12 b...
Got the Solution __asm("g_TsInitStackPointerAddress_a: DCD g_TsInitStackPointerAddress "); Give this statement inside that function then it'll take that variable in the inline assembly
I've embedded a Lua interpreter into my C program, and I've got a simple question that I can't seem to find a clear answer to. Suppose I have a C function that I expose to Lua as follows: ``` static int calculate_value(lua_State *L) { double x = luaL_checknumber(L, 1); return 0; } ``` How can I determine (...
In general, you don't. Lua functions that throw errors usesetjmp/longjmp(or exceptions if compiled as C++) to return control to the calling Lua runtime. The error will be presented to the Lua function thatcalledyourcalculate_valuefunction. If you want to handle parameter errors differently, you cannot use Lua'sluaL_c...
I am doing a CBIR system as an assignment.There are 100 .bmp files,but they have different size,how to re-size them to a same size? Thanks.
Have a look at theCImg Library, it's quite easy to use. You can load your bitmap file then use one of theresizefunction.
This question already has answers here:Closed11 years ago. Possible Duplicate:What does 'unsigned temp:3' means ``` struct Test { unsigned a : 5; unsigned b : 2; unsigned c : 1; unsigned d : 5; }; Test B; printf("%u %u %u %u", B.a, B.b, B.c, B.d); // output: 0 0 0 0 static struct ...
That is abit field. It basically tells the compiler thathey, this variable only needs to be x bits wide, so pack the rest of the fields in accordingly, OK?
I currently using android NDK to write some native code in C. I have learned that using JNI we can make two way calls from java to C and from C to java. I am curious if using JNI introduces an extra thread implicitly or is it still one main() thread for the app ? Thanks,
Dalvik Java VM in Android calls the native code from the current Java-thread. It can be any thread - UI or any other. Your native code is free to spawn new threads at will. Of course, the call java->native->java will return to the same thread it was invoked in.
I would like to do something like this: ``` writeLog(printf("This is the error: %s", error)); ``` so i am looking for a function which returns a formatted string.
Given no such function exists, consider a slightly different approach: makewriteLogprintf-like, i.e. take a string and a variable number of arguments. Then, have it format the message internally. This will solve the memory management issue, and won't break existing uses ofwriteLog. If you find this possible, you can ...
I am confused about the evaluation time ofsizeofoperator.When does the sizeof operator get evaluated? Does its evaluation time (compile-time or runtime) depend on the language (C? C++?)? Can we usesizeofin case of objects created at runtime in C++?
In almost all cases,sizeofis evaluated based on static type information (at compile-time, basically). One exception (the only one, I think) is in the case of C99's variable-length arrays (VLAs).
Is it possible on Linux kernel 3.0+ to increase thread's quantum from user-mode? How?
I doubt it's possible. I quickly found this page (http://www.javamex.com/tutorials/threads/thread_scheduling_2.shtml) which suggests that a thread's quanta length is variable anyway, and subject to many attributes of the execution environment. I suppose if you really needed to it should be possible to write a kernel ...
Please look at the following code: ``` char* test ( ) { char word[20]; printf ("Type a word: "); scanf ("%s", word); return word; } void main() { printf("%s",test()); } ``` When the function returns, the variablewordis destroyed and it prints some garbage value. But when I replace ``` char word...
Undefined behavior is just that - undefined. Sometimes it will appear to work, but that is just coincidence. In this case, it's possible that the uninitialized pointer just happens to point to valid writeable memory, and that memory is not used for anything else, so it successfully wrote and read the value. This is ob...
I want to implement a hashing technique inCwhere all the permutation of a string have same hash keys.e.g.abc&cabboth should have same keys. I have thought of adding theasciivalues & then checkingfrequency of characters[important otherwise bothabc&aadwould have same keys which we do not want].But, it doesn't seem to b...
Why not sort the string's characters before hashing?
in my program I compare char against hexadecimal int and I get different results for running in X86 PC and ARM handheld, compiled with arm-gcc or native gcc on n900, either way, condition is true for PC and not passing on mobile. ``` int main(int argc, char *argv[]) { if (*argv[1] == 0xffffffcc) puts(...
It's probably more sensible to compare with an acutal character constant. Although integer promotions will still happen to both operands of==, at least they will happen in the same way and you will not be depending on the signedness of yourcharof the size of yourintorunsigned int. E.g. ``` if (*argv[1] == '\xcc') ``...
May I know if there is any way to remove non-alphabetical symbols from a string in C? For instance I have anchar array[5][5]with:"hi", "my..", "name", "is,,", "bob!" Desired output:"hi", "my", "name", "is", "bob" Is there anyway to remove the symbols?
Here is a very simple implementation: ``` void keepalnum(char *src) { unsigned char *dest = src; while ((*dest = *src++)) dest += isalnum(*dest) ? 1 : 0; } ``` The idea is to advance the source pointer after each copy, but move the destination pointer only when you see an alphanumeric character. Her...
I have the following array in fortran77 dec(3, 25000), even if only the 8898 out of the 25000 positions in the second dimension are used. I'm passing this array as a parameter, together with other arrays, to a C function. Even though the other parameter's values seem to be right, the dec() values are wrong. I've tri...
Keep in mind that the major order for bidimensional arrays is swapped between the two languages. Sodec[i][j]in one language would bedec[j][i]in the other, plus index base adjustment as you have already found out.
Why do most string functions in the C/C++ stdlibs takechar*pointers? The signed-ness ofcharis not even specified in the standard, though most modern compilers (GCC, MSVC) treatcharas signed by default. When would it make sense to treat strings as (possibly) signed bytes? AFAIK there are no meaningful character value...
I'm pretty sure most of the string functions predate the existence ofunsigned char.Plaincharmay be either a signed or an unsigned type. The C and C++ standards explicitly allow either one (it's always a separate type from eitherunsigned charorsigned char, but has the same range as one or the other).While the C string ...
When I run my CLI program on my iphone i get a Segment fault: 11 error. I dunno what to do, I'm a noob at C. ``` int main (int argc, const char * argv[]) { if (argc > 1 && (!strcmp(argv[1],"--help") || !strcmp(argv[1],"-h"))) { printf("#### redhai 1.2 ####\n"); printf("-j Jailbreak\n"); printf("-i Device...
You are accessingargv[1]without first checking if it exists. You need to first check ifargc > 1. ``` } else if (argc > 1 && !strcmp(argv[1],"-j")) { // ^^^^^^^^^^^^ ```
What is the lexical and syntactic analysis during the process of compiling. Does the preprocessing happens after lexical and syntactic analysis ?
Consider this code: ``` int a = 10; if (a < 4) { printf("%d", a); } ``` In theLexical Analysisphase: You identify each word/token and assign a meaning to it. In the code above, you start by identifying thatifollowed bynfollowed bytand then a space is the wordint, and that it is a language ke...
Does the stack of a thread/process make seperate copy of static function/method or is it shared.if it is shared where it is kept/stored and how does the mechanism works in C. Rgds, Softy
Static function is used to limit the scope of the function within file. As it is a function(code) it goes to text(code) segment. You can understand in details from following article http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory
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 I have to create a tester program for a C project (codetester.c). The user calls the program by executing...
Define your main function like ``` int main(int argc, char *argv[]); ``` argcholds the number of arguments, this will be 2 for "codetester filename".argvholds an array of char sequences;argv[0]will be "codetester" andargv[1]will be "filename".
I have a command line program developed in c. Lets say, i have a parser written in C. Now i am developing a project with gui in python and i need that parser for python project. In c we can invoke a system call and redirect the output to system.out or a file. Is there are any way to do this python? I have both code an...
Sure you can, go for a subprocess. Docs are here:http://docs.python.org/library/subprocess.html#module-subprocess
i'm wondering how can I compare in C language, a number I put onargv[2]and aintnumber in my code: ``` EX: prog.exe file.txt 74 ======================== int n; scanf ("%d", &n); if (n > argv[2]) { [...] } ``` How can I compare those different kind of data?
Any command line parameters passed to your app are stored inargvas character pointers (aka "C strings"). You need to convert the string to an integer via any of the dozens of methods (simplest isatoi) before comparing. If you are writing serious production code, avoid usingatoias it is difficult to distinguish betwee...
Right now each module is writing to stderr, thus I cannot turnoff output of an individual one. Does anyone know how I can associate a stream with stdout thus each module will write to independent stream so I can turn it off. For example: ``` fprintf(newStdout, "hello"); ``` newStdoutis writing to the screen. I don'...
Fromhttp://www.cplusplus.com/reference/clibrary/cstdio/freopen/- Its a C++ reference, but should be valid for C. ``` include <stdio.h> int main () { freopen ("myfile.txt","w",stdout); printf ("This sentence is redirected to a file."); fclose (stdout); return 0; } ``` I don't think you can do this on a per-m...
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 I use codeblocks IDE and gcc compiler. I tried to write the simple program billing system.We I use the getc...
You have not mentioned in what platform you are compiling. If it's Linux you can not usegetch()sinceconio.his only for dos. But with this error message is most probably caused by incorrect integration of gcc with Code::Blocks. Try compling with gcc directly.
I wanted to upload a jpeg image file on the server.I have a GoAhead web server which supports only cgi c program as a serverside handeling. Can any one know how to handle http posted image file in program witten in cgi in c language?
The GoAhead web server has a file upload filter for this purpose. The upload filter receives the uploaded file and saves it to disk. It then sets some request variables describing the upload. Those variables are accessible via CGI or via action functions or JST templates. There is an example in test.c. Search for upl...
I need a macro which helps to output the given parameter's name and value. It's something like the following code. ``` #define AA "Hello" #define BB "World" #define PRINT(input_param) printf("input_param: %s\n", (input_param)) void main() { PRINT(AA); PRINT(BB); } ``` I'm expecting the result:AA: Hello\n BB: Wor...
You need to stringize the macro name with#. This is howassert()works as well: ``` #define AA "Hello" #define BB "World" #define PRINT(input_param) printf(#input_param ": %s\n", (input_param)) void main() { PRINT(AA); PRINT(BB); } ``` It may be more clear if I wrote it like this: ``` #define PRINT(input_param) ...
Something like this: ``` _declspec(align(16)) float dens[4]; //Here the code comes. F32vec4 S_START, Pos, _Vector *((__m128*)dens) = (S_START - Pos) *_Vector; float steps = max(max(dens[3], dens[2]), max(dens[1], dens[0])); ``` How do I do this directly using SSE?
There's no easy way to do this. SSE isn't particularly meant for horizontal operations. So you have to shuffle... Here's one approach: ``` __m128 a = _mm_set_ps(10,9,7,8); __m128 b = _mm_shuffle_ps(a,a,78); // {a,b,c,d} -> {c,d,a,b} a = _mm_max_ps(a,b); b = _mm_shuffle_ps(a,a,177); // {a,b,c,d} -> {b,a,d...
Please look at the following code: ``` char* test ( ) { char word[20]; printf ("Type a word: "); scanf ("%s", word); return word; } void main() { printf("%s",test()); } ``` When the function returns, the variablewordis destroyed and it prints some garbage value. But when I replace ``` char word...
Undefined behavior is just that - undefined. Sometimes it will appear to work, but that is just coincidence. In this case, it's possible that the uninitialized pointer just happens to point to valid writeable memory, and that memory is not used for anything else, so it successfully wrote and read the value. This is ob...
I want to implement a hashing technique inCwhere all the permutation of a string have same hash keys.e.g.abc&cabboth should have same keys. I have thought of adding theasciivalues & then checkingfrequency of characters[important otherwise bothabc&aadwould have same keys which we do not want].But, it doesn't seem to b...
Why not sort the string's characters before hashing?
in my program I compare char against hexadecimal int and I get different results for running in X86 PC and ARM handheld, compiled with arm-gcc or native gcc on n900, either way, condition is true for PC and not passing on mobile. ``` int main(int argc, char *argv[]) { if (*argv[1] == 0xffffffcc) puts(...
It's probably more sensible to compare with an acutal character constant. Although integer promotions will still happen to both operands of==, at least they will happen in the same way and you will not be depending on the signedness of yourcharof the size of yourintorunsigned int. E.g. ``` if (*argv[1] == '\xcc') ``...
May I know if there is any way to remove non-alphabetical symbols from a string in C? For instance I have anchar array[5][5]with:"hi", "my..", "name", "is,,", "bob!" Desired output:"hi", "my", "name", "is", "bob" Is there anyway to remove the symbols?
Here is a very simple implementation: ``` void keepalnum(char *src) { unsigned char *dest = src; while ((*dest = *src++)) dest += isalnum(*dest) ? 1 : 0; } ``` The idea is to advance the source pointer after each copy, but move the destination pointer only when you see an alphanumeric character. Her...
I have the following array in fortran77 dec(3, 25000), even if only the 8898 out of the 25000 positions in the second dimension are used. I'm passing this array as a parameter, together with other arrays, to a C function. Even though the other parameter's values seem to be right, the dec() values are wrong. I've tri...
Keep in mind that the major order for bidimensional arrays is swapped between the two languages. Sodec[i][j]in one language would bedec[j][i]in the other, plus index base adjustment as you have already found out.
Why do most string functions in the C/C++ stdlibs takechar*pointers? The signed-ness ofcharis not even specified in the standard, though most modern compilers (GCC, MSVC) treatcharas signed by default. When would it make sense to treat strings as (possibly) signed bytes? AFAIK there are no meaningful character value...
I'm pretty sure most of the string functions predate the existence ofunsigned char.Plaincharmay be either a signed or an unsigned type. The C and C++ standards explicitly allow either one (it's always a separate type from eitherunsigned charorsigned char, but has the same range as one or the other).While the C string ...
When I run my CLI program on my iphone i get a Segment fault: 11 error. I dunno what to do, I'm a noob at C. ``` int main (int argc, const char * argv[]) { if (argc > 1 && (!strcmp(argv[1],"--help") || !strcmp(argv[1],"-h"))) { printf("#### redhai 1.2 ####\n"); printf("-j Jailbreak\n"); printf("-i Device...
You are accessingargv[1]without first checking if it exists. You need to first check ifargc > 1. ``` } else if (argc > 1 && !strcmp(argv[1],"-j")) { // ^^^^^^^^^^^^ ```
What is the lexical and syntactic analysis during the process of compiling. Does the preprocessing happens after lexical and syntactic analysis ?
Consider this code: ``` int a = 10; if (a < 4) { printf("%d", a); } ``` In theLexical Analysisphase: You identify each word/token and assign a meaning to it. In the code above, you start by identifying thatifollowed bynfollowed bytand then a space is the wordint, and that it is a language ke...
Does the stack of a thread/process make seperate copy of static function/method or is it shared.if it is shared where it is kept/stored and how does the mechanism works in C. Rgds, Softy
Static function is used to limit the scope of the function within file. As it is a function(code) it goes to text(code) segment. You can understand in details from following article http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory
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 I have to create a tester program for a C project (codetester.c). The user calls the program by executing...
Define your main function like ``` int main(int argc, char *argv[]); ``` argcholds the number of arguments, this will be 2 for "codetester filename".argvholds an array of char sequences;argv[0]will be "codetester" andargv[1]will be "filename".
I'd like to save my "screen" in bmp; but a think I'm doing it wrong because this code is really slow: ``` HDC Win = GetDC(NULL); for (j = 0; j < y; j++) for (i = 0; i < x; i++) img->data[j][i] = GetPixel(Win, i, j); ```
CreateDIBSectionto create a bitmap with pointer to raw bits, andBitBltfrom screen into the created bitmap. This works way faster than pixel by pixel queries and you have all the data in memory accessible using regular pointer. SeePerforming full screen grab in windowsfor a code snippet.
How do I do the opposite of this: ``` while((*i2s) & (1<<19)) usleep(10); ``` I want to keep sleeping while the 19th bit is 0.
``` while(((*i2s) & (1<<19)) == 0) usleep(10); ``` of course.
``` #include<stdio.h> int main() { char *s[] = { "knowledge","is","power"}; char **p; p = s; printf("%s ", ++*p); printf("%s ", *p++); printf("%s ", ++*p); return 0; } ``` Output: nowledge nowledge s Please explain the output specially output from the 2ndprintf()statement.I think that b...
first one increments *p and displays the string (setting it to the n in knowldege). second one displays the string *p then increments p (moving it to "is"). third one increments *p then displays the string (which starts at the s in "is").
I'm sure others have already asked this, but is it possible to insert an element into the next available index of an array without using a for-loop to find that index first? Almost like a list.add() function but for arrays in C.
no, you will have to loop through the array.
For example when I input 2 for num1 and 3 for num2, I expect to get 8 for the output as soon as I enter the second number. However, the program expects me to input one more integer, and I just input a random number like 242 and it still outputs 8, which means that it does not affect the result. So my question is why i...
Get rid of the newlines:\n, in yourscanfformat strings, or just use a singlescanf, e.g.: ``` scanf("%i%i", &a, &b); ``` Or: ``` scanf ("%i", &a); scanf ("%i", &b); ```
I am having this structure in a .c file: ``` struct entry { int position; int length; struct entry *node; }; ``` Now, how can I limit the scope of this structurelayoutto the host file, so that when using the same name for a new structurelayoutin another file, I don't get 'redefinition' error? I tried us...
You won't get a redefinition error. Types are local totranslation units, and don't have any visibility. Only functions and data objects have visibility. If you're getting a redefinition error, you must be using that name in a header or other included file so it ends up in the same translation unit.
This is the faulty code ``` #include<stdio.h> #define CAT_I(A, B) A ## B #define CAT(A, B) CAT_I(A,B) void main (void) { printf(CAT("HELLO","WORLD")); } ``` Why it gives that error? How could I fix it? EDIT This is what I am trying to do ``` #define TAG "TAG" #define ...
The result of##must be a single token, and"HELLO""WORLD"is not a single token. To concatenate strings, simply leave them beside each other: ``` printf("HELLO" "WORLD"); ``` Or change your macro to remove the##. ``` #define CAT(A, B) A B ``` String literals are concatenated together when there are no intervening to...
``` fprintf(pFile,msg.c_str()); ``` why do I get a warning in Xcode : ``` Format string is not a string literal (potentially insecure) ``` I assume I get this warning to prevent attacks were msg contains some thing like%swhich stream the stack to the screen until it gets to null termination. Is there any safe way t...
You can either give a format string, ``` fprintf(pFile, "%s", msg.c_str()); ``` or usefputs, ``` fputs(msg.c_str(), pFile); ```
Every so often I see "Speed Up Your PC" programs that offer a RAM cleaning feature. They claim to defrag and free up unused memory like a garbage collector or something... not sure. Here are some examples: http://www.softpedia.com/get/Tweak/Memory-Tweak/Clean-Ram.shtml http://download.cnet.com/Instant-Memory-Clean...
If you really insist on doing this, you could enumerate processes, open a handle to each, and callSetProcessWorkingSetSize(process_handle, -1, -1);for each (but youreallydon't want to do this).
With the C standard librarystdio.h, I read that to output ASCII/text data, one should use mode"w"and to output binary data, one should use"wb". But why the difference? In either case, I'm just outputting a byte (char) array, right? And if I output a non-ASCII byte in ASCII mode, the program still outputs the correct ...
Some operating systems - mostly named "windows" - don't guarantee that they will read and write ascii to files exactly the way you pass it in. So on windows they actually map \r\n to \n. This is fine and transparent when reading and writing ascii. But it would trash a stream of binary data. Basically just always give ...
Commands like sftp work in a way that it's not possible to pipe in user input (ex:password etc...) Q1: How does sftp achieve this? Q2: How do programs like expect get around this restriction?
Requires TTY to be connected for input.expect et al. allocate PTTYs to get around this.
I compiled a shared library with pthreads. Why the address is "00000000" when I use pthread option to compile ? What does that mean ? Is that pthread_create is embedded into binary? (Anyway all works as expected in both methods) Here is the objdump output for with -lpthread ``` 00000000 DF *UND* 00000aa5 GL...
It's not relocated yet. Usually executables on modern OS use offsets and not direct addresses. This way you can load the executable at any address, but you need to process all offsets for that. There are special sections on each executable format that indicate what and how to relocate (e.g..relocon ELF format). More...
I have to communicate with a device which listens on a port for all incoming IP/UDP connection , Ethernet frame carries ip/udp packet which in turn have to carry my own packet say own packet, which is to be like following ``` | first field | second field | third field | fourth field | |2byte mes...
Create a new socket, in datagram mode.Format your content into a buffer.Write the buffer to the socket.
I'm readingThe C Programming Language. Here is a question which is sayingWrite a program to count blanks, tabs, and newlines. Now I can use\nfor newlines and\tfor tabs, but I am hearing first time about blanks! What it really mean by blanks? For the newlines and tabs, I have compiled following program: ``` #include <...
blanks = spaces (' ') Though your code is working I strongly suggest adding{ }for the body of the while loop.
Problem Statement is : Given 2 Dimensional array, print output for example If 4 rows and 6 columns, output would be: ``` 1 2 3 4 5 6 16 17 18 19 20 7 15 24 23 22 21 8 14 13 12 11 10 9 ``` I tried it is looking like square within square but when ...
It's a square spiral.You can read a bout it here:http://metacpan.org/pod/Math::PlanePath::SquareSpiral There's an explanation for theformulas.
Today, i was a little bit surprised about the behavior ofc structure vs c++ structure. fun.cpp:http://ideone.com/5VLPC ``` struct nod { static int i; }; int main() { return 0; } ``` The above program works perfectly. BUT, When the same program is run inCenvironment, it is giving the error: ``` prog.c...
Because in C++, structs are just classes with default visibility ofpublic. So in C, the struct is only a aggregation of data, which does not know anything about the fact that it could be percieved as standalone type. See alsoWhat are the differences between struct and class in C++
I want to create a HTTP request from a specific port using C on a Linux machine. There islibcurlbut I'm not sure if you can specify the interface. Is it possible ? Many thanks :).
Yes it is. Look into the optionsCURLOPT_INTERFACEandCURLOPT_LOCALPORT.
Is there a good C library that I can use in my client application for talking to REST servers ?
libcurl comes to mind, as REST is based around basic HTTP requests. Of course this is just a starting point; you'd need to write a little logic on top of it. I'm not sure if what you're looking for is a source-generating solution where you can point it at a service descriptor and have stubs produced automatically, o...
I can embed hexadecimal values in Python-Strings like this:\xe5abcdefghijklmnoqrstuvqxy\xfdz!\x18\xfejk Is this possible with C?
Yes, using the same notation. ``` printf("\x41\x42\x43\n"); ```
I have to multiply 2 large integer numbers, every one is 80+ digits. What is the general approach for such kind of tasks?
You will have to use a large integer library. There are some open source ones listed on Wikipedia's Arbitrary Precision arithmetic pagehere
I createNthreads usingpthread_createon Linux/gcc. Each thread writes usingfor (;;) printf(...)its ID as fast as it can, nothing else. I let the whole program run for 3 seconds usingusleepand notice that on my4-coreCPU whenN=4it produces something around 1,000,000 lines and whenN=8it produces around 4 times as much. Wh...
I/O and CPU operations are very different. If you run CPU-intensive computations, N=number of cores will be optimal. For I/O, the optimal number can be far higher.
I want to understand in which order are the elements ofh_addr_listsorted when I get thehostentfromgethostbyname. Basically, I'm working on a very old function that gets ahostentstruct fromgethostbyname, and returnesh_addrto the caller. I'm trying to figure out which address will be returned in case of multiple active...
What makes you think that there is "an order" in the first place? What would make any particular address more worthy of being listed first? In other words, I don't think there is a well-defined order for the addresses. You simply get all the addresses that are available to the lookup system.
From Intel'sarticle: The integer format conversions are commonly used in imaging and video applications. For example, they can be used when converting RGBA from four bytes to four floats prior to computation on a pixel. One SSE4 convert instruction can do the same thing as four SIMD instructions did previously, as sh...
Becausepmovzxbddoes only work on 32 bit memory operands or 128 bit sse registers, but not on general purpose registers, you need to insert some type conversions or an explicit load from GPR to SSE. ``` __m128 convert_RGBA_to_float(float* rgba) { return _mm_cvtepi32_ps( _mm_cvtepu8_epi32 ( *(__m128i*)rgba) ); } `...
Where does debian stores C header files likestdio.h,string.hetc? I am working on a project and I need to add a header file to the location but I couldn't locate it anywhere.
The system headers are in/usr/includeand the headers for user-installed packages are in/usr/local/include. But you only should put headers there if you are writing a library which other projects will use. Otherwise, you should use the-Iflag for your compiler to specify the location of additional header file search p...
``` char imei_temp[14] = {0, }; strcpy(imei_temp, "00000000000000"); ``` According to my understanding this is valid code. But Klocwork is saying Buffer overflow, array index of 'imei_temp' may be out of bounds. Array 'imei_temp' of size 14 may use index value(s) 0..14
It's a buffer overflow because your buffer is 14 bytes, but you are writing 15 bytes to it: 14 ascii "0"'s, and a null byte at the end.
I want the size of a C struct to be multiple of 16 bytes (16B/32B/48B/..). It does not matter which size it gets to; it only needs to be multiple of 16 bytes. How could I enforce the compiler to do that?
For Microsoft Visual C++: ``` #pragma pack(push, 16) struct _some_struct { ... } #pragma pack(pop) ``` For GCC: ``` struct _some_struct { ... } __attribute__ ((aligned (16))); ``` Example: ``` #include <stdio.h> struct test_t { int x; int y; } __attribute__((aligned(16))); int main() { printf...
I have seen it in several places where(int)someValuehas been inaccurate and instead the problem called for theround()function. What is the difference between the two? Specifically, if need be, for C99 C. I have also seen the same issue in my programs when writing them in java.
In case of casting afloat/doublevalue toint, you generally loose thefractionalpart due tointeger truncation. This is quite different from rounding as we would usually expect, so for instance 2.8 ends up as 2 with integer truncation, just as 2.1 would end up as 2. Update: Another source of potential (gross) inaccura...
I can embed hexadecimal values in Python-Strings like this:\xe5abcdefghijklmnoqrstuvqxy\xfdz!\x18\xfejk Is this possible with C?
Yes, using the same notation. ``` printf("\x41\x42\x43\n"); ```
I have to multiply 2 large integer numbers, every one is 80+ digits. What is the general approach for such kind of tasks?
You will have to use a large integer library. There are some open source ones listed on Wikipedia's Arbitrary Precision arithmetic pagehere
I createNthreads usingpthread_createon Linux/gcc. Each thread writes usingfor (;;) printf(...)its ID as fast as it can, nothing else. I let the whole program run for 3 seconds usingusleepand notice that on my4-coreCPU whenN=4it produces something around 1,000,000 lines and whenN=8it produces around 4 times as much. Wh...
I/O and CPU operations are very different. If you run CPU-intensive computations, N=number of cores will be optimal. For I/O, the optimal number can be far higher.
I want to understand in which order are the elements ofh_addr_listsorted when I get thehostentfromgethostbyname. Basically, I'm working on a very old function that gets ahostentstruct fromgethostbyname, and returnesh_addrto the caller. I'm trying to figure out which address will be returned in case of multiple active...
What makes you think that there is "an order" in the first place? What would make any particular address more worthy of being listed first? In other words, I don't think there is a well-defined order for the addresses. You simply get all the addresses that are available to the lookup system.
From Intel'sarticle: The integer format conversions are commonly used in imaging and video applications. For example, they can be used when converting RGBA from four bytes to four floats prior to computation on a pixel. One SSE4 convert instruction can do the same thing as four SIMD instructions did previously, as sh...
Becausepmovzxbddoes only work on 32 bit memory operands or 128 bit sse registers, but not on general purpose registers, you need to insert some type conversions or an explicit load from GPR to SSE. ``` __m128 convert_RGBA_to_float(float* rgba) { return _mm_cvtepi32_ps( _mm_cvtepu8_epi32 ( *(__m128i*)rgba) ); } `...
Where does debian stores C header files likestdio.h,string.hetc? I am working on a project and I need to add a header file to the location but I couldn't locate it anywhere.
The system headers are in/usr/includeand the headers for user-installed packages are in/usr/local/include. But you only should put headers there if you are writing a library which other projects will use. Otherwise, you should use the-Iflag for your compiler to specify the location of additional header file search p...
``` char imei_temp[14] = {0, }; strcpy(imei_temp, "00000000000000"); ``` According to my understanding this is valid code. But Klocwork is saying Buffer overflow, array index of 'imei_temp' may be out of bounds. Array 'imei_temp' of size 14 may use index value(s) 0..14
It's a buffer overflow because your buffer is 14 bytes, but you are writing 15 bytes to it: 14 ascii "0"'s, and a null byte at the end.
I want the size of a C struct to be multiple of 16 bytes (16B/32B/48B/..). It does not matter which size it gets to; it only needs to be multiple of 16 bytes. How could I enforce the compiler to do that?
For Microsoft Visual C++: ``` #pragma pack(push, 16) struct _some_struct { ... } #pragma pack(pop) ``` For GCC: ``` struct _some_struct { ... } __attribute__ ((aligned (16))); ``` Example: ``` #include <stdio.h> struct test_t { int x; int y; } __attribute__((aligned(16))); int main() { printf...
I have seen it in several places where(int)someValuehas been inaccurate and instead the problem called for theround()function. What is the difference between the two? Specifically, if need be, for C99 C. I have also seen the same issue in my programs when writing them in java.
In case of casting afloat/doublevalue toint, you generally loose thefractionalpart due tointeger truncation. This is quite different from rounding as we would usually expect, so for instance 2.8 ends up as 2 with integer truncation, just as 2.1 would end up as 2. Update: Another source of potential (gross) inaccura...
Is it possible to callioctlfrom a Linux kernel module? Can anyone provide an example of how it's used?
You can try to callsys_ioctl.It's exported if the kernel is compiled withCONFIG_COMPAT. Or, if you have the device driver'sstruct file_operations, you can call itsioctlhandler directly. However, the ioctl handle would expect pointer parameters to be in the address space of the process currently running, not in the k...
I am trying to compile a code that has a include directory with some header files in it. One header file is referenced as: ``` #include <include/A/example.h> ``` In one of the files. I also have added the correct path of the folder that hasexample.hin the Eclipse:Project -> Properties -> Includes However I get this...
Have you added the directory/home/TJ/workspace/myProjectto the path, and not something else, such ashome/TJ/workspace/myProject(note the missing leading slash) or/home/TJ/workspace/myProject/include/A? Also, remember that <> in the #include directive means standard include files, so maybe you should use ""?
``` #include <stdio.h> void wrapperPrint(char* s) { printf(s); return; } int main() { wrapperPrint("Hello world\n"); wrapperPrint("This is a string"); return 0; } ``` If the program prints strings correctly (it does, tested on gcc 4.6.3) , why do we need format spe...
As-is, there's no problem at all. If, however, you pass in a string containing a percent-sign, that could cause a problem, becauseprintfwould try to treat it as the beginning of a conversion specifier, but 1) the rest of the conversion specifier probably won't be there, and 2) you won't have passed a matching argument...
I am making this assignment in my program and I am getting the warning a titled. Here is the code snippet: table_name[index] = NULL; I could not understand what can be a problem in such a statement.
NULL isnota valid integer, and it is being assigned to an entry of an array made up of presumablyints, so the compiler is complaining. NULL is used as a default pointer value that indicates "nothing" .. if you had a pointer variable and assigned NULL to it, you'd be saying that pointer variable points to "nothing". ...
I typically acquire a character with%c, but I have seen code that used%*c%c. For example: ``` char a; scanf("%*c%c", &a); ``` What is the difference?
In ascanfformat string, after the%, the*character is theassignment-suppressing character. In your example, it eats the first character but does not store it. For example, with: ``` char a; scanf("%c", &a); ``` If you enter:xyz\n, (\nis the new line character) thenxwill be stored in objecta. With: ``` scanf("%*c%...
I'm writing a SQL embedded in C program with tables below: ``` table index:id, xx table a:id, year, yy table b:id, year, zz table c:id, year, vv ``` id in a,b,c belong to id in index Then how to select all the id order by year?
You question is not very clear about what you are after. Superficially, one possible answer might be: ``` SELECT i.id, i.xx, a.year, a.yy FROM index AS i JOIN a ON i.id = a.id UNION SELECT i.id, i.xx, b.year, b.zz FROM index AS i JOIN b ON i.id = b.id UNION SELECT i.id, i.xx, c.year, c.vv FROM index AS i ...
If I create a file in ubuntu like this: "echo "asd" > file.txt" and I do a ls -l file.txt it says that it's size is 4 bytes, but I only wrote 3 (asd). If I do "cat file.txt" it shows the 3 chars that I have added. Why is the file 4 bytes large?
asd+ new line character = 4 bytes ``` $ echo asd | wc -c 4 $ echo -n asd | wc -c 3 $ echo asd | hd 00000000 61 73 64 0a |asd.| 00000004 ``` -n in echo switches newline off hdshows you a hexdump of the stream. You see the0acharacter at the end. That is the fourth character, new...