question
stringlengths
25
894
answer
stringlengths
4
863
I need to print variables usingHEXformat. The problem is when my variables are little the MSBs equal 0 so they are not printed. ``` ex: uint16_t var = 10; // (0x000A)h ``` -> I need to print"000A"but no matter what I do it always prints just'A' How could I get it to work?
You can add a leading0to the width specifier in order to forceprintfto add leading zeros (at least, you can in C and C++ - notentirelysure about other languages that use the function). For example, in C, the following: ``` #include <stdio.h> #include <stdint.h> int main() { uint16_t a = 10; // 0xA printf("%...
This is the algorithm to retrieve values from a2D array, what will be thetime complexityof this algorithm? ``` for(i=0;i<n;i++){ for(j=0;j<2;j++){ x = arr[i][j] } } ``` So thetime complexityof this algorithm would beO(2n)orO(n^2)? What is thereason?
Outer loop is iterating n times, but inner loop is iterating only two times, So time complexity will be O(2n) and not O(n^2). And ``` O(2n) = O(n) ```
Trying to do a rank based voting algorithm. Rank tells order of voter preference. For example if rank is 0, this is the first choice of the voter. I'm trying to save the order of names to the array but it doesn't work. Error is at the ranks[rank] = name; ``` bool vote(int rank, string name, int ranks[]) { for (i...
Your are trying to store a String value in int array. Either change the type of ranks array to String or change type of name to int.
I need to print variables usingHEXformat. The problem is when my variables are little the MSBs equal 0 so they are not printed. ``` ex: uint16_t var = 10; // (0x000A)h ``` -> I need to print"000A"but no matter what I do it always prints just'A' How could I get it to work?
You can add a leading0to the width specifier in order to forceprintfto add leading zeros (at least, you can in C and C++ - notentirelysure about other languages that use the function). For example, in C, the following: ``` #include <stdio.h> #include <stdint.h> int main() { uint16_t a = 10; // 0xA printf("%...
This is the algorithm to retrieve values from a2D array, what will be thetime complexityof this algorithm? ``` for(i=0;i<n;i++){ for(j=0;j<2;j++){ x = arr[i][j] } } ``` So thetime complexityof this algorithm would beO(2n)orO(n^2)? What is thereason?
Outer loop is iterating n times, but inner loop is iterating only two times, So time complexity will be O(2n) and not O(n^2). And ``` O(2n) = O(n) ```
The value ofiis not conflicting with the value ofiinitialized inside the loop, why is it so? ``` #include <stdio.h> int main() { for (int i = 0; i < 5 ; i++) { int i = 10; printf("%d \t", i); i--; } return 0; } ```
The variableiwas initialized as zero in the loop. Now, when the loop iteration begins, the identically named variableiinside the braces shadows the original one (defined outside of the braces). Since it was initialized to 10, the program displays10, then it is decremented by one later that doesn't affect the output b...
Can we add two numbers using pointers but without using any variable like a,b? I mean, generally, we take two variables and store it in pointer... but is it possible to the numbers without taking variable or can we take pointer variable?
Simple answer : ``` int *a = (int *)malloc(sizeof(int)); *a = 10; int *b = (int *)malloc(sizeof(int)); *b = 20; printf("%ld + %ld = %ld\n", *a , *b , *a + *b); ```
I would like to make clang compile both C and C++ files in the directory (if any). To achieve this, I run clang as follows:clang *.c *.cpp. My issue is that it refuses to run if there's no files of one type:clang: error: no such file or directory: '/mnt/c/test/*.c'Is there a way to make clang ignore wildcards that don...
The problem seems to be with the built in shell globbing inbash, not withclang. You can't makeclangignore what you feed it and a non-matching globbing will send the result unexpanded (since there's nothing to expand). To turn off the default globbing so that no matches results in an empty match: ``` shopt -s nullglob...
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.Closed2 years ago.Improve this question I am asked to write the C code that finds the number pi using the Leibniz formula. However, the result shou...
I played with it by increasing your iterations.At "200" I got 3.15.Basically "10" isn't even close to enough.
I'm trying to resize an array in C but i get a runtime assertion this is the code snippet : ``` int *v = malloc(sizeof(v) * 5); memcpy(v, (int[]){ 0, 1, 2, 3, 4,}, 5 * sizeof(int)); v = realloc(v, sizeof(int) * 6); v[6] = 6; for(int i = 0; i < 5; i++) { print...
You got two bugs that may cause memory corruption: sizeof(v)->sizeof(*v)v[6] = 6;, this is out of bounds since you allocated space for 6 items not 7. And C got 0-indexed arrays as they taught us in array beginner class.
Can we add two numbers using pointers but without using any variable like a,b? I mean, generally, we take two variables and store it in pointer... but is it possible to the numbers without taking variable or can we take pointer variable?
Simple answer : ``` int *a = (int *)malloc(sizeof(int)); *a = 10; int *b = (int *)malloc(sizeof(int)); *b = 20; printf("%ld + %ld = %ld\n", *a , *b , *a + *b); ```
I would like to make clang compile both C and C++ files in the directory (if any). To achieve this, I run clang as follows:clang *.c *.cpp. My issue is that it refuses to run if there's no files of one type:clang: error: no such file or directory: '/mnt/c/test/*.c'Is there a way to make clang ignore wildcards that don...
The problem seems to be with the built in shell globbing inbash, not withclang. You can't makeclangignore what you feed it and a non-matching globbing will send the result unexpanded (since there's nothing to expand). To turn off the default globbing so that no matches results in an empty match: ``` shopt -s nullglob...
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.Closed2 years ago.Improve this question I am asked to write the C code that finds the number pi using the Leibniz formula. However, the result shou...
I played with it by increasing your iterations.At "200" I got 3.15.Basically "10" isn't even close to enough.
I'm trying to resize an array in C but i get a runtime assertion this is the code snippet : ``` int *v = malloc(sizeof(v) * 5); memcpy(v, (int[]){ 0, 1, 2, 3, 4,}, 5 * sizeof(int)); v = realloc(v, sizeof(int) * 6); v[6] = 6; for(int i = 0; i < 5; i++) { print...
You got two bugs that may cause memory corruption: sizeof(v)->sizeof(*v)v[6] = 6;, this is out of bounds since you allocated space for 6 items not 7. And C got 0-indexed arrays as they taught us in array beginner class.
I have the following C code. I want to write a Java version of the C condition but I don't know what boolean operators the C numerical operators represent in the if statement. The C code is: ``` if ( (n >= 1) * (n < 10) + (n == 0) ) { printf("A\n"); } else { printf("B\n"); } return 0; ``` What bo...
You can figure this out by looking at their truth tables. Keep in mind that in C,0isfalse, and any other value (including1) istrue. ``` * | 0 | 1 + | 0 | 1 | | | | ---+---+-- ---+---+-- 0 | 0 | 0 0 | 0 | 1 ---+---+-- ---+---+-- 1 | 0 | 1 1 | 1 | 2 ``` In case this...
I want to know if there is a way to make a parent process stop his child for a given time usingsignalfor example: ``` pid_t pid = fork(); if(pid==0){ while(1){ //some code here } }else{ // some code to make child process stop for x seconds } ```
You may use SIGSTOP and SIGCONT to stop and continue the process. In combination with some time delay function (e.g. sleep() ) you may get the desired effect. You may check the example here:https://ostechnix.com/suspend-process-resume-later-linux/
How to pass a pointer toconst intin a recursive call. I am using the following code format to calculate Fibonacci recursively, but am getting the error: error: lvalue required as unary '&' operand** ``` #include <iostream> void fun(const int *n) { fun( &(*n-1) ); // it is giving error. } int main() { ...
You would have to use another variable then, to which you assign the decremented const variable: you simply can't pass a decreased value of a const variable, since by definition, it is not modifiable neither by increment or decrement. ``` #include <iostream> void fun2 (const int *n) { std::cout << *n << std::endl...
I would like to trap and handle CPU exceptions outside of KVM. How can I achieve this? ``` /* KVM_EXIT_EXCEPTION */ struct { __u32 exception; __u32 error_code; } ex; Unused. ``` From the documentation. This exit status is apparently not implemented. Yet, to handle an exception afaik you ...
So, I solved this by handling the exceptions unprivileged (in usermode), and simply trap into the hypervisor using any method of doing such, like writing to a trapping MMIO address. In my case the guest is always unprivileged and can't modify its own pagetables, so the host will be setting everything up before enterin...
This question already has answers here:How to write a while loop with the C preprocessor?(7 answers)Closed2 years ago. Is it possible to write a macro such as the following: ``` putcharX(repeat, char) ==> putcharX(5, '*'); ==> putchar('*'); putchar('*'); putchar('*'); putchar('*'); putchar('*'); ``` Note: I'm n...
you cannot write "real" recursive statements in macros. the closest you can get is ``` #define putcharOne putchar('*') #define putcharTwo putcharOne; putcharOne #define putcharThree putcharOne; putcharOne; putcharOne #include <stdio.h> int main() { putcharOne; putcharTwo; return 0; } ```
Could we point and address specific place in memory using pointer in c language? Then modify it from another file (ANOTHER PROGRAM) and view it from any where. Like : Modifying it : ``` #include<stdio.h> void main(){ int *p; p= 12345678; scanf("%d",p); } ``` Viewing it : ``` #include<stdio.h> void ma...
No. Each process in your operating system has its own address space.Processes can communicate, using the channels provided by the operating system.Look into IPC, aka inter process communication, if you're interested in knowing more about it.
If I have the following buffer: ``` char buffy[40]; // includes \0 at the end ``` Should thefgetsfunction haveSTLEN40 or 39? Why? ``` char buffy[40]; while (fgets(buffy, 40, fp) != EOF) // ... ```
The number of characters thatfgetsreads in is at most one less than the value of its second parameter. So the proper value should be 40 in this context. It will read at most 39 characters and the last element of the array will be used to store the '\0'. This ensures that no buffer overrun will occur. As an idiom ``` ...
How can I replace theNumbersvalues with the with theinput. If theinputis 1 than theNumbersvalue is going to be{"K", "2", "3", "4", "5", "6", "7", "8", "9"}and then if the userinputis 4 theNumbersvalue is going to be re updated to be{"K", "2", "3", "K", "5", "6", "7", "8", "9"}and so on. ``` int main(void) { int inp...
You need to use the standard C string function strcpy. For example ``` #include <string.h> //... strcpy( Numbers[input - 1], "K" ); ``` Before using the function you should check that the value ofinputis greater than0and not greater thansizeof( Numbers ) / sizeof( *Numbers ).
Instead of writingif(exp[i] =='*' || exp[i] =='/' || exp[i] =='+')can i write something like thisif(exp[i] == {'*','/','+'}).But writing this throws me an error, So is there any simple way of doing this ?
You can use thestrchr()function together with acompound literal: ``` if( strchr( (char[]){'*','/','+','\0'}, exp[i] ) ) ``` Or if you prefer, the far more readable string literal version: ``` if( strchr("*/+", exp[i]) ) ```
When compiling withgccI usedtimeto get compile time. ``` time gcc main.c && ./a.out ``` when trying to do the similar thing inclangI can't get the result ``` clang -time main.c && ./a.out ``` gives me a waring: clang: warning: argument unused during compilation: '-time' probably my approach is false, so please h...
Tryclang main.c -ftime-report
I was looking into scanf() - shifts the cursor to next line so got curious if fgets does the same but the output I am getting does not make sense to me . Please help me out in understanding it Code - ``` main() { char name[30] , name2[20]; scanf("%s" , name) ; printf("%s" , name) ; fgets(name2 , 30 , stdin) ; print...
The firstscanfdoesn't consume the end of line, just a string; so the call tofgetsread an empty line. Never mixscanfandfgetsyou will have problems.scanfis formatted input, whilefgetsis just raw input.
``` #include <stdio.h> #include <stdlib.h> int main() { exit(0); printf("%s\n", "Nice"); } ``` I was wondering if it is possible to disable whatever it is that doesn't generate the instruction for a call to printf if it is placed right after a call to exit. I'm usinggcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~...
exit()is defined in<stdlib.h>as never returning to its caller: ``` _Noreturn void exit(int status); ``` The compiler takes advantage of this and does not generate code for statements that are never reached. If you pass-Wallto get more diagnostics, you will get a warning about this.
This question already has answers here:Is the strrev() function not available in Linux?(7 answers)Closed2 years ago. I am unable to use strrev() function even after including string.h in Ubuntu 20.04. Compiler says undefined reference to strrev(), but strlen() and other functions work. What should I do?
You need to implement it yourself. ``` char *strrev(char *str) { char *end, *wrk = str; { if(str && *str) { end = str + strlen(str) - 1; while(end > wrk) { char temp; temp = *wrk; *wrk++ = *end; ...
This question already has answers here:Is the strrev() function not available in Linux?(7 answers)Closed2 years ago. I am unable to use strrev() function even after including string.h in Ubuntu 20.04. Compiler says undefined reference to strrev(), but strlen() and other functions work. What should I do?
You need to implement it yourself. ``` char *strrev(char *str) { char *end, *wrk = str; { if(str && *str) { end = str + strlen(str) - 1; while(end > wrk) { char temp; temp = *wrk; *wrk++ = *end; ...
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed2 years ago.Improve this question But it works for a l...
strlendoesn't return anintor along, it returns asize_t. It appears that in your system, asize_tis the same size as along. But if you're going to print out asize_twithprintf, you're supposed to use%zuto do it. That should work (on a new enough compiler to support it) regardless of the relative sizes ofint,longandsize_...
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed2 years ago.Improve this question But it works for a l...
strlendoesn't return anintor along, it returns asize_t. It appears that in your system, asize_tis the same size as along. But if you're going to print out asize_twithprintf, you're supposed to use%zuto do it. That should work (on a new enough compiler to support it) regardless of the relative sizes ofint,longandsize_...
I tested the following code on two different computers, using gcc: ``` int main(int argc, char** argv) { char c1, c2; c1 = 100; c2 = 4*c1; printf("%d", c2); } ``` One of both tests threw a segmentation fault, the other outputted-112. Why did this happen ?
First of all, let me tell you, a plancharissignedorunsigned, depends on the implementation. That said, I think you understand it by now, trying to store a value into a type which may not be fit to handle that, is implementation defined behavior. In most practical case, the stored value will be treated as the 2's com...
I am running gdb in the following way: ``` gdb $file "My Arg here" --ex "source .breakpoints_$file.c" --ex 'r' --ex 'set confirm off' ``` Yet I get the following in the program: ``` ─── Variables ─────────────────────────────────── arg argc = 1, argv = 0x7fffffffe1d8: 47 '/' ``` Meaning it's not picking up theargv...
You can do this by passing theargsargument togdb. For example: ``` gdb --ex "source .breakpoints_$file.c" --ex 'r' --ex 'set confirm off' \ --args $file "An argument" another ``` And now we get: ``` ─── Variables ────────────────────────────── arg argc = 3, argv = 0x7fffffffe1b8: 47 '/' >>> p argv[1] $1 = 0x7f...
I am writing a function ``` int are_non_negatives(int* start, int n) { ... } ``` This function returns 1 if all the nextnintegers in the arraystartarenon-negative. It returns 0 otherwise. My question is if there exist tricks that do this as fast as possible (other than looping and checking every single position)?...
One slightly "dirty/non-portable" trick you could leverage for the worst case where all elements need to be checked: In 2's complement int representation, the highest bit is set if and only if the value is negative. So, you could bitwise OR them all and check the highest bit. This could be done using vector instructio...
I am running gdb in the following way: ``` gdb $file "My Arg here" --ex "source .breakpoints_$file.c" --ex 'r' --ex 'set confirm off' ``` Yet I get the following in the program: ``` ─── Variables ─────────────────────────────────── arg argc = 1, argv = 0x7fffffffe1d8: 47 '/' ``` Meaning it's not picking up theargv...
You can do this by passing theargsargument togdb. For example: ``` gdb --ex "source .breakpoints_$file.c" --ex 'r' --ex 'set confirm off' \ --args $file "An argument" another ``` And now we get: ``` ─── Variables ────────────────────────────── arg argc = 3, argv = 0x7fffffffe1b8: 47 '/' >>> p argv[1] $1 = 0x7f...
I am writing a function ``` int are_non_negatives(int* start, int n) { ... } ``` This function returns 1 if all the nextnintegers in the arraystartarenon-negative. It returns 0 otherwise. My question is if there exist tricks that do this as fast as possible (other than looping and checking every single position)?...
One slightly "dirty/non-portable" trick you could leverage for the worst case where all elements need to be checked: In 2's complement int representation, the highest bit is set if and only if the value is negative. So, you could bitwise OR them all and check the highest bit. This could be done using vector instructio...
This question already has answers here:Algorithm to find nth root of a number(5 answers)Closed2 years ago. C hassqrt()andcbrt(), but those are only the second and third roots. What if the root is an arbitrary number? What if I need the 57nth root?
Use thepowfunction, taking advantage of the fact that getting the 57 root is the same as raising to the power of 1 / 57. More generically, to get theyroot ofx: ``` double result = pow(x, 1.0 / y); ```
``` *(&v69 + v15) = (double)(char)(*((_BYTE *)v14 + v15) ^ 0x80) * 0.0078125; ``` What does *(&v69 + v15) on the left side of the expression mean in this construction? v69 is the variable declared above. ``` float v69; ```
This is (confirmed by OP) reverse-compiled code. Take the address of variable v69 and add v15 to it and dereference the result as a pointer and assign to it. It makes sense. But there's a problem waiting for you. If not passed back through the exact same compiler again, variable rearrangement will break the correspo...
``` *(&v69 + v15) = (double)(char)(*((_BYTE *)v14 + v15) ^ 0x80) * 0.0078125; ``` What does *(&v69 + v15) on the left side of the expression mean in this construction? v69 is the variable declared above. ``` float v69; ```
This is (confirmed by OP) reverse-compiled code. Take the address of variable v69 and add v15 to it and dereference the result as a pointer and assign to it. It makes sense. But there's a problem waiting for you. If not passed back through the exact same compiler again, variable rearrangement will break the correspo...
How can i redeclared a variable in c. I know this can not be declared directly as follows; ``` int k = 5; float k = 12.5; ``` Is there any possible way to do like this?
No, you cannot redefine a variable with different types within the same scope. Although, there is one possible alternative. The same variable name can be used in a new scope or a subroutine. See the example below: ``` #include <stdio.h> // Subroutine void testing() { int k = 9; printf("k = %i\n", k); } // Ma...
Say I had a program in C where I asked the user to enter a number between 1 and 3. If the user selected a number outside of the range, whicherrnowould be most appropriate to return in my function?
I wouldn't use errno for a simple user-facing function like that. errno is mostly for system calls that are reporting low-level I/O, process, and other OS errors. It's not designed for things like bad keyboard input, incorrect file contents, or out of range values. When it's used by user libraries it's typically when ...
If open() returns a value of -1 to my program, which indicates a failure, do I still need to close the file? I read that if fopen() fails, then you do not need to call fclose() since you have not opened any files. I was wondering if this was the case for open() as well? ``` int fd = open(myfile, O_RDONLY); if (fd ==...
No. -1 isn't a file handle, so there's no need or reason to close it. You could have answered your own question by checking the return value ofclose(-1). It returns -1, so that call was in error.
When I run isalpha in vscode with c17-standard (or any other) it always returns only 1 or 0. Yet when i run it on another system it returns also bigger numbers than 1. How does isalpha work? Where can I see which implementation do I have? What causes this difference in behaviour on my system? I realise this question ...
From the C standard: 7.4.1 Character classification functionsThe functions in this subclause returnnonzero (true)if and only if the value of the argument conforms to that in the description of the function. When you implement the function from this class you do not have to return1or0. You are free to ...
I am trying to debug a Heap Corruption (using the QIRA Debugger); that only works with Doug Lea's Malloc. I have tried doing the following: ``` LD_PRELOAD=./malloc.so qira ./program $(cat shfree5) ``` I get the following error: ERROR: ld.so: object './malloc.so' from LD_PRELOAD cannot be preloaded (wrong ELF class...
It looks like you can setQEMU_SET_ENV=LD_PRELOAD=./malloc.soin the environment to affect the process. I'll note that you can similarly unset environment variables for the target by settingQEMU_UNSET_ENV=FOO,BAR.
Is there a way to pass a literal value to a function argument of a pointer . eg ``` unsigned char returnBitShift(unsigned char* bit , unsignedChar* shiftBitsToRight){ return (*bit) >> (*shiftBitsToRight); } unsigned char someBit = 254 , bitval; bitVal = returnBitShift(&someBit,(unsigned char)& 1); ```
You can use a compound literal to create an unnamed object, and its address can be taken and passed to a function: ``` bitval = returnBitShift(&someBit, & (unsigned char) {1}); ``` A compound literal is form with a type in parentheses followed by an initializer list in braces.
I am having a c program which print letter by letter of the word. I referred this program from this linkhttps://www.tutorialgateway.org/c-program-to-print-characters-in-a-string/. If I run this program in online c compiler this gives the exact result, but not working in turbo c++ ``` #include <stdio.h> int main() { ...
Tryfgets(str, 100, stdin)instead ofscanf(). This is the normal way to read a line into a buffer. When I usedscanf()I only got part of the output because it will stop reading a string at a space.
Is there a function attribute in GCC which acts as __stackless in IAR? I've been looking for it and didn't find anything... Thanks in advance Regards, Victor.
I would use a combination ofnakedandnoreturn. __attribute__((naked,noreturn,optimize("-O3"))) ``` extern int *x; void __attribute__((naked,noreturn,optimize("-O3"))) foo(int a, int b) { for(int c = a; c < b; c++) { x[c] = c * a; } } ``` https://godbolt.org/z/xf9YKa
Suppose my code is ``` void main() { for(i=1;i<5;i++) { printf("%d, ",i); } } ``` The output of this program will be ``` 1, 2, 3, 4, ``` How can I get output like ``` 1, 2, 3, 4 ``` The last,should be omitted.
``` #include <stdio.h> int main(void) { const char *pad = ""; for (int i = 1; i < 5; i++) { printf("%s%d", pad, i); pad = ", "; } putchar('\n'); return 0; } ``` You can't "delete" the character once you've printed it. You have to code so that you don't print what isn't actual...
I am actually stuck with the idea as mentioned in the question, about calling nested functions dynamically. Say I have 4 functions: fun1(), fun2(), fun3(), fun4() And I want them to be called in this way ``` fun1() { fun2() { fun3() { fun4() { } } } } ``` I am not sure how that ...
Nested functions are not part of the C Standard. Some compilers support them but using them makes the code less portable. Avoid such extensions.
I recently learned something fromthis questionaboutcinin C++ and its speed was compared with the speed ofscanfin C. Callingcinobject is much slower than callingscanffunction as usual but when I was reading the accepted answer, I understood if we callstd::ios::sync_with_stdio(false);,cinsynchronization withscanfis turn...
If you use both sets of I/O functions (header<cstdio>or<stdio.h>and also<iostream>) on the same stream (e.g. thestdinstream is associated with bothscanfandcin), then you'd better leave them synchronized. If any one stream only uses one I/O family you can turn off synchronization (you can still usefscanfwith a particu...
Given the below C code: ``` static atomic_int a_i; static void f() { for (int i = 0; i < 100; ++i) atomic_fetch_add_explicit(&a_i, 1, memory_order_relaxed); } ``` And two threads concurrently callingf(). Is it the case thata_imay end up having a non200result in hardware platforms with a relaxed cache cohe...
The resulting value is guaranteed to be 200. The memory order argument is only about whichothermodifications are made visible to other threads.memory_order_relaxedmeans that no guarantees are made. But the variable itself is still updated atomically.
This question already has answers here:Use of %d inside printf to print float value gives unexpected output(4 answers)Closed2 years ago. This is my code: ``` #include <stdio.h> #define PI 3.141592f #define RADIUS 10.0f int main(void) { float volume; volume = (4.0f/3.0f) * PI * (RADIUS * RADIUS * RADIU...
%dis for printingint, so passingfloatto that invokesundefined behavior. You should use%for%gto printfloat.
How can I format fscanf to format the input{'name surname', 'username', points}to strings which do not contain apostrophes ``` fscanf(fp,"{%s %s %d}",name,username,username1); ```
This should work: ``` fscanf(fp,"{'%[a-zA-Z ]', '%[a-zA-Z ]', %d}",name,username,username1); ```
This question already has answers here:Use of %d inside printf to print float value gives unexpected output(4 answers)Closed2 years ago. This is my code: ``` #include <stdio.h> #define PI 3.141592f #define RADIUS 10.0f int main(void) { float volume; volume = (4.0f/3.0f) * PI * (RADIUS * RADIUS * RADIU...
%dis for printingint, so passingfloatto that invokesundefined behavior. You should use%for%gto printfloat.
How can I format fscanf to format the input{'name surname', 'username', points}to strings which do not contain apostrophes ``` fscanf(fp,"{%s %s %d}",name,username,username1); ```
This should work: ``` fscanf(fp,"{'%[a-zA-Z ]', '%[a-zA-Z ]', %d}",name,username,username1); ```
In C'ssignal.hheader file there are a bunch of macros defined for (e.g.SIGCONT,SIGKILL). Are these object-like macros or function-like macros? How can one tell? Disclaimer: very new to C programming.
SIGCONTandSIGKILLare object-like macros. Macros that are defined and used with parenthesized arguments after them, like: ``` #define max(a, b) ((a) < (b) ? (b) : (a)) ``` are function-like macros, simply because they use arguments like a function. Macros that are defined and used without parenthesized arguments, li...
While debugging a simple C program, I always get an error saying "Launch: program 'XXX' does not exist" Note: I already have my compiler - GCC installed & I'm using Ubuntu operating system.
Replace the launch configuration from: ``` "program": "${workspaceRoot}/helloworld" ``` with: ``` "program": "${fileDirname}/helloworld" ``` This should fix your problem. Important:Ensure the compiled filename intasks.jsonis equivalent to your"program"'s filename.
``` char str[] = "a"; char ch = 'a'; ``` speaking of the difference between the two, we all knowstrpoint to a memory space which stored [a, \0], but I want to ask whether there is a difference betweenstr[0]andch?
but I want to ask whether there is a difference betweenstr[0]andch? No. str[0]andch, both are of typechar, and hold the value'a'. From this aspect (type and value), there is no difference.
I know that there is a similar topic, but those answers don't clarify what I want to find out. Thus, as long as from the excerpt below one can notice that a function and the reference to that function behave in the same way, what is the point in having both function variable and function pointers. ``` #include <stdio...
fand&fmean the same thing, so there's no need to use&f. But the language designers decided not to make it invalid for some reason, so you have this redundant syntax.
I cannot understand why are pointer type casts necessary, as long as pointers point to an address and their type is important only when it comes to pointer arithmetic. That is to say, if I encounter the next code snippet: int a = 5;then both char*b = (char*)&a;andint*c = (int*)&a point to the very same memory loca...
The pointer type is important when you dereference it, since it indicates how many bytes should be read or stored. It's also important when you perform pointer arithmetic, since this is done in units of the size that the pointer points to.
I can add include paths in Visual Studio easily but I couldn't find a way to do it in GCC? Any helps please?
Use the-Icommand-line argument: ``` gcc -Ipath ```
Take the following example where I want to get aconstdogandcatobject: ``` // place 1 (type declaration) const typedef struct Animal { int id; char* name; } Animal; // place 2 (singleton creation/assignment) const Animal Dog = {1, "Dog"}; const Animal Cat = {2, "Cat"}; // place 3 (reference of si...
const in place 2 is not needed. If you remove the const, you still cannot change the values ofDogandCatafter the declaration because your const typedef. Likewise, the const in place 3 is not needed. If you remove the const typedef, then you need the consts in place 2 and 3, depending on your purpose.
``` char fileName[20]; puts("Enter the date.\n"); scanf("-> %s", fileName); //Read the file FILE *ptr; ptr = fopen(fileName, "r"); if(ptr == NULL) { printf("\nNo file was found with this name\n"); exit(0); } else { printf("\nI FOUND the file.\n"); }...
Thank you @kaylum I got the answer. The problem is with thescanf()statement. Thescanf("-> %s", fileName)statement wants the user to input only->otherwise it will fail.
Title, basically. Isopen()cross platform? I personally like the flags combined with|better than a string, so can I just useopen()instead? Will it work anywherefopen()will?
open()is part of thePOSIXspecification, so it will work in any environment that implements this. This includes all modern flavors of Unix (POSIX is derived from Unix) as well as Windows. So you should be able to use it in any platform you're likely to encounter that also provides a hosted C implementation (so not a mi...
So I was reviewing the Microchip's dsPIC MCU header file and stumbled upon this construct: ``` /* Generic structure of entire SFR area for each UART module */ typedef struct tagUART { uint16_t uxmode; uint16_t uxsta; uint16_t uxtxreg; uint16_t uxrxreg; uint16_t uxbrg; } UART, *...
It's a kind ofall-in-oneform of ``` struct tagUART { // the structure itself with all its details uint16_t uxmode; uint16_t uxsta; uint16_t uxtxreg; uint16_t uxrxreg; uint16_t uxbrg; }; typedef struct tagUART UART; // UART is a shorter name for struct tagUART typedef struct ta...
This question already has answers here:What is short-circuit evaluation in C?(3 answers)Closed2 years ago. I want to ask a question about the code below. ``` int a=1, b=3, c=1; if((a||c--)&&(c&&b--)) printf("%d",b); printf("%d %d %d",a,b,c); ``` Why does the code prints "21 2 1" rather than "1 2 0" ? Thanks for y...
Since the or is evaluated to true immediately in (a||c--), the c-- is never evaluated. The compiler does this. If a statement is true right off the bat, it won't bother evaluating the rest. So, c is never decremented as the right side of the or is never evaluated.
``` #include <stdio.h> int main() { char text[20]; int quantity; float number; printf("Enter the data: "); scanf("%s %*d %f", text, &quantity, &number); printf("\nOutput: %s %d %f\n", text, quantity, number); return 0; } ``` Is there a way to properly use assignment suppression? Data ...
When you use assignment suppression, don't supply an argument for that match: ``` scanf("%s %*d %f", text, &number); ``` As for "deleting" the value inquantity, C doesn't have such a concept. Because it was not initialized, its value isindeterminate, so it should be initialized before printing it.
How to assign value to char** in C. ``` char** departmentList; departmentList[0] = "hahaha"; ``` above code is running in a function but failed all other places. Im using gcc 10.2.0 as the compiler.
You must allocate some buffer todepartmentListbefore dereferencing that. ``` char** departmentList; departmentList = malloc(sizeof(*departmentList)); // allocate departmentList[0] = "hahaha"; ``` Add#include <stdlib.h>(if it is not present) to usemalloc().
I'm using Visual Studio 2019 and I'm trying to compile an UEFI driver, that uses udis86(https://github.com/vmt/udis86) with the__UD_STANDALONE__preprocessor definition and the /NODEFAULTLIB linker option set. This gives me this error I have tried to set the_NO_CRT_STDIO_INLINEpreprocessor definition, like replied to ...
Maybe you could take a standalonevsnprintfimplementation from somewhere to satisfy the dependency. e.g.https://github.com/MrBad/vsnprintf or the Linux kernel one?https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/lib/vsprintf.c
This question already has answers here:random element from array in c(5 answers)Closed2 years ago. Basically i made an array with number 1,2,3. ``` int array[3] = {1,2,3}; ``` How can I select a random number from this list and assign it to a different variable?
Use therand()function and mod the result down to 3 values 0, 1, or 2 using mod. Then access the corresponding value in your array: ``` srand(time(NULL));// without this rand() function might continuously give the same value int index = rand() % 3; printf("random: %d\n", array[index]); ``` Considering that t...
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.Closed2 years ago.Improve this question I've been working on this problem: ``` #include<stdio.h> int main() { printf("%c", "abcdefgh"[4]); ...
The string"abcdefgh"doesn't have 4 elements. It's an array with 9 elements (the characters plus the null terminator, and square brackets are the array subscript operator. So"abcdefgh"[4]is getting the element at index 4 from"abcdefgh"which is'e'.
``` int a = 10; while (a > 8 ? (a--, (a > 7 ? a-- : a)): a--,a--) { printf("%d", a); // prints out 7 break; } ``` premise: I know that the code is very badly written, this is not a real example, I will never write like that. Can someone explain to me why it prints 7 instead of 8? it seems that the lasta-...
Comma operator,has lower precedence than ternary operator?:. Breaking your expression up: ``` a > 8 // true because a = 10 ? ( a-- // executed, making a 9 , ( a > 7 // true because a = 9 ? a-- // executed, making a 8 : a // not executed ) ) : a-- // not exe...
I would like to convert an int to a byte in C. In Java, I'd write: ``` int num = 167; byte b = num.toByte(); // -89 ``` In C: ``` int num = 167; ??? ```
You can simply cast to a byte: ``` unsigned char b=(unsigned char)num; ``` Note that ifnumis more than 255 or less than 0 C won't crash and simply give the wrong result.
I'm new to C language and I'm very curious about the best way to declare string in c. Example: ``` char *name; //or char name[]; scanf("%s", &name); printf("Hello %s !", name); ``` Which of these two will be better in this case? ``` char *name; char name[]; ```
If you have a string with constant length. You can declare an array ofcharlike this. ``` char name[64]; scanf("%s", name); // no more than 63 characters, remember the '\0' printf("Hello %s\n", name); ``` If the string length is dynamic, please use the functionmallocto allocate a specific length of memory. What's m...
This question already has answers here:how to initialize all elements of an array at one go when definition and declaration are separate?(5 answers)Closed2 years ago. Is there a way to delay the array initialization. For example, instead of doing: ``` int array[2] = {1,2}; ``` To do: ``` int array[2]; array = {1,2...
An array cannot be assigned to directly. You would either need to assign each element individually, or usememcpyalong with a compound literal of the proper type. ``` memcpy(array, (int[2]){1,2}, sizeof(array)); ```
I have a function where I am trying to reach the last index of the file contents. When i use descriptors and lseek combination as given below, things work normally: ``` offset = lseek(infd, 0, SEEK_END); ``` results in offset: 39 (which byte size of the file) infd is 3 ``` offset = fseek(file1, 0, SEEK_END); ``` ...
You are usingfseek, if you read thedocumentationyou can find: Return value​0​ upon success, nonzero value otherwise. On the other hand,lseekdocumentationreads: Return valueUpon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file. Hope this clears...
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.Closed2 years ago.Improve this question I perfectly know that .exe files are not executable under Linux but I need some files to be converted in .e...
You cancross-compileyour source files with special compilers : they are runnable on one platform, but produce executables for another.
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.Closed2 years ago.Improve this question I perfectly know that .exe files are not executable under Linux but I need some files to be converted in .e...
You cancross-compileyour source files with special compilers : they are runnable on one platform, but produce executables for another.
How can I work with the structure if i pass structure like parameter function ** ? ``` typedef struct TQueue { ... int m_Len; }TQUEUE; void nahraj(TQUEUE **tmp) { tmp[5]->m_Len = 7; } int main (void) { TQUEUE *tmp; tmp = malloc(10*sizeof(*tmp)); nahraj (&tmp); printf("%d\n",tmp[5].m_Len)...
You need to dereferencetmpbefore indexing it, since it's a pointer to an array, not an array itself. And the elements of the array are structures, not pointers to structures, so you use.rather than->. ``` void nahraj(TQUEUE **tmp) { (*tmp)[5].m_Len = 7; } ```
I was trying to find out what would be best practice. Suppose I have a C-function void myfunc(double); and I store this function prototype in myfunc.h I write the function definitions in myfunc.c ``` void myfunc(double p){ /* * Do work */ } ``` Should I #include "myfunc.h" in myfunc.c? It isn't necessary but ...
Yes you should because it makes sure that the function signature is the same in the declaration and the definition. If they don't match the program won't compile. It is also a good idea to includemyfunc.hbefore any other include file inmyfunc.c. That way you will know that the header file is self-contained.
How can I use amax_sizevariable to get only the desired characters?. ``` int max_size=64; sscanf(p,"%s %(MAX_SIZE-1)[^\n]",a,b); ```
Withsscanf, you would have to first prepare the formatting string. Something along: ``` char *fmt; int r = asprintf(&fmt, "%%s %%%u[^\n]", (unsigned)MAX_SIZE - 1); if (r < 0) abort(); sscanf(p, fmt, a, b); free(fmt); ``` The sad part about such solution is that compiler stops warning you about invalid specifiers.
I'm doing an exercise for my college and I am somewhat lost on pointers. The whole exercise is telling us to make a functionchar *mystrcpy(char *dest, char *src). So what we need is to make an already included in <string.h> by ourselves. It's not that hard as for the logical steps of the function, but i don't get wh...
You don't need a pointer to function but a function that return a pointer. like : ``` char* strcpy(char* destination, const char* source); ``` that return a pointer to destination.
Consider this short code: ``` #include <stdio.h> int main(){ short s[] = {0xAB, 0xCD}; printf("%x\n", *(char*)s); printf("%x\n", *((char*)s+1)); } ``` I thought casting s to char* would allow me to step bytewise through the array, producing the output ``` a b ``` But instead I get this: ``` ffff...
Use the correct printf format if you want one byte. ``` short s[] = {0xAB, 0xCD}; printf("%hhx\n", *(unsigned char*)s); printf("%hhx\n", *((unsigned char*)s+1)); printf("%hhx\n", *((unsigned char*)s+2)); printf("%hhx\n", *((unsigned char*)s+3)); ``` Then you will see the correct outputab 0 cd 0. It will also indica...
I have this small function that read words from a file: ``` bool load(const char *dictionary) { FILE *fp = fopen(dictionary,"r"); //defined LENGTH = 45; char *word = malloc(LENGTH + 1); while(fscanf(fp,"%s[\n]",word) != EOF) { //do ... thing in here } free(word); return tr...
No, this will not cause a memory leak in the way you suggest.fscanfdoes not reassignword, but rather modifies itscontents. You may wish to think of it in terms of:fscanfdoesn't changeword, but does changeword[0],word[1], etc. After a call tofscanf,wordwill still point to the samelocationin memory (i.e. whatever you g...
I'm doing an exercise for my college and I am somewhat lost on pointers. The whole exercise is telling us to make a functionchar *mystrcpy(char *dest, char *src). So what we need is to make an already included in <string.h> by ourselves. It's not that hard as for the logical steps of the function, but i don't get wh...
You don't need a pointer to function but a function that return a pointer. like : ``` char* strcpy(char* destination, const char* source); ``` that return a pointer to destination.
Consider this short code: ``` #include <stdio.h> int main(){ short s[] = {0xAB, 0xCD}; printf("%x\n", *(char*)s); printf("%x\n", *((char*)s+1)); } ``` I thought casting s to char* would allow me to step bytewise through the array, producing the output ``` a b ``` But instead I get this: ``` ffff...
Use the correct printf format if you want one byte. ``` short s[] = {0xAB, 0xCD}; printf("%hhx\n", *(unsigned char*)s); printf("%hhx\n", *((unsigned char*)s+1)); printf("%hhx\n", *((unsigned char*)s+2)); printf("%hhx\n", *((unsigned char*)s+3)); ``` Then you will see the correct outputab 0 cd 0. It will also indica...
I have been trying to write a file from memory in C, more specifically an executable file. Every time I try to usefputsit detects a '00' in memory after a bit and stops writing. But there is still the rest of the file that it has to write. In the file that I am trying to write there are '00's all over the place for pa...
you should use 'fwrite' take the place of fpus
I have a project where we are supposed to find a sha256 from another sha256. For example we have ``` hash1 = "45f1bc22c29626c6db37d483273afbe0f6c434de02fe86229d50c9e71ed144fc" ``` and we would have to find ``` hash0 = "5495a885b7f445a198cc5b67a517a0e0536792ab3e7ead18a12c75f8310a9b89" ``` hash1is just thehash0used...
It's impossible, hashes can't be inverted, regardless if they're hashes of hashes or of other content. You could try all the combinations, sure, knowing that the source is a 256-bit sequence, but this is practically prohibitive, although there's always a possibility of 1 out of 2^256 that you guess it at the first try...
``` #include <cs50.h> #include <stdio.h> int main(void) { // TODO: Prompt for start size int n,m,y,b,a; do{ n= get_int("Start Size"); } while(n <9); // TODO: Prompt for end size do { m = get_int("End Size"); } while(n > m); // TODO: Calculate number...
The condition to end the loop doesn't depend on anything that changes inside the loop. So the loop will either never execute or will execute forever.
I am trying to undertand how this code works, specifically the linemsk = ~(uint64_t) 0 << (uint64_t)(high - low + 1); I really only am curious whatuint64_tis calling/doing. Not so much the bit operations Thanks for any insight! ``` uint64_t clearBits(unsigned low, unsigned high, uint64_t source){ uint64_t msk; ...
uint64_tis an integer type.uint64_t msk;declares a variable of that type and(uint64_t) 0casts0to that type since the literal0is anint. Similarly,(uint64_t)(high - low + 1)casts the result of a calculation to the typeuint64_t. However, this second cast is unnecessary, as discussed in the comments since the type of the ...
This question already has answers here:Get a substring of a char* [duplicate](5 answers)Copying a part of a string (substring) in C(13 answers)Closed2 years ago. I am trying to parse data from the user. I need to get a certain number from the user. And I do not mean like with strstr(). I mean more like characters 9-...
Use strcnpcy, in the second parameter you pass the starting position: ``` char array[15] = "asdfghjkbruhqw"; char dest[10] = ""; strncpy(dest, &arr[9], 3); ```
How do I convert this array with ASCII numbers to text, so every number get's a letter. So "72" gets H, 101 gets E and so on. int a[] = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100};
You can iterate over the array, and use the%cformating parameter to print the ascii characters of the int value ``` for (int i = 0 ; i < 11; i ++){ printf("%c", a[i]); } ```
I am trying to undertand how this code works, specifically the linemsk = ~(uint64_t) 0 << (uint64_t)(high - low + 1); I really only am curious whatuint64_tis calling/doing. Not so much the bit operations Thanks for any insight! ``` uint64_t clearBits(unsigned low, unsigned high, uint64_t source){ uint64_t msk; ...
uint64_tis an integer type.uint64_t msk;declares a variable of that type and(uint64_t) 0casts0to that type since the literal0is anint. Similarly,(uint64_t)(high - low + 1)casts the result of a calculation to the typeuint64_t. However, this second cast is unnecessary, as discussed in the comments since the type of the ...
This question already has answers here:Get a substring of a char* [duplicate](5 answers)Copying a part of a string (substring) in C(13 answers)Closed2 years ago. I am trying to parse data from the user. I need to get a certain number from the user. And I do not mean like with strstr(). I mean more like characters 9-...
Use strcnpcy, in the second parameter you pass the starting position: ``` char array[15] = "asdfghjkbruhqw"; char dest[10] = ""; strncpy(dest, &arr[9], 3); ```
Why doesn't gcc give any warnings about this code? ``` #include <stdio.h> void printDigits(int *arr, int arrsize); int main() { int number[] = { 1, 7, 8, 3, 6, 5, 4, 2 }; size_t arraysize = (sizeof(number) / sizeof(number[0])); printDigits(number, arraysize); return 0; } void printDigits(int *arr...
There is a warning.i<arrsizeis computed but then discarded, so gcc warns: ``` warning: left-hand operand of comma expression has no effect [-Wunused-value] ``` (Which is enabled by-Wall)
The following code doesn't run. Can I say increment/decrement operators won't work on functions with return type int? ``` int main() { char x[] = {"test"}; int size = strlen(x); //works :) int size2 = --strlen(x); //doesn't work return 0; } ``` Error is: ``` error: lvalue require...
The prefix decrement operator--decrements the object which is the subject of the operator. The return value of a function is just that, a value and not an object. It's the same as if you tried to do--4. If you want to assign 1 less than the length ofxtosize2, you would do it like this: ``` int size2 = strlen(x) - ...
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.Closed2 years ago.Improve this question I also noticed that multiples of 0.0625 such as 1.25 keep giving zero but I was unable to find an explanati...
as per CostantinoGrana "Do you know how IEEE 754 works? The numbers which you say "give 0" are multiples of a not too negative negative power of 2. So when you store them in little endian, the 32 less significant bits, that are all 0, are the first thing you find in memory as int. Your int is 32 bits wide, thus 0."
In SDL, when I destroy a window withSDL_DestroyWindow, do I also need to callSDL_FreeSurfaceto release the surface that is associated with that window? ``` SDL_Window *window = SDL_CreateWindow(/*...*/); SDL_Surface *wsurface = SDL_GetWindowSurface(window); /*...*/ SDL_FreeSurface(wsurface); /* <- do I also need this...
It gets released automatically. Here is the relevantdocumentation: A new surface will be created with the optimal format for the window, if necessary. This surface will be freed when the window is destroyed.Do not free this surface.
My stack_d.h file ``` #ifndef stack_d #define stack_d struct s { int boyut; int tepe; int dizi; }; typedef struct s* stack; stack * init (); int pop(stack *); void push (int, stack *); void bastir(stack *); #endif ``` My stack.c file ``` #include <stdio.h> #include <stdlib.h> #include "stack_d.h" stack ...
What should I do? Remove the pointer from thetypedef: ``` typedef struct s stack; ``` and your code should be fine. Do not use pointertypedefs, they are very confusing.
I've come across theiso646.hwhich provides some of the nice logical keyword operators that I'm used to from python. Is one of the following approaches preferred over the other? ``` if (x>7 && y<-2) printf("Normal symbols\n"); ``` ``` #include<iso646.h> if (x > 7 and z < 4) printf("Iso646 is here\n"); ``` I...
As a C developer, I would be puzzled if I seeandinstead of&&. Or should it be a single&? I would need to dig into the include files to be sure how that uncommon keyword is defined. Indeed&&is much more familiar thanandin the context of a C program.
I'm trying to learn C programming right now but I'm a bit stumbled upon the concept of declaring an array of pointers to functions. The statement is right here: ``` int (*menu_option[10])(char *title); ``` What exactly is happening here?
from thespiral rulehere menu_optionis an array of 10function pointersthey takechar*as an argument and return anint usehttps://cdecl.org/to parse C gibberish to English