question
stringlengths
25
894
answer
stringlengths
4
863
This question already has answers here:Why do programs sometimes "skip over" printfs?(4 answers)Closed7 years ago. This C program printsDone, then enters an infinite loop. ``` #include <stdio.h> int main(int argc, char const *argv[]) { printf("Done"); while (1) {} return 0; } ``` But when I run it, thi...
It needs to flush the buffer. Usually console output doesn't flush until it receives a'\n'. There's a little-used function for this,fflush(). ``` #include <stdio.h> int main(int argc, char const *argv[]) { printf("Done"); fflush(stdout); while (1) {} return 0; } ``` That should print for you.
Can you find the length of a string by doing subtraction on an array of pointers to strings? For example if I have the code below ``` char *pStrings[4] = { "First string", "Hello", "Afternoon", "Ab" }; int firstStrLen = pStrings[1] - pStrings[0] - 1; //Will I get the length of the first string by doi...
No, this is undefined behavior. You are allowed to subtract pointers only when they are pointing to memory from the same contiguous memory block. In your examplepStrings[1]andpStrings[0]are not pointing to a contiguous block of memory, so the result ofpStrings[1] - pStrings[0]is undefined. 6.5.6.9: When two pointers...
main.c ``` List L; Initialize(&L); printf("%d\n", Size(&L)); ``` list.c ``` void Initialize (List *L) { L = malloc(sizeof(List)); if (L == NULL) { perror("Unable to create memory for list. Exiting."); exit(1); } L->size = 0; } int Size (List *L) { return L->size; } ``` What I w...
ThisInitializefunction ignore the argument, allocate a buffer, write something to it, throw it away and cause memory leak. Try this simple function using the same way asSize: ``` void Initialize (List *L) { L->size = 0; } ```
This question already has answers here:Why do programs sometimes "skip over" printfs?(4 answers)Closed7 years ago. This C program printsDone, then enters an infinite loop. ``` #include <stdio.h> int main(int argc, char const *argv[]) { printf("Done"); while (1) {} return 0; } ``` But when I run it, thi...
It needs to flush the buffer. Usually console output doesn't flush until it receives a'\n'. There's a little-used function for this,fflush(). ``` #include <stdio.h> int main(int argc, char const *argv[]) { printf("Done"); fflush(stdout); while (1) {} return 0; } ``` That should print for you.
Can you find the length of a string by doing subtraction on an array of pointers to strings? For example if I have the code below ``` char *pStrings[4] = { "First string", "Hello", "Afternoon", "Ab" }; int firstStrLen = pStrings[1] - pStrings[0] - 1; //Will I get the length of the first string by doi...
No, this is undefined behavior. You are allowed to subtract pointers only when they are pointing to memory from the same contiguous memory block. In your examplepStrings[1]andpStrings[0]are not pointing to a contiguous block of memory, so the result ofpStrings[1] - pStrings[0]is undefined. 6.5.6.9: When two pointers...
This question already has answers here:Why do programs sometimes "skip over" printfs?(4 answers)Closed7 years ago. This C program printsDone, then enters an infinite loop. ``` #include <stdio.h> int main(int argc, char const *argv[]) { printf("Done"); while (1) {} return 0; } ``` But when I run it, thi...
It needs to flush the buffer. Usually console output doesn't flush until it receives a'\n'. There's a little-used function for this,fflush(). ``` #include <stdio.h> int main(int argc, char const *argv[]) { printf("Done"); fflush(stdout); while (1) {} return 0; } ``` That should print for you.
Can you find the length of a string by doing subtraction on an array of pointers to strings? For example if I have the code below ``` char *pStrings[4] = { "First string", "Hello", "Afternoon", "Ab" }; int firstStrLen = pStrings[1] - pStrings[0] - 1; //Will I get the length of the first string by doi...
No, this is undefined behavior. You are allowed to subtract pointers only when they are pointing to memory from the same contiguous memory block. In your examplepStrings[1]andpStrings[0]are not pointing to a contiguous block of memory, so the result ofpStrings[1] - pStrings[0]is undefined. 6.5.6.9: When two pointers...
I'm a newbie to the go world, so maybe this is obvious. I have a Go function which I'm exposing to C with thego build -buildmode=c-sharedand corresponding//export funcNamecomment. (You can see it here:https://github.com/udl/bmatch/blob/master/ext/levenshtein.go#L42) My conversion currently works like this: ``` func...
You don't need to do anything special. UTF-8 is Go's "native" character encoding, so you can use the functions from theutf8package you mentioned, e.g.utf8.RuneCountInStringto get the number of Unicode runes in a string. Keep in mind thatlen(s)will still return the number of bytes in the string. Seethis post in the of...
I am working with Mathworks Polyspace for my CODE analysis. I have a hardware register where I write a KEY+MODE and read the register to check the value in the register is equal to MODE. The problem is, Polyspace considers this as 'always fail' as I am writing and reading different values in consecutive steps. Is th...
Since KEY+MODE is different from MODE, Polyspace will logically consider the testyour_hardware_register == MODEas failed (fortunatly). It seems that KEY and MODE are bit flags for your register. So I see two options: Use the bitwise AND operator to test the register :if (your_hardware_register & MODE)make the regist...
I'm chinese.I'm reading syslog.h,and i find a term "0-big number" which i can't understand.I can understand the hole paragraph meaning,but i'm still curious about the term "0-big number",could anybody explain the term? ``` /* * priorities/facilities are encoded into a single 32-bit quantity, where the * bottom 3 bits...
The author just decided to call 28 set bits (2^28 - 1) abig numberinstead of writing it out. So it's not a term but meanszerotobig number.
So My code runs differently when I have: *ptr++; and ++*ptr I know the part about the ++ being in front you add first and when its in the back you add at the end. But this pointer increment is at the end of a method. To clarify I'm just trying to move the pointer to the next character. This is a character type pointe...
*ptr++is processed as*(ptr++); it incrementsptrbut returns the original value, which is then dereferenced. ++*ptris processed as++(*ptr)which dereferences the pointer, then increments thevalue it points to(notthe pointer). To preincrement the pointer, then get the value at the incremented location, you want*++ptr, w...
I'm curious why the following code returns negative numbers even though every single variable and fuction initialization in this program is an unsigned int. I thought they always were supposed to be positive?. ``` #include <stdio.h> unsigned int main () { unsigned int ch = 0; unsigned int asteriskValue = 0; while(ch...
I think your results is really a positive value, but printing it with a "%d" flag, tells printf to interpret it as a signed value, as if you were casting on the fly the type: (signed)asteriskValue Try printing it with a "%u" formatting instead of "%d".
So My code runs differently when I have: *ptr++; and ++*ptr I know the part about the ++ being in front you add first and when its in the back you add at the end. But this pointer increment is at the end of a method. To clarify I'm just trying to move the pointer to the next character. This is a character type pointe...
*ptr++is processed as*(ptr++); it incrementsptrbut returns the original value, which is then dereferenced. ++*ptris processed as++(*ptr)which dereferences the pointer, then increments thevalue it points to(notthe pointer). To preincrement the pointer, then get the value at the incremented location, you want*++ptr, w...
I'm curious why the following code returns negative numbers even though every single variable and fuction initialization in this program is an unsigned int. I thought they always were supposed to be positive?. ``` #include <stdio.h> unsigned int main () { unsigned int ch = 0; unsigned int asteriskValue = 0; while(ch...
I think your results is really a positive value, but printing it with a "%d" flag, tells printf to interpret it as a signed value, as if you were casting on the fly the type: (signed)asteriskValue Try printing it with a "%u" formatting instead of "%d".
I want a code in one line only. I haven't found something usefull for the moment. Exemple, I have: ``` #include <unistd.h> int function(){write(1,"abcdefghijkmnopqrstuvwxyz\n",27);return(0);} ``` And I'm searching something like: ``` #include <unistd.h>;int function(){write(1,"abcdefghijkmnopqrstuvwxyz\n",27);r...
You can't. The#includepreprocessing directive must be followed by a newline. It's part of the syntax (6.10.1 in the C standardhttp://open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf). It's generally okay to omit headers from your one-liner, although even better to make the code compile without headers. If someone is...
I have an function address stored in anunsigned int, and a function pointer. Now i want thatfunction_pointerwill contain the value offunction_address ``` unsigned int function_address = 0xdeadbeef; void(*function_pointer)(void) = function_address; // not valid ``` how to do that in C ?
Perform an explicit cast. ``` void(*function_pointer)(void) = (void (*)(void))function_address; ```
I have an Xcode project for iOS in Xcode 7.0 that contains Objective-C, C++, and C code. Xcode tries to compile the C++ header files with the extension .h (not .hpp) as C header files which generates errors. How do I fix this? There should be a setting for which files should be compiled as which language.
Individually header files doesn't compiled. Compiled source files where they included. If you include them in .c they will be compiled like C, if in .m - like Objective-c, if in .cpp - like C++, if in .mm - like Objective-C++. It doesn't matter how you name them .h or .hpp. If you have some portion of C++ code in h-...
Is there any doc i can read about this kind of function? ``` // return the capital of char c char a(char c){ return c >= 'a' && c<='z' ? c +'A' - 'a':c; } ```
Read up on the ternary operator. :) And then it will be clear the code is doing: ``` if (c >= 'a' && c<='z') { return(c +'A' - 'a'); } else { return c; } ``` So basically it is capitalizing the Latin alphabet in ASCII.
This question already has answers here:Type of #define variables(7 answers)Closed7 years ago. When I define a numerical constant with#define(e.g.#define pi 3.141593) is it anint,float,doubleor what?
Neither. It is a lexicographical replacement, that is, it will replacepiwith3.141593wherever it shows up.
I must start out by saying that I am extremely new to C! I have been through theQuestions that may already have your answerand tried the suggestions however those do not solve the error message that I am receiving. I am receiving an error message with the below code: ``` int autoop_check(aClient *cptr, aClient *spt...
You are missing braces for the body of theifstatement. ``` if (IsOper(cptr)) { char *parv[] = { "+o", sptr->name, NULL }; (void)do_mode(chptr, sptr, sptr, 2, parv, 0, 0); } ```
How can I check if my code is getting recompiled by GCC or not. For example if I type: ``` g++ -c test.cpp ``` is there a way that GCC tells you that the code is being recompiled in to a new object file because test.cpp has changed. I know I can check the object file's timestamp in terminal but is there an option in...
gcc will always build if you tell it to build. Like robert said in the comments it is up to your build system to figure out if the file needs updating. In make you could just print an info if your target is being hit or you could do a checksum (md5sum or so) of your binary the beginning and end of your build.
I want to store strings in a 2D array using pointers but I'm confused with how to do it. The examples I've seen use only arrays of ints or use the brackets[] to allocate a fixed size of memory. So I'm trying to initialize my 2D array of strings and this is what I have: ``` char ** stringArr = (char**)malloc(/*I don't...
Do this, because you're allocating some number of pointers: ``` malloc(rows * sizeof(char*)) ```
I have an function address stored in anunsigned int, and a function pointer. Now i want thatfunction_pointerwill contain the value offunction_address ``` unsigned int function_address = 0xdeadbeef; void(*function_pointer)(void) = function_address; // not valid ``` how to do that in C ?
Perform an explicit cast. ``` void(*function_pointer)(void) = (void (*)(void))function_address; ```
I have an Xcode project for iOS in Xcode 7.0 that contains Objective-C, C++, and C code. Xcode tries to compile the C++ header files with the extension .h (not .hpp) as C header files which generates errors. How do I fix this? There should be a setting for which files should be compiled as which language.
Individually header files doesn't compiled. Compiled source files where they included. If you include them in .c they will be compiled like C, if in .m - like Objective-c, if in .cpp - like C++, if in .mm - like Objective-C++. It doesn't matter how you name them .h or .hpp. If you have some portion of C++ code in h-...
Is there any doc i can read about this kind of function? ``` // return the capital of char c char a(char c){ return c >= 'a' && c<='z' ? c +'A' - 'a':c; } ```
Read up on the ternary operator. :) And then it will be clear the code is doing: ``` if (c >= 'a' && c<='z') { return(c +'A' - 'a'); } else { return c; } ``` So basically it is capitalizing the Latin alphabet in ASCII.
I have this code: ``` #include <stdio.h> #include <string.h> int main() { char s1[50], s2[50]; printf("write s1:\n"); fgets(s1, sizeof(s1), stdin); printf("s2:\n"); fgets(s2, sizeof(s2), stdin); printf("The concatenation of the two strings: %s\n", strcat(s1, s2)); if( strcmp(s2, s1) < 0 ) { pr...
You are doing ``` strcat(s1, s2) ``` before comparing. Which will modify strings1so strings will not be equal
I compiled and executed this code and the computer hangs. I sent the file(a.out not a.c) to a friend and he executed it and the result was same. How do I intelligently check if there is such fork() in infinite loops? What should be the preventive measures against this attack? ``` #include<stdio.h> int main(){ wh...
Just use theulimitto limit the maximum number of processes. Additionally you can configure the limitations by editting the/etc/security/limits.conffile. Take a look to the following link which provides more information about how to prevent from this attack: http://www.cyberciti.biz/tips/linux-limiting-user-process.ht...
I am trying to get the maximum virtual memory of the current process in Linux. And I am using getrlimit() ``` #include <stdio.h> #include <sys/time.h> #include <sys/resource.h> struct rlimit rlim; getrlimit(RLIMIT_AS,&rlim); printf("Soft limit %ld",rlim.rlim_cur); printf("Hard limit %ld",rlim.rlim_max); ``` I get -...
The valueRLIM_INFINITYdenotes no limit on a resource (both in the structure returned bygetrlimit()and in the structure passed tosetrlimit()). These are the default values for a process. Check the value of this constant.
Do file descriptor are with respect to the processes or with respect to the operating system? What I basically want to know is if in a c program I open a file and that file gets assigned a file descriptor value lets say, 103, so when I open a file with file descriptor 103 in some other c program would I be referring t...
Each Process will be having its own file descriptor table. Its processor specific, if you change thefdit will be valid only to that process it wont affect the other processes in the system. once process is terminatedfdwill be discarded. What if I fork a new process from the process I opened that file? Current File d...
I'm just started learning C programming. So I have problem with change temperature via Functions. Please check this program and where did I do mistake? Thank you!!! ``` #include<stdio.h> double f_to_c(double f); double get_integer(void); int main(void) { double a; a = get_integer(); printf("he degree in...
In your case, ``` double f_to_c(double f) { int f, c; c = 5.0 / 0.9*(f - 32.0); return c; } ``` int fis shadowing thedouble f. Use some other name for the variable(s). Essentially, you're trying to make use of an uninitialized automatic local variable which invokesundefined behavior
Just curious, why below code is not equivalent to forever loop? Instead application crashes. ``` unsigned short i; for (i = 1; i >= 0; i++) { printf("%d\n", i); } ```
The problem is solved. Antivirus Karspersky was analysing this exe file for nearly 20 seconds it looks. If I disable antivirus, it runs immediately. Thanks for all your inputs.
Just curious, why below code is not equivalent to forever loop? Instead application crashes. ``` unsigned short i; for (i = 1; i >= 0; i++) { printf("%d\n", i); } ```
The problem is solved. Antivirus Karspersky was analysing this exe file for nearly 20 seconds it looks. If I disable antivirus, it runs immediately. Thanks for all your inputs.
I'm trying to call a function in main for the different programs (Q2-3 and Q4) but I'm getting an error during compiling. in my main I have prog1 (); [it says "previous implicit declaration of prog1 was here"] then there is a function of the same name at the very end void prog1() { [it says "conflicting types for pro...
Because you didn't give a prototype forprog1(). If it has for example the following signature ``` char *prog1(void); ``` and you don't give a prototype but call it frommain(), then you define it later with the mentioned signature, the implicitly declared prototype which isint prog1()conflicts with the definition. ...
EXPLANATION: simply trying to convert a a char to hexadecimal but i keep getting this error and I'm not sure how to get around this PROBLEM: ``` warning: passing argument 1 of ‘strtol’ makes pointer from integer without a cast[cs214111@cs lab3]$ vi lab3.c ``` CODE: ``` void print_group(char array[]) { int num...
You are passingcharwherechar *is expected, maybe ``` strcpy(ch, &array[3]); ``` But from your code it would seem like this, is what you actually need ``` num = strtol(&array[3], 0, 16); ``` ifstrcpy()works in this case, then this will work.
Here is my code: ``` #include <stdio.h> #include <math.h> int main(void) { double x, y, z; double numerator; double denominator; printf("This program will solve (x^2+y^2)/(x/y)^3\n"); printf("Enter the value for x:\n"); scanf("%lf", x); printf("Enter the value for y:\n"); scanf("%lf",...
There's no loop in your function, so I think it's your calls toscanf()that are causing the error: You need to pass reference toscanf(), i.e. usescanf("%lf",&x)instead ofscanf("%lf",x). BTW, according to your fonction definition, you should usepow(x,2)instead ofsqrt(x)which returns the square root.
I am developing an R package with low-level C code. Suppose I have following function in myCcode. ``` SEXP myFun(SEXP obj) ``` I need to know whether the R objectobjis a regularmatrixorbig.matrix(use R packagebigmemory) so that I can call different functions for computation. Is this possible? How could I know the c...
You can use theinheritsfunction: ``` #include <R.h> #include <Rinternals.h> SEXP myFun(SEXP obj) { if (inherits(obj, "big.memory")) { // do stuff } } ```
My code is as follows to open a xterm terminal and run the ./paramax executable ``` #include <unistd.h> #include <sys/ipc.h> int main(int argc, char* argv[]) { execl("/usr/bin/xterm", "/usr/bin/xterm", "-hold", "./paramax", (void*)NULL); return 0; } ``` Now the problem is for ./paramax I need to give a commandline ...
Runxterm -e ./paramax arg and more args, either directly or through an exec call.
I have a Linux kernel module which calculates network packet statistics among several CPUs (in kernel address space). Periodically I clear the corresponding memory chunk and strongly need this action to take immediate effect for all CPUs, otherwise it will distort the subsequent statistics values. My target CPU is a P...
After some reflection I realised that the problem here is not really linked to data cache flushing. Actually I try to avoid a banal race condition (the first cpu clears value while the second increments it). In my case it's too expensive to protect data by mutex, so it's worth using atomic flag to notify the owning CP...
I have a loop in a C language code: ``` i = 0; while(!isdigit(password[i]) && password[i++] != '\0'); ``` password is declared globally like this: ``` char password[33]; ``` iis an integer. I want to check if the password a user is entering has at least one number or not. If I replaced '\0' with any other chara...
The indexiis not incremented once you find a digit: ``` !isdigit(password[i]) && password[i++] != '\0' ``` ifisdigit(password[i])returnstruethe right side of&&operator is not evaluated.
Could someone help walk me through what some lines in this MIPs code are doing? The C code isB[8] = A[i - j]with i = $s3, j = $s4, &A[] = $s6, and &B[] = $s7 The MIPs code is as follows... ``` sub $t0, $s3, $s4 # i - j sll $t0, $t0, 2 #Gets the offset of 8 for B[] add $t0, $s6, $t0 #Goes to the offset in B[] ? lw ...
``` sll $t0, $t0, 2 // This multiplies (i-j) * 4, not 8. Because the indexes are 4-byte ints add $t0, $s6, $t0 // $t0 = A + (i-j)*4. So $t0 = &A[i-j] lw $t1, 0($t0) // $t1 = A[i-j] sw $t1, 32($s7) // B[32/4] = $t1 ``` 32($s7) means $s7 + 32. The reason you add 32 because you are accessing the 8th element of a...
I'm trying to code a function that checks a through achar* a[], and often end up using something like ``` if(a[i] == 'x'){ i++; //... } ``` Now I would really like to change this toa[i++]instead, but it doesn't seem to work. Question: Am I doing something wrong here, or is there a clean alternative to avoi...
if (a[i++] == 'x')by itself is fine in C. It is, however, semantically different: Your original code only incrementsiif the condition is true, whereasif (a[i++] == 'x')always incrementsi.
I had written below code in C. I expected error message since array size cannot be allocated dynamically. But the code compiles. But the result size of myArray1 is absurd. I am not sure why it compiles. I am using codeblock and minGW. ``` int a; printf("Enter the value for a\n"); scanf("%d",&a); int myArr...
C99 standard supports variable sized arrays on the stack. Here is thegcc docson it: Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The...
Generally say I have some functionsstep1step2... and they are called successively: ``` int main() { ... step1(); // something wrong detected and need to break out of the whole program step2(); step3(); ... } ``` How can I break out fromstep1and skip all the rest of code to terminatemain()function? Curren...
Use ``` exit(1); ``` The number indicates the exit status. 0 is no failure, everything larger then 0 indicates an error.
I'm trying to code a function that checks a through achar* a[], and often end up using something like ``` if(a[i] == 'x'){ i++; //... } ``` Now I would really like to change this toa[i++]instead, but it doesn't seem to work. Question: Am I doing something wrong here, or is there a clean alternative to avoi...
if (a[i++] == 'x')by itself is fine in C. It is, however, semantically different: Your original code only incrementsiif the condition is true, whereasif (a[i++] == 'x')always incrementsi.
I had written below code in C. I expected error message since array size cannot be allocated dynamically. But the code compiles. But the result size of myArray1 is absurd. I am not sure why it compiles. I am using codeblock and minGW. ``` int a; printf("Enter the value for a\n"); scanf("%d",&a); int myArr...
C99 standard supports variable sized arrays on the stack. Here is thegcc docson it: Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The...
Generally say I have some functionsstep1step2... and they are called successively: ``` int main() { ... step1(); // something wrong detected and need to break out of the whole program step2(); step3(); ... } ``` How can I break out fromstep1and skip all the rest of code to terminatemain()function? Curren...
Use ``` exit(1); ``` The number indicates the exit status. 0 is no failure, everything larger then 0 indicates an error.
In the gcc compiler we can provide a macro to be used by the preprocessor inCusing -D flag (example-gcc -DN=10 test.c) What is the flag that can be used to do the same in the clang compiler? When I give the same -D option to the clang compiler on Windows, it gives an error: "Directory not found."
Answer is the 2 comments from @cremno and @FUZxxl above. The error wasn't coming from the clang compiler although it said clang error. Rather it was coming from the Windows cmd which looks for a directory after the '=' sign.
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.Closed7 years ago.Improve this question When using C programming language, I have no idea how to put a user input to an array. I need to get integ...
This is a very helpful link Also look up this too for clarification on Console.Read & Console.ReadlineDifference between Console.Read() and Console.ReadLine()?
The title says it all. The app I'm debugging has several diagnostics that callDebugger(). I want it to just print the message and continue execution.
Wow, this is cleverly hidden. Select the project in the project navigator. Then menu: Product > Scheme > Edit Scheme... Choose "Run" in the left column, then select the "Diagnostics" header on the top right. At the bottom you'll see a checkbox for: "Legacy [ ] Stop on Debugger() and DebugStr()"
I wrote a C programm and saved it with a .c extension. Then I compiled with the gcc but after that I only see my .c file and an .exe file. The program runs perfectly. But where is the .o file that I learned in theory? Has it been overwritten to .exe and all done by the gcc in on step? (Preprocessing, compiling, assemb...
By default,gcccompiles and links in one step. To get a.ofile, you need to compile without linking. That's done with the-coption. Suppose you want to compile two files separately, then link them. You would do the following: ``` gcc -c file1.c # creates file1.o gcc -c file2.c # creates file2.o gcc -o myex...
Why does the following snippet cause random numbers to print to the screen withprintf, butputcharalways outputs 1? ``` #include <stdio.h> int main() { char c; printf("%d\n", c ); putchar(c); } ```
According to C99 standard, this isundefined behavior. Let's see why: Section 6.7.8.9 says that If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. This applies to your variablec, because it has automatic storage duration, and it is not initialized explicitly. ...
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.Closed7 years ago.Improve this question When using C programming language, I have no idea how to put a user input to an array. I need to get integ...
This is a very helpful link Also look up this too for clarification on Console.Read & Console.ReadlineDifference between Console.Read() and Console.ReadLine()?
The title says it all. The app I'm debugging has several diagnostics that callDebugger(). I want it to just print the message and continue execution.
Wow, this is cleverly hidden. Select the project in the project navigator. Then menu: Product > Scheme > Edit Scheme... Choose "Run" in the left column, then select the "Diagnostics" header on the top right. At the bottom you'll see a checkbox for: "Legacy [ ] Stop on Debugger() and DebugStr()"
I wrote a C programm and saved it with a .c extension. Then I compiled with the gcc but after that I only see my .c file and an .exe file. The program runs perfectly. But where is the .o file that I learned in theory? Has it been overwritten to .exe and all done by the gcc in on step? (Preprocessing, compiling, assemb...
By default,gcccompiles and links in one step. To get a.ofile, you need to compile without linking. That's done with the-coption. Suppose you want to compile two files separately, then link them. You would do the following: ``` gcc -c file1.c # creates file1.o gcc -c file2.c # creates file2.o gcc -o myex...
Why does the following snippet cause random numbers to print to the screen withprintf, butputcharalways outputs 1? ``` #include <stdio.h> int main() { char c; printf("%d\n", c ); putchar(c); } ```
According to C99 standard, this isundefined behavior. Let's see why: Section 6.7.8.9 says that If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. This applies to your variablec, because it has automatic storage duration, and it is not initialized explicitly. ...
Is it possible to build a c (not cpp or visual cpp) application with visual studio? I do not want to only build it via cmd line but have some kind of project/solution within visual studio. I've programmed in high-level languages like c#, java, python, etc etc but have no idea of c/cpp. I want to start learning c (aga...
Yes, you can do that with MSVC. FromMSDNsite: Give your files the.cextension, for examplemysource.c. The Visual C++ compiler automatically assumes that files with the.Cextension areCfiles and notC++files, and rejectsC++syntax and keywords (such aspublic,private, andclass).C++files use the.cppextension.See the/TC,/TPc...
The title says it all. The app I'm debugging has several diagnostics that callDebugger(). I want it to just print the message and continue execution.
Wow, this is cleverly hidden. Select the project in the project navigator. Then menu: Product > Scheme > Edit Scheme... Choose "Run" in the left column, then select the "Diagnostics" header on the top right. At the bottom you'll see a checkbox for: "Legacy [ ] Stop on Debugger() and DebugStr()"
I wrote a C programm and saved it with a .c extension. Then I compiled with the gcc but after that I only see my .c file and an .exe file. The program runs perfectly. But where is the .o file that I learned in theory? Has it been overwritten to .exe and all done by the gcc in on step? (Preprocessing, compiling, assemb...
By default,gcccompiles and links in one step. To get a.ofile, you need to compile without linking. That's done with the-coption. Suppose you want to compile two files separately, then link them. You would do the following: ``` gcc -c file1.c # creates file1.o gcc -c file2.c # creates file2.o gcc -o myex...
Why does the following snippet cause random numbers to print to the screen withprintf, butputcharalways outputs 1? ``` #include <stdio.h> int main() { char c; printf("%d\n", c ); putchar(c); } ```
According to C99 standard, this isundefined behavior. Let's see why: Section 6.7.8.9 says that If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. This applies to your variablec, because it has automatic storage duration, and it is not initialized explicitly. ...
Is it possible to build a c (not cpp or visual cpp) application with visual studio? I do not want to only build it via cmd line but have some kind of project/solution within visual studio. I've programmed in high-level languages like c#, java, python, etc etc but have no idea of c/cpp. I want to start learning c (aga...
Yes, you can do that with MSVC. FromMSDNsite: Give your files the.cextension, for examplemysource.c. The Visual C++ compiler automatically assumes that files with the.Cextension areCfiles and notC++files, and rejectsC++syntax and keywords (such aspublic,private, andclass).C++files use the.cppextension.See the/TC,/TPc...
What's wrong with this program. It compiles but is not giving correct output. ``` /* Program for Armstrong Number*/ #include<stdio.h> #include<math.h> void main() { int num,sum=0,temp,d; printf("\n========Program for Armstrong Number=========\n"); printf("Enter the number : "); ...
``` while(temp>10){ d=temp%10; sum+=pow(d,3); d/=10; // this should be temp/=10; } ``` This loop is infinite as you don't modifytemp.
I downloaded Eclipse Mars although I have been doing most of my work on Android Studio. The reason is I need another tool, which is not compatible with Android Studio. The procedures I followed instructed to create an executable C project. I then added hello world to it, but I can an error stating there is nothing to ...
Compiler is simply telling you that your code was already compiled and there are no changes in your code, then it does not compile. Is a builtin feature of compilers, if there are no changes in source code file, compilers do not waste time. Clean Projectbefore toBuild Projector modify Hello.c and Build your project.
I'm expanding circuit emulation engine for Win32 and want to add arm core support and integrate with systemC.I need some library that allows me to load binary file and execute it step by step. It shouldn't use any kernel drivers or hypervisor.The execution speed doesn't matter as it mostly will run step by step.back i...
You should take a look at :https://hiventive.com We're developing an open source solution that allow you to connect QEMU with SystemC exporting QEMU CPUs as a library with a TLM-2.0 like interface. A GDB server is also available. There is a Raspberry Pi demo platform available through our beta.
In it's main page it says: fchdir() is identical to chdir(); the only difference is that the directory is given as an open file descriptor. And the prototype is given as following: int chdir(const char *path);int fchdir(int fd); My question is how can a directory be passed as a file descriptor? Do directories al...
Do directories also have a corresponding descriptor like files? Yes. The Unix philosophy(and Linux) is to treat everything as a stream of bytes. So yes, you can doopen(2)on a directory and get its file descriptor. Not only directories but sockets, pipes and devices can also be opened usingopen(2)system call and do op...
After I look around, I haven't find a built in function forUUIDcreation withinOSX kernel space. (which is limited toKernel.framework) Are there any alternatives I could use? Or should I just use time hash (MD5/SHA1)?
These should help: ``` void uuid_generate(uuid_t out); void uuid_generate_random(uuid_t out); void uuid_generate_time(uuid_t out); ``` They're declared in<uuid/uuid.h>, and linkage is defined in Libkern.exports, i.e. your kext'sOSBundleLibrariesproperty must listcom.apple.kpi.libkern- which it probably already does....
In a (C++) class I took recently the teacher mentioned that using the->operator was a tiny bit slower than using dot notation and dereferencing your pointer manually (e.g.(*ptr)). Is this true, and, if so, why?Does this apply to C as well?
The->operator is neither slower or faster than.operator. The fact is thatdereferencingsomething is slower than just access to a memory location, because there is one more indirection. And this is a fact of life, either in C and C++ and any other language. In C++, you have alsoreferences, so you can dereference someth...
How can we do transaction signing in mozilla firefox by loading PKCS#11 library to database. after some research i found about capicom library. but the thing is this library does not support with windows7 and higher versions.
you cannot use c code but you can do the same by java applets which are to be signed. Please referhttp://www.nakov.com/books/signatures/Java-for-Digitally-Signing-Documents-in-Web-book-Nakov.html
Can you please help to print the below pattern? ``` 12345 15 2345 14 345 12 45 9 5 5 ``` I have tried with this code? code : ``` for(i=1;i<=5;i++) { for(j=1;j<=i;j++) { printf(" "); } for(j=i;j<=5;j++) { printf(...
Well the problem is clear: 29 = 15 + 14. This means you are forgetting to clear sum when you begin a new line. ``` for(i=1;i<=5;i++) { sum = 0; // reset sum when we begin a new line ```
I am writing a C program in Linux and useforkto create a child process. When I run my program using./test 1 > out.txtboth the parent process and the child processes send information tostdout. I would like the fileout.txtto only contain output from the parent process and discard all output from the child process. How...
I would redirect the parent's stdout to the file, then when you fork, reopen the stdout handle of the child to go to something else (like /dev/null if you just want to ditch it, or you could open the terminal again if you want it to go back to stdout). Thedup2system call can do that.opena new one,closethe old one, th...
If I set the seed to 0 in C, I will get this sequence after callingrand()three times: ``` 38, 7719, 21238, ..., ``` If I set seed to 1 (srand(1)) I will get this other sequence: ``` 41, 18467, 6334, ..., ``` I know that is's very improbable, but will the sequence ofsrand(1)be present in the sequence ofsrand(0)at s...
Though it is not defined by standard - The answer to your question is yes, it depends upon the algorithm being used, which is usually Linear Congruential Generators (LCG). LCG is considered to be high on cross-autocorrelation. Looking at howrandis implemented in your platform will let you characterize it better. Here...
In C programming for Linux, I know thewait()function is used to wait for the child process to terminate, but are there some ways (or functions) for child processes to wait for parent process to terminate?
Linux has an extension (as in, non-POSIX functions) for this. Look upprctl("process-related control"). Withprctl, you can arrange for the child to get a signal when the parent dies. Look for thePR_SET_PDEATHSIGoperation code used withprctl. For instance, if you set it to theSIGKILLsignal, it effectively gives us a w...
What happens in the follwing code, does program executes 'return 1' or exits before? ``` int cmd_quit(tok_t arg[]) { printf("Bye\n"); exit(0); return 1; } ```
exit()ends the program, no matter what. So: no. In practice, a C runtime will always do something similar of ``` exit(main(argc, argv)); ``` to execute your program. (meaning:ifmain()returns,exit()will be called automatically with its return value)
Im creating a simple program in C that user insert a number, for example 5 and the program sums until 5, 0+1+2+3+4. Im using this formula ``` int sum_naturals(int n){ return (n-1)*n/2; } ``` But now i want a formula that can sum from 2 different numbers, like user inserts number 5 and 9 and the program will do 5...
You can reuse your function ``` int sum(int a, int b) { return sum_naturals(b) - sum_naturals(a-1) } ``` Of course you have to add some validation.
I am using C API to create and drop tables from the oracle database. The snippet of code is ``` OCIStmt *stmt; rc = OCIHandleAlloc(ora_env, (dvoid **)&stmt, OCI_HTYPE_STMT, 0, 0); char *query = "DROP TABLE idmap_id;"; rc = OCIStmtPrepare(stmt, errhp, (OraText*)query, strlen(query), OCI_NTV_SYNTAX, OCI_DEFAULT); rc =...
Remove the semi-colon. (I guess Oracle expects another SQL statement after it.)
I need to use scanf to read a text file input into stdin. I want to read the text file line by line and then assign each values in the line to their values. This is the text file38 5 35 3099 48 222 16 4 1 Ronaldo 2 33 2572 22 97 7 6 0 Neymar 1 38 3375 43 191 18 4 0 Messi 13 37 2472 22 80 1 6 0 Griezmann The first li...
You can usefscanfto read from the text file (as you have fixed format of data) - ``` char name[100]; int a,b,c,d,e,f,g,h; // sorry for such variable names while(fscanf(fp,"%d %d %d %d %d %d %d %d %99s",&a,&b,&c,&d,&e,&f,&g,&h,name)==9) // fp be file pointer ```
How do I get1.371429as01.37. Is it not%2.02f? I need to have a leading zero and also round it to two decimal places.
Try this: ``` #include<stdio.h> int main() { double a = 1.2345666; printf("%05.2lf\n", a); return 0; } ``` Here,05says "print 5 columns with leading zeros"..2says "print decimal digits untill 2 columns". 2 decimal digits + 1.+ 2 integer part => total 5 columns you have to print.
I'm trying to build my project and create an executable file in Eclipse using the Microsoft Visual C compiler. I get the following output in the Console: ``` 12:02:42 **** Incremental Build of configuration Release for project ProjectName **** make all Building target: ProjectName.exe Invoking: Linker (link) link /n...
Switched to just using Visual Studio. Worked straight away.
In C programming for Linux, I know thewait()function is used to wait for the child process to terminate, but are there some ways (or functions) for child processes to wait for parent process to terminate?
Linux has an extension (as in, non-POSIX functions) for this. Look upprctl("process-related control"). Withprctl, you can arrange for the child to get a signal when the parent dies. Look for thePR_SET_PDEATHSIGoperation code used withprctl. For instance, if you set it to theSIGKILLsignal, it effectively gives us a w...
What happens in the follwing code, does program executes 'return 1' or exits before? ``` int cmd_quit(tok_t arg[]) { printf("Bye\n"); exit(0); return 1; } ```
exit()ends the program, no matter what. So: no. In practice, a C runtime will always do something similar of ``` exit(main(argc, argv)); ``` to execute your program. (meaning:ifmain()returns,exit()will be called automatically with its return value)
Im creating a simple program in C that user insert a number, for example 5 and the program sums until 5, 0+1+2+3+4. Im using this formula ``` int sum_naturals(int n){ return (n-1)*n/2; } ``` But now i want a formula that can sum from 2 different numbers, like user inserts number 5 and 9 and the program will do 5...
You can reuse your function ``` int sum(int a, int b) { return sum_naturals(b) - sum_naturals(a-1) } ``` Of course you have to add some validation.
I am using C API to create and drop tables from the oracle database. The snippet of code is ``` OCIStmt *stmt; rc = OCIHandleAlloc(ora_env, (dvoid **)&stmt, OCI_HTYPE_STMT, 0, 0); char *query = "DROP TABLE idmap_id;"; rc = OCIStmtPrepare(stmt, errhp, (OraText*)query, strlen(query), OCI_NTV_SYNTAX, OCI_DEFAULT); rc =...
Remove the semi-colon. (I guess Oracle expects another SQL statement after it.)
I need to use scanf to read a text file input into stdin. I want to read the text file line by line and then assign each values in the line to their values. This is the text file38 5 35 3099 48 222 16 4 1 Ronaldo 2 33 2572 22 97 7 6 0 Neymar 1 38 3375 43 191 18 4 0 Messi 13 37 2472 22 80 1 6 0 Griezmann The first li...
You can usefscanfto read from the text file (as you have fixed format of data) - ``` char name[100]; int a,b,c,d,e,f,g,h; // sorry for such variable names while(fscanf(fp,"%d %d %d %d %d %d %d %d %99s",&a,&b,&c,&d,&e,&f,&g,&h,name)==9) // fp be file pointer ```
How do I get1.371429as01.37. Is it not%2.02f? I need to have a leading zero and also round it to two decimal places.
Try this: ``` #include<stdio.h> int main() { double a = 1.2345666; printf("%05.2lf\n", a); return 0; } ``` Here,05says "print 5 columns with leading zeros"..2says "print decimal digits untill 2 columns". 2 decimal digits + 1.+ 2 integer part => total 5 columns you have to print.
I'm trying to build my project and create an executable file in Eclipse using the Microsoft Visual C compiler. I get the following output in the Console: ``` 12:02:42 **** Incremental Build of configuration Release for project ProjectName **** make all Building target: ProjectName.exe Invoking: Linker (link) link /n...
Switched to just using Visual Studio. Worked straight away.
I recently came across the 'cmocka' mocking library for C. I was able to mock a single function and test the caller function successfully. Now i need it to use it for a project that i am working on, where it is required to mock a large number of functions. How to pass all the functions that I want to mock to the 'wrap...
Invoke the compiler like this: gcc -g -Wl,--wrap=something,--wrap=somethingElse code_new.c headers.c -l cmocka
So I've read a lot of similar posts but I can't nail down what my issue is here. ``` { FILE * fp; fp = fopen("integer_store.txt", "r"); int total; int i; clock_t start, end; double time; start = clock(); fscanf(fp, "%d", &i); while(!feof(fp)) { fscanf(fp, "%d", &i); ...
Please initialize the variabletotallikeint total = 0;first. Moreover, you should check iffopensucceeded (fpis notNULL).
I am new to C and programming. I am trying to print an array separated by comma. But don't wish to print the last comma element. Here is my code so far ``` void p_array(const int array[], const int s) { for(int i = 0; i < s; i++) { printf("%i, ",array[i]); } } ``` I am getting the array printed as ``` 1, 2,...
``` for(int i = 0; i < s; i++) { if(i) printf(", "); printf("%i",array[i]); } ```
I'm given a char* arguments. Which is basically a input stream that consists of "hex-address new_val" and I need to read both values as int*. I'm using sscanf() and reading hex-address just fine, but I can't figure out the way to advance to read new_val.No matter what I tried - I get segfault. Here is what I have so f...
int addr, val; // not int* sscanf(arguments, "%x %x",&addr, &val); printf("adr = %x || val = %x\n", addr, val);
The purpose of this function is to be utilized for qsort function in the C library. The function below works only if the two sets have the same amount of elements. However, if one of the sets has less elements than the other set (and the values are continuously matching), my function seems to go into a segmentation fa...
You are not at all checking if a node is NULL. You have to check it at the start of the function. ``` if(pa == NULL || pb == NULL) return 0; ```
``` #include <stdio.h> typedef struct hello{ int id; }hello; void modify(hello *t); int main(int argc, char const *argv[]) { hello t1; modify(&t1); printf("%d\n", t1.id); return 0; } void modify(hello *t) { t = (hello*)malloc(sizeof(hello)); t->id = 100; } ``` Why doesn't the program output100? Is i...
``` void modify(hello *t) { t = (hello*)malloc(sizeof(hello)); t->id = 100; } ``` should be ``` void modify(hello *t) { t->id = 100; } ``` Memory is already statically allocated toh1again you are creating memory on heap and writing to it. So the address passed to the function is overwritten bymalloc()The ret...
I tried the below code in both java and c++ , but it throwed an error in java while it does not throw an error in c++. Why is it so ? ``` while("abc"){ } ``` I do know it purely depends on the property of languages. But I would like to know why java set a condition that only boolean values should be allowed in loops...
I believe you are talking about compiler error and not run-time in case of java ``` while ( expression ) { // expression must evaluate to boolean value true or false // as far as I knwo "abc" is neither true or false when it comes to java hence error } ``` in C ``` while ( expression ) { // expression can be any...
am trying to pass along a "long long" number, the problem is when I try to divise this number by 10 , the answer is incorrect .. ``` #include <stdio.h> int main(void) { int n = 0 ; long long s = 4111111111111111; n = s % 10 ; printf("n after modulos %i\n",n ); s = s / 10 ; printf("this is s ...
``` printf("this is s after division %llo \n",s ); ^ (this prints (correct)value in octal representation) ``` Use specifier%lld(to get value in decimal ) .
So I've read a lot of similar posts but I can't nail down what my issue is here. ``` { FILE * fp; fp = fopen("integer_store.txt", "r"); int total; int i; clock_t start, end; double time; start = clock(); fscanf(fp, "%d", &i); while(!feof(fp)) { fscanf(fp, "%d", &i); ...
Please initialize the variabletotallikeint total = 0;first. Moreover, you should check iffopensucceeded (fpis notNULL).
This question already has answers here:srand(time(NULL)) doesn't change seed value quick enough [duplicate](6 answers)Closed8 years ago. I am trying to generate two different random numbers in C within a given range.The range is ``` 0 to nk-1 ``` But my following code sometimes works and sometimes fails.What is the...
You're supposed to seed the RNG once, ``` srand(time(0)); n1=rand()%nk; n2=rand()%nk; while(n1==n2) { n2=rand()%nk; } ```
I have the following: ``` char rank[100][100]; int score = 5; strcpy(rank[0], "%d" score); ``` However,strcpy()does not accept these arguments. Is there any way to append a formatted string into my array?
You could usesprintf: ``` char rank[100][100]; int score; sprintf(rank[0], "%d", score); ``` Note however thatsnprintfis the buffer overflow-safe alternative.
I wrote this code in C to print nos from 1 to 10 in a txt file one by one but after the execution only first no is printed in the txt file. pls help ``` #include<stdio.h> #include<stdlib.h> int main() { int i; FILE *fptr; fptr=fopen("C:\\program.txt","w"); for(i=1;i<=10;i++) { f...
Don't close the file until you finish writing to the file. ``` #include<stdio.h> #include<stdlib.h> int main() { int i; FILE *fptr; fptr=fopen("C:\\program.txt","w"); for(i=1;i<=10;i++) { fprintf(fptr,"\n%d\n",i); } fclose(fptr); } ```
I want to execute the following command ``` ubus -S call network.interface status '{"interface": "lan"}' ``` withexecvpin C: ``` char* arg[] = {"ubus", "-S", "call", "network.interface" , "status", "'{\"interface\": \"lan\"}'", NULL}; execvp(arg[0],arg); ``` but the command does not work. I make an investigation a...
Wrong path .. the argument reads{"interface": "lan"},not'{"interface": "lan"}'. The quotes are just for your shell, so it knows the whitespace inside belongs to the argument instead of being the delimeter between two arguments.ubuswill never see them. edit:better sayubusshouldnever see them, because in your implement...
How do we round a floating point number in C/C++ to print exactly two digits after the decimal point rounded to the nearest decimal place? say for example,when I use, ``` printf("%.2f", 12.555); cout<<fixed<<setprecision(2)<<12.555<<endl; ``` I get, ``` 12.55 12.55 ``` but I need output as, ``` 12.56 12.56 ```
The problem is that the actual double value for 12.555 is ``` 12.55499999999999971578290569595992565155029296875000 ``` so when you round it to 2 decimal places it rounds down to 12.55. There's really nothing you can do about that.
This question already has answers here:What does ~0 do?(4 answers)Closed7 years ago. Why doesprintf("%d", ~0);yield a value of-1? Shouldn't it be1since the~operator converts each 1-bit into a 0-bit and vice versa? From what I understand is0000will be negated to1111.
~is a bitwise complement operator .00000000is flipped to11111111. If you take2'scomplement of1(00000001)what you get is11111111which is to represent-1in binary. Therefore the output is-1.
I'm trying to use x and y coordinates from mouse for a game, but i can not get the coordinates. This is the event i've been reading: ``` typedef struct{ Uint8 type; Uint8 button; Uint8 state; Uint16 x, y; } SDL_MouseButtonEvent; ``` I need something like: ``` if(SDL_MouseButtonEvent.x >= 100) { //d...
A quick precision:event.mouse.xhas been replaced byevent.motion.xandevent.motion.xrelfor respectively absolute and relative mouse movement, bothint.