question
stringlengths
25
894
answer
stringlengths
4
863
I have a binary file :temp.exe This binary (temp.exe) takes two command line argumentsaandb. I also have a fileagrsList.txt, which contains : ``` a1 b1 a2 b2 a3 b3 : : : : an bn ``` Now, I want to pass each line of this file as argument to the binary file. PS: I do not have access to the source code, so that I ...
You can use ``` xargs -rn 2 temp.exe < agrsList.txt ``` The-rmeanstemp.exeis only run if there are parameters. The-n 2meanstemp.exeis run with at most two parameters. If there is an odd number of words inagrsList.txt, thentemp.exewill be run with just one parameter, the last one. Seeman xargsfor further information...
How can I reverse an array of integers from left to right in C programming? ``` #include <math.h> #include <stdio.h> int main() { int k[4] = {1,2,3,4}; N=4; for(k=1; k<=N; k=k+1); printf("%d",flip(k)); } ``` Example: k = [1,2,3,4] flip should give k=[4,3,2,1] k is a number array
DeclareNasint(whereasknot needed). Print remainder by 10 in a loop and decrementN = N/ 10each time, try following code: ``` for(; N; N = N/10) printf(" %d", N % 10); ``` Loop runs till N != 0. It doesn't reverse number, but just print reverse.
So I was using CGo for a number crunching web app and it happens that CGo seems faster. Is there any that I can use CGo on Google App Engine Go runtime.
Nope. CGo is not supported yet, and perhaps never will. This isPaaSafter all and they need to isolate the platform. But you never know. Perhaps a restricted version.
How can I reverse an array of integers from left to right in C programming? ``` #include <math.h> #include <stdio.h> int main() { int k[4] = {1,2,3,4}; N=4; for(k=1; k<=N; k=k+1); printf("%d",flip(k)); } ``` Example: k = [1,2,3,4] flip should give k=[4,3,2,1] k is a number array
DeclareNasint(whereasknot needed). Print remainder by 10 in a loop and decrementN = N/ 10each time, try following code: ``` for(; N; N = N/10) printf(" %d", N % 10); ``` Loop runs till N != 0. It doesn't reverse number, but just print reverse.
So I was using CGo for a number crunching web app and it happens that CGo seems faster. Is there any that I can use CGo on Google App Engine Go runtime.
Nope. CGo is not supported yet, and perhaps never will. This isPaaSafter all and they need to isolate the platform. But you never know. Perhaps a restricted version.
How do I write to a single bit? I have a variable that is either a 1 or 0 and I want to write its value to a single bit in a 8-bitregvariable. I know this will set a bit: ``` reg |= mask; // mask is (1 << pin) ``` And this will clear a bit: ``` reg &= ~mask; // mask is (1 << pin) ``` Is there a way for me to do t...
Assumingvalueis0or1: ``` REG = (REG & ~(1 << pin)) | (value << pin); ``` I useREGinstead ofregisterbecause as@KerrekSBpointed out in OP comments,registeris a C keyword. The idea here is we compute a value ofREGwith the specified bit cleared and then depending onvaluewe set the bit.
Are there linux console (/terminal) equivalents for these WinAPI functions: ``` GetConsoleScreenBufferInfo // for getting cursor position SetConsoleCursorPosition // for setting cursor position SetConsoleWindowInfo // for resizing console window or hiding cursor ReadConsoleOutputCharacter // for reading the character...
You can try usingNCurses for getting cursor position ``` ~$ echo -e "\033[6n" ``` for resizing console window ``` wmctrl -r "Mozilla Firefox" -e <G>,<X>,<Y>,<W>,<H> ```
How does the following code works without giving a name for the typedef in the 3rd line?How compiler assumes pf as a new data type? ``` #include <stdio.h> int fun(int, int); typedef int (*pf) (int, int); int proc(pf, int, int); int main(){ printf("%d\n", proc(fun, 6, 6)); return 0; } int fun(int a, int b){...
It does give it a name: ``` typedef int (*pf) (int, int); ^^ ``` That's the typedef'd name. It reads as:pf is a pointer to a function that takes two ints and returns an int. For more details on how function pointer typedefs work, see: Understanding typedefs for function pointers in CThe function poi...
Here are some links documenting the functions that I want to use: xmlNewNodexmlNewChildxmlNewProp Since these functions use dynamic memory allocation, I want to do error checking, but I couldn't find information about behavior of these functions in case of an error. Do these functions simply return NULL on failure ?...
Yes, like most of thelibxml2functions which return pointers, these returnNULLon failure.
I'm trying to implement HTTP/1.1 protocol using Socket in C language. I just want to know if the Body inside a request can contain strings like: "\r\n" i.e a CR LF. Also, please let me know if there is a maximum limit to the number of characters inside the body.
There are no limits to the size or content of the body in an HTTP request or response.
Are the following same: ``` extern int a[]; ``` and ``` extern int *a; ``` I mean, are they interchangable?
No they are not. You'll see the difference when you try something likea++. There's plenty of questions about the difference between pointers and arrays, I don't think it's necessary to write more here. Look it up.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed10...
This will just create an AF_INET (ipv4) socket that does TCP. Once you callconnectit will bind to a port, if not already done so viabind. If you want to pick a port number yourself, justbindmanually.
I am trying to write an echo server in C (to be honest I'm just copying the code fromhttp://gnosis.cx/publish/programming/sockets.html). Anyhow, compiling the program is no problem but when running it segfaults. gdb gives following error message: Program received signal SIGSEGV, Segmentation fault. 0xb7e46d5c in ??...
try running 'bt' command it will give the stacktrace. The segfault is most probably in your code which is being notified at libc.so.6. Since libc.so.6 is optimized binary it doesnt have debug symbols so you get ?s.
In thesource code ofstdbool.hin LLVM project, it reads: ``` /* Don't define bool, true, and false in C++, except as a GNU extension. */ #ifndef __cplusplus #define bool _Bool #define true 1 #define false 0 #elif defined(__GNUC__) && !defined(__STRICT_ANSI__) /* Define _Bool, bool, false, true as a GNU extension. */ #...
The only reason I can think of is, that preprocessor statements like ``` #ifdef bool // do some stuff or define bool #endif ``` in other c files include afterwards will work proper and not trying to redefine bool in another way like ``` #define bool int ``` which would interfere with the first definition
Anyone knows if it is possible to use printf to print a VARIABLE number of digits? The following line of code prints exactly 2: ``` printf("%.2lf", x); ``` but let's say I have a variable: ``` int precision = 2; ``` Is there a way to use it in printf to specify the number of digits? Otherwise I will have to writ...
It is possible: ``` #include <stdio.h> int main() { int precision = 3; float b = 6.412355; printf("%.*lf\n",precision,b); return 0; } ```
I have recently installed MinGW to my computer, to compile and run programs written in c. Right now I have to manually go to the bin-folder to execute and compile files. The path is C:\MinGW\bin Is there a a way to avoid this everytime? I want be able to directly write the commands when I open the command Line. I ...
A simple solution would be a small batch script. Create a new batch file with this code: ``` @echo off cd C:\MinGW\bin :loop set /p var= %var% goto loop ``` Could you show me youruserenvironment variable called "path"? Maybe we will find the error there. Edit: Create a new environment variable in the upper field (u...
I have 2 arrays of bytes, and i want to copy/append them in the byte array _allBytes. How can i do that? Any suggestions are welcome. ``` Byte _secretBytes[6]; Byte _saltBytes[4]; // append the two arrays Byte *_allBytes[(sizeof(_secretBytes) + sizeof(_saltBytes))]; ```
``` Byte _allBytes[(sizeof(_secretBytes) + sizeof(_saltBytes))]; memcpy(_allBytes, _secretBytes, sizeof(_secretBytes)); memcpy(_allBytes + sizeof(_secretBytes), _saltBytes, sizeof(_saltBytes)); ``` Or, using the Foundation framework (since your question is tagged with iOS/Objective-C): ``` NSMutableData *allData = [...
I am stuck with a classical Multiple Inheritance problem in C. I have created source filesStack.candQueue.c. Both of them #include a file Node.c (which containing functions to allocate and deallocate memory). Now, I am trying to implement another program in a single file, for which I need to include both Stack.c and ...
Calling this "multiple inheritance" may be confusing because multiple inheritance is an object-oriented programming issue that doesn't arise in C. It appears to me that your difficulty may be that you are trying to #include executable code (i.e..cfiles) instead of linking the.cfiles and #including header (.h) files t...
I know there are objective-c (or C) macros for quantities like maximum integer, max float, max unsigned integer, etc. but every time I need to use one I can't remember it and I can't find it by searching. How do you search for those things?
Googlelimits.h.Even better, look up this file on your system.Then, in Xcode (and other IDEs) code-completion is your friend; just start to type "int" and you'll see the list:INT16_MAX,INT16_MIN, ... On Xcode (in iOS project) I did not have to explicitly#include <limit.h>but you may have to do this first on other IDEs...
Is there a way to tell what mode aFILE *was opened? Specifically I need to tell if a file stream is writable. Either just the true/false result of whether it's writable, or theconst char *of the mode itself is good.
Not directly answer your question, but you can usefreopen ``` FILE *freopen(const char *path, const char *mode, FILE *stream); ``` It opens a specified file on a specified stream, closing the stream first if it is already open. If the stream previously had an orientation,freopenclears it.
This question already has answers here:C code won't finish running(4 answers)Closed10 years ago. The purpose of this code is to construct a charHadamard matrixof the size of my choosing. This question is related to a previousquestionI asked. The answer given there was an integer not char matrix, but the code here is...
Note: I've no idea what your program does, but obviously this is wrong. You failed to actually change the control variable in your for-loop (which can be done in the final expression or the loop body itself). Change this: ``` for (ind=1;ind<=sizeH;ind*2) ``` to this: ``` for (ind=1;ind<=sizeH;ind*=2) // << note *=...
/* patch.hoc v. 1.2 10/19/2001 NTC */ load_file("nrngui.hoc") create soma // model topology access soma // default section = soma soma { diam = 10 // soma dimensions in um L = 10/PI // surface area = 100 um^2 }
You're assigning a variable of typestruct ListNodeto a variable of typestruct ListNode *. It looks like you want to assign theaddressof the struct to the pointer, not the struct it self. Try this: ``` n1.next = &n2; n2.next = &n3; n3.next = &n4; ```
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.Closed10 years ago.Improve this question I ahve googled and searched this on stackoverflow, but the results are on how to use pointers. Sorry if my...
Pointers are just integers containing memory addresses. Nothing more. So a pointer itself does not save user data. However, a pointer can point at an instance of aclass/structwhich can itself save user data.
Why doesn't this work? ``` #include<stdio.h> int main() { char ch[50]; ch[50]="manipulation"; puts(ch); } ``` and why does this work? ``` #include<stdio.h> int main() { char ch[50]="manipulation"; puts(ch); } ``` By "it works" I mean i get the output i want, that is, printing of "manipulation"(without quotes) as s...
It doesn't work because with the syntax: ``` ch[50]="manipulation"; ``` You're assigning the string "manipulation" to the 50th element of ch. That's not possible because the array is composed of idividual characters, and you're assigning a string to a individual char. Also, ch has elements from 0 to 49, and there's...
Is there a possibility to just have one coordinate in the vertex buffer, but still draw a square (two GL_TRIANGLES, or a GL_QUADS)? How would my vertex shader look like to archive this? ``` float vertices[]={ 0.0, 0.0, 0.0 } glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER...
Geometry shader (passthrough Vertex Shader) can do this or you can use GL_POINTS, too, although some OpenGL implementations have surprisingly small maximum point sizes. It will probably not be as efficient as passing a proper quad directly.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed10...
Is it true? You can check out theadvantage and disadvantages of Inline Functionsand justify it
I know there are objective-c (or C) macros for quantities like maximum integer, max float, max unsigned integer, etc. but every time I need to use one I can't remember it and I can't find it by searching. How do you search for those things?
Googlelimits.h.Even better, look up this file on your system.Then, in Xcode (and other IDEs) code-completion is your friend; just start to type "int" and you'll see the list:INT16_MAX,INT16_MIN, ... On Xcode (in iOS project) I did not have to explicitly#include <limit.h>but you may have to do this first on other IDEs...
Is there a way to tell what mode aFILE *was opened? Specifically I need to tell if a file stream is writable. Either just the true/false result of whether it's writable, or theconst char *of the mode itself is good.
Not directly answer your question, but you can usefreopen ``` FILE *freopen(const char *path, const char *mode, FILE *stream); ``` It opens a specified file on a specified stream, closing the stream first if it is already open. If the stream previously had an orientation,freopenclears it.
This question already has answers here:C code won't finish running(4 answers)Closed10 years ago. The purpose of this code is to construct a charHadamard matrixof the size of my choosing. This question is related to a previousquestionI asked. The answer given there was an integer not char matrix, but the code here is...
Note: I've no idea what your program does, but obviously this is wrong. You failed to actually change the control variable in your for-loop (which can be done in the final expression or the loop body itself). Change this: ``` for (ind=1;ind<=sizeH;ind*2) ``` to this: ``` for (ind=1;ind<=sizeH;ind*=2) // << note *=...
/* patch.hoc v. 1.2 10/19/2001 NTC */ load_file("nrngui.hoc") create soma // model topology access soma // default section = soma soma { diam = 10 // soma dimensions in um L = 10/PI // surface area = 100 um^2 }
You're assigning a variable of typestruct ListNodeto a variable of typestruct ListNode *. It looks like you want to assign theaddressof the struct to the pointer, not the struct it self. Try this: ``` n1.next = &n2; n2.next = &n3; n3.next = &n4; ```
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.Closed10 years ago.Improve this question I ahve googled and searched this on stackoverflow, but the results are on how to use pointers. Sorry if my...
Pointers are just integers containing memory addresses. Nothing more. So a pointer itself does not save user data. However, a pointer can point at an instance of aclass/structwhich can itself save user data.
Why doesn't this work? ``` #include<stdio.h> int main() { char ch[50]; ch[50]="manipulation"; puts(ch); } ``` and why does this work? ``` #include<stdio.h> int main() { char ch[50]="manipulation"; puts(ch); } ``` By "it works" I mean i get the output i want, that is, printing of "manipulation"(without quotes) as s...
It doesn't work because with the syntax: ``` ch[50]="manipulation"; ``` You're assigning the string "manipulation" to the 50th element of ch. That's not possible because the array is composed of idividual characters, and you're assigning a string to a individual char. Also, ch has elements from 0 to 49, and there's...
Is there a possibility to just have one coordinate in the vertex buffer, but still draw a square (two GL_TRIANGLES, or a GL_QUADS)? How would my vertex shader look like to archive this? ``` float vertices[]={ 0.0, 0.0, 0.0 } glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER...
Geometry shader (passthrough Vertex Shader) can do this or you can use GL_POINTS, too, although some OpenGL implementations have surprisingly small maximum point sizes. It will probably not be as efficient as passing a proper quad directly.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed10...
Is it true? You can check out theadvantage and disadvantages of Inline Functionsand justify it
Is there a way to import a makefile-based C project into an IDE? I want to use IntelliSense, code browsing and other advanced features available in IDEs, so any IDE that has those will do.
NetBeanshas the ability to import a C project based on an existing Makefile. It has most of the features you'd expect from an IDE. Just go toFile->New Projectand selectC/C++ Project with Existing Makefile I use the feature all the time and it seems pretty reliable. Eclipselets you import an existing project too bu...
I have a simpleCprogram (Compiled on the raspberry pi) Which is supposed to calculate 17.67 * 20 (which is 353.4) The below program prints out 353. Is theprintfrounding it off? I've tried "%g" and "%.1f" ``` #include <stdio.h> #include <math.h> int absolute_humidity(float temp) { float abs_hum = (17.67 * temp); ...
``` absolute_humidity returns an `int` ``` Change the signature as ``` float absolute_humidity(float temp); ```
I need an efficient glsl code that doesn't haveif-elsestatement. Currently the algorithm is like this : ``` lowp float a; if (a > 1.0) a -= 1.0; else if (a < 0.0) a += 1.0; ``` It's similar with a floating point modulo operator : ``` a = mod(a,1.0); ``` onlyif a == 1, it shouldreturn 1, instead of0. How ...
Here is a mathematic representation that might do what you need - without using branching statements For inputs between [-1, 2.0] ``` a = a + 1 - max(trunc(a), ceil(a)) Input Output 0.3 0.3 -0.3 0.7 0.7 0.7 1.3 0.3 1.7 0.7 1 1.0 ```
In the below program I try to input a number between1to100but if I entera'character'or"string"( like s orsova) during the execution time ofscanf()statement it creates a infinite loop. so I try to do .... when I input a string or a character it shown me a message like "wrong value entered. enter again" and it will ente...
You need to check the return value ofscanfIf the user has not entered a integer, you need to eat the input. Thescanffunction will continually say not a integer, try again. So ifscanfreturns 0 you need to deal with it
I am trying to get the length of a string but i am getting the wrong value, it is saying that it is only 4 characters long. Why is this? am i usingsizeof()correctly? ``` #include <stdio.h> int main(void) { char *s; int len; s = "hello world"; len = sizeof(s); printf("%d\n", len); } ```
Thesizeofoperator is returning the size of the pointer. If you want the length of a string, use thestrlenfunction. Even if you had an array (e.g.char s[] = "hello world") thesizeofoperator would return the wrong value, as it would return the length of the array which includes the string terminator character. Oh and ...
I am executing the following code to read out a particular value 6 Bytes from an array.For me somehow the following looks ugly.I am running this code on a Little Endian Processor. Is there some way I can make it more elegant. ``` temp_ts = (ptr[ts_offset]); new_ts = temp_ts << 40; temp_ts = (ptr[ts_offset + 1]); new...
You can code it as a loop and let the compiler do the unrolling: ``` for (new_ts = i = 0; i < 6; i++) new_ts = (new_ts << 8) | ptr[ts_offset + i]; ``` For what it's worth, I compiled this withgcc 4.3.6and-O4. It does unroll nicely.
Is there a OpenCV way to (gaussian) smooth just 1 channel in a 3 channel (RGB) image? Any of Python or C or C++ OpenCV is fine.
You can useSplitto split the image into its channels and then useFilter2Don one of the components. ``` Split(src, src_r, src_g, src_b) Smooth(src_r, dst_r) Merge(dst_r, src_g, src_b, dst) ```
I don't know why I am getting warnings for the following code. ``` #include<stdio.h> #include<malloc.h> int main() { int **p; int i,j; for(i=0;i<5;i++) { if(i==0) p=(int*)malloc(1*sizeof(int)); else p=(int*)realloc(p,(i+1)*sizeof(int)); p[i]=(int*)malloc...
You get warnings because p is anint **and you are allocating memory as if it was anint *in yourif..elselines. Simply replace your lines as follows: ``` p=(int **)malloc(1*sizeof(int *)); p=(int **)realloc(p,(i+1)*sizeof(int *)); ```
For our activity today, we were tasked to make using recursion with the sum of digits. I already made this program: ``` int main() { int num = 0, sum; printf("Enter an integer: "); scanf("%d",&num); //counter=1; for ( sum=0; num>0;) { sum = sum + num % 10; num = num /10; } printf("Sum = %d", sum); get...
To do recursion, create a function that recurses rather than using a for loop. ``` int SumDigits(int i) { if (i < 10) { return i; } else { return i%10 + SumDigits(i/10); } } scanf("%d", &i); printf("%d\n", SumDigits(i)); ```
I'm learning about structures within structures and typedef definitions. I understand normal typedef definitions, but in this example a typedef is used for struct data points ``` struct CGPoint{ CGFloat x; CGFloat y; }; typedef struct CGPoint CGPoint; CGPoint rectPt; rectPt.x=2; rectPt.y=3; ``` I dont un...
if you don't use ``` typedef struct CGPoint CGPoint; ``` you can't write ``` CGPoint rectPt; ``` but instead you have to write explicitly ``` struct CGPoint rectPt; ``` because in C defining astructdoesn't automatically define a typename for that as it happens in C++
So I want to know the differences between these two. ``` struct Record { int ID, char *name }Student; typedef struct Record { int ID, char *name }Student; ``` I know that Student in first one is struct variable. But is Student in second one a variable or just a type name?
``` typedef struct Record { ... } Student; ``` This creates a new typestruct Recordalong with a typedef for it namedStudent.Studentis an alias forstruct Record. These would be identical variable declarations: ``` struct Record studentRecord; Student studentRecord; ``` Typically the typedef will be named the same as...
I've created a Plain C project in Qt Creator in Linux, but I'm getting this error: ``` error: 'for' loop initial declarations are only allowed in C99 mode note: use option -std=c99 or -std=gnu99 to compile your code ``` What should I put in my *.pro file to enable C99?
``` QMAKE_CFLAGS += -std=c99 ``` This worked for me, even though it is not documented and the intellisense doesn't recognize it.
This question already has answers here:Why Output is 0000 and How? [duplicate](2 answers)Closed9 years ago. ``` { static int i=5; if(--i) { main(); printf("%d ",i); } } ``` The output of this program is0 0 0 0. Shouldn't this program show compiler error? What am I missing here?
First of all, I +1 your question because in my 15 years of programming I have never thought of recursively calling main()! Now regarding your question, it compiles because main() is just a function like any other function in the code. The only special thing about it is that the linker expects to see a main() in the c...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed10...
that means the button is active on low better known asactive low
In my library, I have an instance structure, which contains everything needed for the library, this is so you can define multiple instances of the library. The library requires the user to define their own extension, or custom variables. This is what I tried: Library.h ``` typedef struct custom_s *custom; typedef ...
Shouldn't it be: test.customs->c = 1 Since you type'd it in typedef struct custom_s *custom; and Used as customin the instance structure. Which is never allocated...
Given this code: ``` int main(void) { __asm volatile ("jmp %eax"); return 0; } ``` 32-bit TCC will complain with: ``` test.c:3: error: unknown opcode 'jmp' ``` but the 64-bit version will compile just fine. What's the problem with the 32 bit code?
The solution is to simply add a star (*) before the register, like this: ``` __asm volatile ("jmp *%eax"); ``` I'm not exactly sure what the star means. According tothisSO post: The star is some syntactical sugar indicating that control is to be passed indirectly, by reference/pointer. As for why it works with 64-...
I'm writing the multithreaded program on Linux and want to create a process in a thread without ending the other threads. I looked into fork/exec but in the exec man page in section 3p on linux states: ``` A call to any exec function from a process with more than one thread shall result in all threads being t...
But if you fork() first and exec in the child, the child process only has one thread and that is destroyed by the exec function. The parent process and all of its threads are unaffected.
This is yet another sequence-point question, but a rather simple one: ``` #include <stdio.h> void f(int p, int) { printf("p: %d\n", p); } int g(int* p) { *p = 42; return 0; } int main() { int p = 0; f(p, g(&p)); return 0; } ``` Is this undefined behaviour? Or does the call tog(&p)act as a sequence poin...
No. It doesn't invokeundefinedbehavior. It is justunspecified, as the order in which the function arguments are evaluated is unspecified in the Standard. So the output could be0or42depending on the evaluation order decided by your compiler.
How can I delete a new line character once printed in a C code? I want to write a bunch of lines and delete them and after a pause print some other lines then delete them...in a loop. Like a real time update without scrolling. I can print characters and delete them by printing backspace character but once I print new ...
The backspace character'\b'(ASCII 8)movesto the previous positionwithin the line. If you are underxtermorvt100compatible you can make use ofconsole codes: ``` #include <stdio.h> #include <unistd.h> /* for sleep() */ int main(void) { printf("Line\n"); sleep(2); printf("\033[A"); /* move cursor one line u...
``` char* fun() { return("samsung india"); } main() { printf("%s",printf("electronics")+fun()); } ``` Output: "electronicsia" could somebody please explain me this output ?
printf("electronics")sends the output to stdout and returns the number of characters printed, which is 11, and sincefun()returns a char-pointer, you are adding 11 to that pointer before the outer printf sends it to stdout. So the inner printf outputs "electronics" and after that the outer printf outputs "ia".
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed10 years ago. Code in C language. ``` #include<stdio.h> #define PRODUCT(x) ( x * x * x) int main() { int i =5,k; k = PRODUCT( ++i ); printf("i is :%d ",k); return 0; } ``` My Que...
Preprocessed code will have ( ++i * ++i * ++i) which have Lack ofsequence pointbetween the two execution on same variable resultingUndefined behaviour.
I've created a Plain C project in Qt Creator in Linux, but I'm getting this error: ``` error: 'for' loop initial declarations are only allowed in C99 mode note: use option -std=c99 or -std=gnu99 to compile your code ``` What should I put in my *.pro file to enable C99?
``` QMAKE_CFLAGS += -std=c99 ``` This worked for me, even though it is not documented and the intellisense doesn't recognize it.
This question already has answers here:Why Output is 0000 and How? [duplicate](2 answers)Closed9 years ago. ``` { static int i=5; if(--i) { main(); printf("%d ",i); } } ``` The output of this program is0 0 0 0. Shouldn't this program show compiler error? What am I missing here?
First of all, I +1 your question because in my 15 years of programming I have never thought of recursively calling main()! Now regarding your question, it compiles because main() is just a function like any other function in the code. The only special thing about it is that the linker expects to see a main() in the c...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed10...
that means the button is active on low better known asactive low
In my library, I have an instance structure, which contains everything needed for the library, this is so you can define multiple instances of the library. The library requires the user to define their own extension, or custom variables. This is what I tried: Library.h ``` typedef struct custom_s *custom; typedef ...
Shouldn't it be: test.customs->c = 1 Since you type'd it in typedef struct custom_s *custom; and Used as customin the instance structure. Which is never allocated...
Given this code: ``` int main(void) { __asm volatile ("jmp %eax"); return 0; } ``` 32-bit TCC will complain with: ``` test.c:3: error: unknown opcode 'jmp' ``` but the 64-bit version will compile just fine. What's the problem with the 32 bit code?
The solution is to simply add a star (*) before the register, like this: ``` __asm volatile ("jmp *%eax"); ``` I'm not exactly sure what the star means. According tothisSO post: The star is some syntactical sugar indicating that control is to be passed indirectly, by reference/pointer. As for why it works with 64-...
I'm writing the multithreaded program on Linux and want to create a process in a thread without ending the other threads. I looked into fork/exec but in the exec man page in section 3p on linux states: ``` A call to any exec function from a process with more than one thread shall result in all threads being t...
But if you fork() first and exec in the child, the child process only has one thread and that is destroyed by the exec function. The parent process and all of its threads are unaffected.
This is yet another sequence-point question, but a rather simple one: ``` #include <stdio.h> void f(int p, int) { printf("p: %d\n", p); } int g(int* p) { *p = 42; return 0; } int main() { int p = 0; f(p, g(&p)); return 0; } ``` Is this undefined behaviour? Or does the call tog(&p)act as a sequence poin...
No. It doesn't invokeundefinedbehavior. It is justunspecified, as the order in which the function arguments are evaluated is unspecified in the Standard. So the output could be0or42depending on the evaluation order decided by your compiler.
How can I delete a new line character once printed in a C code? I want to write a bunch of lines and delete them and after a pause print some other lines then delete them...in a loop. Like a real time update without scrolling. I can print characters and delete them by printing backspace character but once I print new ...
The backspace character'\b'(ASCII 8)movesto the previous positionwithin the line. If you are underxtermorvt100compatible you can make use ofconsole codes: ``` #include <stdio.h> #include <unistd.h> /* for sleep() */ int main(void) { printf("Line\n"); sleep(2); printf("\033[A"); /* move cursor one line u...
``` char* fun() { return("samsung india"); } main() { printf("%s",printf("electronics")+fun()); } ``` Output: "electronicsia" could somebody please explain me this output ?
printf("electronics")sends the output to stdout and returns the number of characters printed, which is 11, and sincefun()returns a char-pointer, you are adding 11 to that pointer before the outer printf sends it to stdout. So the inner printf outputs "electronics" and after that the outer printf outputs "ia".
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed10 years ago. Code in C language. ``` #include<stdio.h> #define PRODUCT(x) ( x * x * x) int main() { int i =5,k; k = PRODUCT( ++i ); printf("i is :%d ",k); return 0; } ``` My Que...
Preprocessed code will have ( ++i * ++i * ++i) which have Lack ofsequence pointbetween the two execution on same variable resultingUndefined behaviour.
Assume I have code like: ``` if(condition1 || condition2 || condition 3 || condition4) { // this inner part will be executed if one of the conditions is true. // Now I want to know by which condition this part is executed. } ```
I'm sure there are better ways to do this, here's one: ``` int i = 0; auto check = [&i](bool b)->bool { if (!b) ++i; return b; }; if (check(false) || // 0 check(false) || // 1 check(true) || // 2 check(false)) // 3 { std::cout << i; // prints 2 } ```
I want to write a command line shell for a background program, and in witch I can type some commands. I want to add a feature like the bash (or other shell-like) ---'UP' key to get the historic input. How can I capture the 'UP' key was pressed? If I just usestd::getline(std::cin, line)I can't get the 'UP' key or othe...
There is areadlinefunction that supports history and line editing, etc. In basic mode it does reading of line, etc. If you want to add hooks, you can make it expand commands when pressingtabor similar. This is what your typical shell in Linux uses. Documentation here:http://web.mit.edu/gnu/doc/html/rlman_2.html An...
I have the coordinates of 4 points, and I want to to draw a quad based on those coordinates in opencv! is there in function that can based on those point draw a region! I know thatrectcan do that but I know I'll not always have a rectangle!
I would suggest to use polygon drawing withpolylinesorfillPolyseedrawing functionsfor more information.
This question already has answers here:Is uninitialized data behavior well specified?(7 answers)What will be the value of uninitialized variable? [duplicate](6 answers)Closed9 years ago. Please explain why I am getting output 2 here. My expected o/p is 5 or 7. Please throw some light. Thank you! ``` #include<stdio.h...
You haven't initializedes, so your program is just printing the random value that happens to be on the stack when the program runs. You need to say something like: ``` e es = c; ``` That will give you the5output you seek.
Below are the code snippets of generic qsort on C. What do I write in the fourth parameter of the genmyqsort when it's called in the recursion? ``` int compnode(node *a, node *b){ return(strcmp(a->name,b->name)); } void genmyqsort(void *a, int n, int size, int (*fcmp)(const void*,const void*)){ int pivot; i...
You pass the same comparator as you got from the caller (fcmp): ``` genmyqsort(a*size, pivot, size, fcmp); genmyqsort(a+(pivot+1)*size, n-pivot-1, size, fcmp); ``` This will ensure that all instances ofgenmyqsort()in the call tree will compare array elements in exactly the same way.
In the following program line 5 gives an error but 11 does not while both are doing same things i.e initialization of a string with 0? I very well know that it gives compiler error.My doubt exactly is if line 5 gives error then why line 11 doesnot? ``` #include<stdio.h> int main() { char name[20]=0; ...
If you want to initialize a compound object (arrays, structures, unions) then you need to put the values inside curly braces{}. So you need to write ``` char name[20] = { 0 }; /* Or '\0' */ ``` Strings are a special case, where the compiler handles that, so you can write e.g. ``` char name[20] = ""; ```
I am having a problem with a program of mine, as I cannot see the output display. Using a Dev C++ compiler to compile my C program, I debug it to see the output. However my program immediately terminates, so I can't see the output properly. I ended my program with return 0, and Aldo tried getch(), but even with bot...
you need the window stop to view the output, is it right? if yes, include this library ``` #include <stdlib.h> ``` then add this line at the end of code: ``` system("PAUSE"); ``` e.g ``` #include <stdlib.h> #include <stdio.h> int main() { /* do/print some thing*/ system("PAUSE"); } ```
When I run make on this program I am trying to build, I get these warnings: ``` ld: warning: ignoring file ../lib/libiptools.a, file was built for archive which is not the architecture being linked (x86_64) ld: warning: ignoring file ../lib/libmpeg.a, file was built for archive which is not the architecture being lin...
libiptools.a and libmpeg.a are compiled for 32-bit, but the rest of your project is compiled for 64-bit. Either find 64-bit versions of those libraries, or compile for 32-bit.
I have an issue where I am inputting an decimal argument to my code: ``` ./a.out 650 ``` and would like to simply convert the decimal value into hex and output it in a little-endian format: ``` 0A28 ``` My current solution has been to convert the char* to decimal using atoi (we can assume the input is decimal, no ...
Like this: ``` #include <stdio.h> #include <stdlib.h> unsigned long int n = strtoul(argv[1], NULL, 0); unsigned char const * p = (unsigned char const *)&n; for (size_t i = 0; i != sizeof n; ++i) printf("%02X", p[i]); ``` To print the reverse endianness, usesizeof n - i - 1in place ofi.
In the following program line 5 gives an error but 11 does not while both are doing same things i.e initialization of a string with 0? I very well know that it gives compiler error.My doubt exactly is if line 5 gives error then why line 11 doesnot? ``` #include<stdio.h> int main() { char name[20]=0; ...
If you want to initialize a compound object (arrays, structures, unions) then you need to put the values inside curly braces{}. So you need to write ``` char name[20] = { 0 }; /* Or '\0' */ ``` Strings are a special case, where the compiler handles that, so you can write e.g. ``` char name[20] = ""; ```
I am having a problem with a program of mine, as I cannot see the output display. Using a Dev C++ compiler to compile my C program, I debug it to see the output. However my program immediately terminates, so I can't see the output properly. I ended my program with return 0, and Aldo tried getch(), but even with bot...
you need the window stop to view the output, is it right? if yes, include this library ``` #include <stdlib.h> ``` then add this line at the end of code: ``` system("PAUSE"); ``` e.g ``` #include <stdlib.h> #include <stdio.h> int main() { /* do/print some thing*/ system("PAUSE"); } ```
When I run make on this program I am trying to build, I get these warnings: ``` ld: warning: ignoring file ../lib/libiptools.a, file was built for archive which is not the architecture being linked (x86_64) ld: warning: ignoring file ../lib/libmpeg.a, file was built for archive which is not the architecture being lin...
libiptools.a and libmpeg.a are compiled for 32-bit, but the rest of your project is compiled for 64-bit. Either find 64-bit versions of those libraries, or compile for 32-bit.
I have an issue where I am inputting an decimal argument to my code: ``` ./a.out 650 ``` and would like to simply convert the decimal value into hex and output it in a little-endian format: ``` 0A28 ``` My current solution has been to convert the char* to decimal using atoi (we can assume the input is decimal, no ...
Like this: ``` #include <stdio.h> #include <stdlib.h> unsigned long int n = strtoul(argv[1], NULL, 0); unsigned char const * p = (unsigned char const *)&n; for (size_t i = 0; i != sizeof n; ++i) printf("%02X", p[i]); ``` To print the reverse endianness, usesizeof n - i - 1in place ofi.
I have a working client/server implementation in UDP in C, but I'm trying to figure out how to get the server to send a variable back to the client. This is because the client sends X packets in 60 seconds, and the server will successfully receive Y packets. I want the server to return the Y variable to the client s...
It is possible. On the server side extract clients address and use it: ``` n = recvfrom(sockfd,msg,1000,0,(struct sockaddr *)&cliaddr,&len); sendto(sockfd,msg,n,0,(struct sockaddr *)&cliaddr,sizeof(cliaddr)); ``` On the client's side: left as an exercise for the reader.
In the following code, ``` #include <stdio.h> #include<conio.h> main() { int y=-01; y<<=3; printf("%d\n",y); y>>=3; printf("%d",y); getch(); } ``` I read in a book that while using the right shift operator on y, the signed bit may or may not be preserved depending on my compiler. Why is that?...
Some processors have only an "unsigned" right shift (fills the sign bit with 0's) or a signed right shift (fills the size bit with copies of the current sign bit). Since some processors only have one or the other, but not both, the standard doesn't try to mandate one behavior or the other. For what it's worth, many (...
I am having an issue with the % operator in C. I know that the % operator gives the remainder of a division. However when faced with a question like1 % 2or3 % 2, I get confused. After googling this, I found different solutions. Some say that as1 / 2is0.5, we round it down to 0. So1 % 2is 0. Others say that as1 /...
%is the remainder operator: The % operator computes theremainder after dividing its first operand by its second. It's what left from the division. For example: 5 % 3 is 2.5 % 4 is 1.5 % 2 is 1. (Because 2 can fit 2 times in 5, 1 will be left) When you do 1 % 2 the result is 1 because 1/2 is 0, and the remainder ...
How One can access a variable from ONLY two functions that a file consists of total five functions.(No global or static declaration)
You can't in C; the file is the compilation unit that defines the boundaries forstaticvariables of that sort, since anyone who can edit or view that file could work with all of the functions in it. If you really need to separate visibility, you have to split the functions into multiple files.
When I press Ctrl+c then SIGINT will be passed to signal() . What value will be pass to the system call signal() when i press a key A ?
No signal will be raised. The purpose of signals is to inform about a special condition outside normal program flow. Processing input, like the letter A, is part of normal program flow. These two are completely separate, and have different goals. If you're on UNIX, typeman signalon your console.
I am trying to compile Linphone for windows but when I run "./configure --prefix=/opt/linphone --enable-shared --disable-static" I get an error message claiming that I cannot run C compiled programs. I am using Mingw on Windows 8, I have installed the C++ and C compilers and also the Mingw Developer Tools
It appears to be a target mismatch error. Mingw32 binaries cannot be run on windows 32-bit kernel. You should try installing Mingw64 binaries. Also try building from a linux or windows machine. I had this issue which I resolved later by compiling on Mac.
Hey I have something of this type ``` eph_t *a; ``` The type is eph_t as you can see. Its an array in C but I do not know the size of the array nor do I know what is the end element of the array. Is there a way, I can go through the whole array because I want to assign the values of every element in an array to some...
If you do not know the size of the array then it is unsafe to iterate over it. Any time that you attempt to read elements beyond the last one you will get undefined behaviour. There is nothingsafeyou can do unless you know the size of the array.
I have developed C/C++ binaries and I have android app. I have ported binaries on linux base server and now I would like to use this binaries in my android app. Can i call this binaries from my app? Is it possible, please excuse me as I don't have any idea about this.
Here you will find a nice tutorial to implement C code into your Android Project: JNI tutorial
I want to access information inside a struct if somebody can help me out here. ``` typedef struct { int time; char sat,rcv; char LLI [3]; } obsd_t; typedef struct { obsd_t *data; } obs_t; ``` I have something like ``` obs_t obs; int x; ``` Now I want to assi...
You are mixing a pointer with a variable. Use.operator for struct variables (e.g. obs) and use->for pointers (e.g. for data) i.e. x = obs.data->time or you can also use like this as suggested byYu Hao x = obs.(*data).time
My code only takes 5 values as input.? What am i doing wrong? ``` #include<stdio.h> #include<stdlib.h> int main() { char arr[3][3]; int i,j,n; for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%c",&arr[i][j]); } } return 0; } ``` How should i correct it?
Change ``` scanf("%c",&arr[i][j]); ``` to ``` scanf(" %c",&arr[i][j]);. ``` Notice the space given before specifier to consume\nleft in stdin buffer when you pressed enter. Each\nis working as input taking your space from input space.
I have the following code to open a buffer in the memory and write some data to it: ``` int main() { char buf[1000] = {0}; FILE * os = fmemopen(buf, 1000, "w"); fprintf(os, "%d", 100); fclose(os); printf("%d\n", buf); return 0; } ``` The output is some random numbers such as :895734416or a ...
printf("%d\n", buf);output the address ofbufinstead of the return value.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question I would like to know which libray offers the possiblity of manipulate object over an imag...
Use GTK3 withcairo(i.e.cairographics). e.g.GtkDrawingArea. Seezetcodetutorials onGTK&cairo. NB:GooCanvasis probably obsolete with GTK3 GTK3 will be useful for mouse related things, and Cairo for drawing. You could consider alsolibSDLinstead.
I want to scan a 2-D matrix forintegersrow wise i.e. one row at a time in 'C' For example:if matrix is: ``` 1 2 3 4 5 6 7 8 9 ``` then there should be only 3 time scanf be used and first time input be ``` 1 2 3 ``` at once and so on for other row. for character we can use something like: ``` char mat[10][10...
If you don't know the number of columns or lines, then you can do something like this: Read each line one by one into a string. Then split the current line on the space character (using e.g.strtok), and use e.g.strtolto parse the string into an integer. Like this pseudo-code ``` while (fgets(line)) { number_str...
this is a part of my little 'C' program... ``` printf("Time to sleep for the end of process: %d sec\n", getpid() % 10); ``` I would like to come down the seconds, without the line on the terminal changes. Like an animation. How can i do this in 'C'? Thanks everyone!
Replace your\nwith a\r, and as long as your numbers are all the same length (number of digits), I believe that should work.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Closed9 years ago.This question appears to be off-topic becauseit lacks sufficient information to diagnose the problem.Describe your problem in more detail orinclude a minimal examplein the question itself.Questions aski...
If the PID is stored in a variable calledx, then the last digit can be found asx % 10.
I have anUINT16unsigned integer of say ``` 4455, 312, 560 or 70. ``` How to use printf to insert a decimal point before the last two digits so the example numbers appear as ``` 44.55, 3.12, 5.60 or 0.70 ``` If there is no printf solution, is there another solution for this? I do not wish to use floating point.
%.2dcould add the extra padding zeros ``` printf("%d.%.2d", n / 100, n % 100); ``` For example, ifnis560, the output is:5.60 EDIT: I didn't notice it'sUINT16at first, according to @Eric Postpischil's comment, it's better to use: ``` printf("%d.%.2d", (int) (x/100), (int) (x%100)); ```
I tried finding it but could not find the solution to this. I just want to know what does this mean in terms of return value. Does it mean that return value can be any of the 5 values present. Or the return value is all of these 5 numbers ``` static int is_navmsg(int msg) { return msg==1019||msg==1020|...
It will return1if the value ofmsgis1019or1020or1044and so on. Otherwise0.
I writing Dbus service implementing some protocol. My service sends to client message with unexpected data (library i used has some bugs, that i want to overwrite). How to inspect, trace client calls? I want to determine what client wants and locate buggy method. Or how to trace all calls in service? I has much oflo...
dbus-monitor "sender=org.freedesktop.Telepathy.Connection.******"
How can I pass achar*array as a parameter, without creating one and initializing it? This code works (creating an initializing one): ``` char *messages[] = {"Zero", "One", "Two", "Three"}; printf("%s", messages[1]); ``` But it wont work if you pass it like so: ``` #include <stdio.h> void printElement1(char *messa...
You're just missing the type for your compound literal. Change that line to: ``` printElement1((char *[]){"Zero", "One", "Two", "Three"}); ``` and it will work fine.
I wrote a script for downloading a hdf5 file using libcurl, but I cannot find way to open it in c, I don't want to store it in disk and H5Fopen it. Is there a way to do the H5Fopen work on the downloaded memory buffer? Thanks:)
It is called File Image and you need recent HDF5 to do that: http://www.hdfgroup.org/HDF5/doc/Advanced/FileImageOperations/HDF5FileImageOperations.pdf
externis a storage class in C. How exactly does it work? The output of the code given below is 20. How is this the output? ``` #include <stdio.h> int main() { extern int a; printf("%d", a); return 0; } int a=20; ```
It means three things: The variable hasexternal linkage, and is accessible from anywhere in the program;It hasstatic storage duration, so its lifetime is that of the program (more or less); andThe declaration is just a declaration, not a definition. The variable must also be defined somewhere (either without theexter...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do...
Linux alternative toconio.his ncurses library. To install it search for packages:libncurses,libncurses-dev.