question
stringlengths
25
894
answer
stringlengths
4
863
I included a check fornullptrin a line of C code. The compiler (gcc) complained when using-std=c17as well as-std=gnu17. Is there such a thing as nullptr (or equivalent) in modern C standards? (C11, C17) If not, then why?
No, C still usesNULLfor a null pointer. C++ needs a dedicated null pointer literal because it has overloading and template type deduction. These features get confused byNULL, which expands to0(or something like that) in C++. However, the risk of such confusion in C is small (maybe_Genericcan get confused by this), and in addition, C can use(void*)0for a null pointer, which mitigates this risk even more.
can anybody tell me exact code i have this code. im using devc++ and i need only C code. ``` #include <stdio.h> #include <stdlib.h> int main() { system("C:/programA.exe"); // how to add 2nd program with timer? return 0; } ``````````````````` This code works ok. Step1- launch Program A immidiately. (already in mentioned code works).Then goto next line without waiting to close ProgramA. Step2- sleep for five seconds Step3- launch Program b (Only if user press a key F10 or F11) With waiting time 30 seconds. If user not press that key then close automatically after 30 seonds. ```
Forkthe program and useexecvpto replace the forked process with the program you want to start.Detecting key presses directly is not possible using just C. Thencurseslibrary is a good general choice to do this.
I am going through one small code where I need to take whole line as input through scanf function, and I think there is one format specifier "[^\n%*c]" can someone please tell me syntax for it and how it works?
The best way is probably to usefgets. ``` char str[20]; fgets(str, 20, stdin); printf("%s", str); ``` No reason to usescanfhere. Just remember thatfgetsalso puts the newline character in the buffer. It can be removed like this: ``` str[strcspn(str, "\n")] = 0; ```
What can I do to get rid of the compiler warning about a statement with no effect? I'm using fgets to read the output of a bash command, but I don't need to or want to do anything with it apart from outputting it to my buffer. ``` while (fgets(pid, sizeof(pid), fp) != NULL) { 1; //Statement with no effect :( } ```
Why do you have the1;line? You can have emptywhileloops ``` while (fgets(pid, sizeof(pid), fp) != NULL) { } ``` Or ``` while (fgets(pid, sizeof(pid), fp) != NULL); // Note semi-colon ``` It's probably best to avoid the second option as it's easier to misunderstand what's going on.
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 ``` #include <stdio.h> #include <conio.h> int main() { float a,b; int c; printf("Enter Number a\n "); scanf("%f",&a); printf("Enter num b \n"); scanf("%f",&b); c=a+b; printf("The sum is %d",c); return 0; } ``` The query has now been resolved ,thanks to the community at stack overflow ,I am a beginner in programming and have just started to learn c and didn't knew regarding this but now I have been banned to ask questions😥
you should change code runner output to theTerminal go to vscode settings and search code runnrer : run in terminal and check it video how to do it :https://www.youtube.com/watch?v=Mxao-84mypo
Consider a Fibonacci sequence whose values do not exceed four million. Find the sum of the even-valued terms. Your answer must be 4613732. ``` #include <stdio.h> int main() { int a =0,b=1,c=0,sum=0; while (c<=10){ int c=a+b; a=b; b=c; if(c%2==0){ sum=sum+c; } } printf("%d",sum); return 0; } ``` The output comes out to be blank. I tried 10 for smaller calculation time and the answer should be 2+8=10. I don't know what to do.
In this question ``` int c=a+b; ``` You are not using the value declared outside of the method Insted you are defining a new variable that only works on inside of your method. Try removing theintdecleration inside thewhileloop and It should work
I have this statement and I want to change this in the form of a macro: ``` int *arr; <br> int T; cudaMalloc( &arr, sizeof(int) * (1+T) ); ``` I did something like this but this is not working in program. ``` #define fun(a,b,c) cudaMalloc( (a), sizeof( b) * (1+ c)); ``` How this could be done?
This works: ``` #define CUDA_MALLOC(a, b, c) (cudaMalloc( (a), sizeof(b) * (1 + (c)) )) // other code cuda_ret = CUDA_MALLOC(&arr, float, no_elements); ``` Note the lack of a semicolon at the end of the line and the extra parentheses to guard against problems resulting from operator precedence. On a side note, I'm not convinced using these kinds of macros is a good practice.
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 encountered this line of code: ``` memset(tmp, 0, (-len) & 0x7F); ``` Wherelenis auint8_tpointervariable. What's is the "-" doing tolenbefore the bitwise operation? What would be the result? Given it is an unsigned integer, I don't think it'd make sense to add a sign this way (if it is at all possible in C), even less with it being a pointer.
lencannot be apointerto a variable, because the unary minus operator cannot accept a pointer as an operand. The code would not compile. Considering thefunction prototype of memset, it is more likely thatlenis of the typeuint8_there. The behavior of applying the unary minus operator on unsigned types is describedhere.
I have this statement and I want to change this in the form of a macro: ``` int *arr; <br> int T; cudaMalloc( &arr, sizeof(int) * (1+T) ); ``` I did something like this but this is not working in program. ``` #define fun(a,b,c) cudaMalloc( (a), sizeof( b) * (1+ c)); ``` How this could be done?
This works: ``` #define CUDA_MALLOC(a, b, c) (cudaMalloc( (a), sizeof(b) * (1 + (c)) )) // other code cuda_ret = CUDA_MALLOC(&arr, float, no_elements); ``` Note the lack of a semicolon at the end of the line and the extra parentheses to guard against problems resulting from operator precedence. On a side note, I'm not convinced using these kinds of macros is a good practice.
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 encountered this line of code: ``` memset(tmp, 0, (-len) & 0x7F); ``` Wherelenis auint8_tpointervariable. What's is the "-" doing tolenbefore the bitwise operation? What would be the result? Given it is an unsigned integer, I don't think it'd make sense to add a sign this way (if it is at all possible in C), even less with it being a pointer.
lencannot be apointerto a variable, because the unary minus operator cannot accept a pointer as an operand. The code would not compile. Considering thefunction prototype of memset, it is more likely thatlenis of the typeuint8_there. The behavior of applying the unary minus operator on unsigned types is describedhere.
I am planning on writing a command line text editor in C for a *nix system similar to nano or vim but I am stuck on how I would go about getting access to the entire terminal window so the user can move around the text editor freely, do I need to use a 3rd party library to achieve this result if so what libraries are required, or am I able to achieve this result with the standard C libraries and if so what libraries should I use.
The ncurses library is the simplest way of gaining access to a full terminal window although it can also be achieved with the libc libraries.
I am new to C and trying out Tensorflow in C. I could see most of the Structs are incomplete type and I want to write a function where they are intialized. For example, below code is not working. ``` int main() { TF_Status* Status = NULL; TF_Graph* Graph = NULL; init(Status); return 0; } void init(TF_Status* Status, TF_Graph* Graph) { Status = TF_NewStatus(); Graph = TF_NewGraph(); } ``` Any idea how can I do this?
Pass pointers to what to modify to functions to let functions modify them. ``` void init(TF_Status** Status, TF_Graph** Graph); int main(void) { TF_Status* Status = NULL; TF_Graph* Graph = NULL; init(&Status, &Graph); return 0; } void init(TF_Status** Status, TF_Graph** Graph) { *Status = TF_NewStatus(); *Graph = TF_NewGraph(); } ```
struct birthday{ int day:6; }b-day; While declaringb-dayas a structure it shows the following error: ``` error: expected ':', ',', ';', '}' or '__attribute__' before '-' token| ``` but after removing the hyphen from the variable name it works, why?
Hyphens are used as subtraction and negation operators, so they cannot be used in variable names. (Whether the variable is for a structure or another type is irrelevant.) If you had: ``` int a = 1; int b = 2; int a-b = 3; printf("%d\n", a-b); ``` then we would have ambiguity about whether to print “-1” foraminusbor to print “3” for the variablea-b.
I am getting an int of the entire string s for 'letter', the conditions in my 'if' statement seem to not be reading properly - is my syntax incorrect? I get user input: ``` string s = get_string("Text here: "); ``` the function is as follows: ``` int letter_count(string s) { int i =0; int len = strlen(s); int letter = 0; while(i < len) { if (s[i] != '\0' || s[i] != '.' || s[i] != ',' || s[i] != '!' || s[i] != '?') { letter++; } i++; } return letter; } ``` then call the function: ``` int letter = letter_count(s); printf("letter Count: %i\n", letter); ```
Try changing the OR operator with the AND
Here I want to change the change the value ofibut getting error as:error: redefinition of 'i' int i=4; ^ exp.c:5:9: note: previous definition is here int i=4; ``` #include<stdio.h> #include<math.h> int main(void){ int i=4; printf("before:%i",i); int i=5; printf("after:%i",i); } ``` So my question is how to overwrite the value of a variable which already value assigned.
You maydefinea variable only once. You can (usually!) (re)assign a value to a variable as many times as you want: ``` int main(void){ int i=4; // Declare as "int" and assign value "4" printf("before:%i",i); i=5; // Assign a different value printf("after:%i",i); } ```
A relatively large project is using many objects (mostly from C files) to create several executables and dynamic libraries. For example, one of these files (gxdb.c) creates a function named gxdbkq, which appears (in the details of the object file) as: ``` ... 00000000000007b0 T gxdbkq ... ``` However, and when I check the shared library, the function has become undefined: ``` ... U gxdbkq ... ``` The problem is probably in the linking phase, but I do not know how to even start troubleshooting this issue.
The problem is probably in the linking phase Yes, the most likely problem is that you do not linkgxdb.ointo your library. Another possibility is that your link line has a "stray" flag which makes the linker ignore the next argument, which happens to begxdb.o. You should closely examine your link line to make sure thatgxdb.ois on it, and that no unintended flags are.
the following is a part of C code for singly linked list: ``` for(tptr = start; tptr != NULL && tptr->data < newnode->data; prev=tptr, tptr= tptr->next); ``` How do I convert this for loop in C to for loop in Python?
In C ``` for(tptr = start; tptr != NULL && tptr->data < newnode->data; prev=tptr, tptr= tptr->next); ``` is equivalent to ``` tptr = start; while (tptr != NULL && tptr->data < newnode->data) { prev = tptr; tptr = tptr->next; } ``` A C-styleforloop is rather awhileloop. Expressing it in Python with aforconstruct would be certainly possible (e.g., writing aforloop that runs forever and breaking out if the condition is not met), but it would not be best practice. In Python, I would recommend to express your example with awhileloop (unless it is a simplefor-loop like iterating over the numbers 0 to n).
I have a static library (array.a) in c that contains a code like this : ``` int array[ARRAY_LENGTH]; ``` andARRAY_LENGTHis defined inCFG.clike this : ``` #define ARRAY_LENGTH 10 ``` my question is that if I changeCFG.cand setARRAY_LENGTHto20, then I havearray[20]in my app or it remainarray[10]? How can I change it?
The array in a linked library will have the size it had at the point of linking. Changing the source without linking it again won't magically change the size in the lib. Generally one provides a .h file and one or several .c file(s). The .c file(s) becomes the lib and the .h file contains all info required. It doesn't make sense to place an array in one .c file and declare its size in another .c file.
``` #include <stdio.h> extern int i; int main() { int i = 5; printf("%d", i); return 0; } ``` From what I understand, there is no global variable namedito which the external declaration ofishould refer. So it should produce a linker error. Yet this code runs successfully and prints5. Why so?
``` #include <stdio.h> extern int i; // this is one variable called "i" int main() { int i = 5; // it is second variable called "i" printf("%d", i); return 0; } ``` You have variableideclared (but never defined) in the global (file) scope. You also have variableidefined in the local scope of functionmain. The global scopeiand the automatic function scopeivariables are not related. As you never use the globaliit was optimized out by the compiler and the linker did not have to search for the objectiin object and library files. BTW yourmainfunction should beint main(void)notint main()
I have two uint_16ts that I've gotten from the nibbles of my data as seen in the code below. I need to put that into mask set so that each of the nibbles are now in its own byte. The code I got is below I can't for the life of me figure it out. I need to do this cause this will create the mask I will use to unmask mildly encrypted data. ``` uint16_t length = *(offset+start) - 3; uint16_t mask = length; if(Fmt == ENCRYPTED) { char frstDig = (length & 0x000F) char scndDig = (length & 0x00F0) >> 4; mask = ```
Shift one of the digits by 8 bits, and OR them together. ``` mask = (scndDig << 8) | frstDig; ```
I have a static library (array.a) in c that contains a code like this : ``` int array[ARRAY_LENGTH]; ``` andARRAY_LENGTHis defined inCFG.clike this : ``` #define ARRAY_LENGTH 10 ``` my question is that if I changeCFG.cand setARRAY_LENGTHto20, then I havearray[20]in my app or it remainarray[10]? How can I change it?
The array in a linked library will have the size it had at the point of linking. Changing the source without linking it again won't magically change the size in the lib. Generally one provides a .h file and one or several .c file(s). The .c file(s) becomes the lib and the .h file contains all info required. It doesn't make sense to place an array in one .c file and declare its size in another .c file.
``` #include <stdio.h> extern int i; int main() { int i = 5; printf("%d", i); return 0; } ``` From what I understand, there is no global variable namedito which the external declaration ofishould refer. So it should produce a linker error. Yet this code runs successfully and prints5. Why so?
``` #include <stdio.h> extern int i; // this is one variable called "i" int main() { int i = 5; // it is second variable called "i" printf("%d", i); return 0; } ``` You have variableideclared (but never defined) in the global (file) scope. You also have variableidefined in the local scope of functionmain. The global scopeiand the automatic function scopeivariables are not related. As you never use the globaliit was optimized out by the compiler and the linker did not have to search for the objectiin object and library files. BTW yourmainfunction should beint main(void)notint main()
I have two uint_16ts that I've gotten from the nibbles of my data as seen in the code below. I need to put that into mask set so that each of the nibbles are now in its own byte. The code I got is below I can't for the life of me figure it out. I need to do this cause this will create the mask I will use to unmask mildly encrypted data. ``` uint16_t length = *(offset+start) - 3; uint16_t mask = length; if(Fmt == ENCRYPTED) { char frstDig = (length & 0x000F) char scndDig = (length & 0x00F0) >> 4; mask = ```
Shift one of the digits by 8 bits, and OR them together. ``` mask = (scndDig << 8) | frstDig; ```
This question already has answers here:What is short-circuit evaluation in C?(3 answers)Closed2 years ago. How the Output was 1 and 4 . I cant understand the logic behind the c program? ``` #include <stdio.h> int main() { int a; int i = 4; a = 24 || --i; printf("%d %d",a,i); return 0; } ``` Output ``` 1 4 ...Program finished with exit code 0 Press ENTER to exit the console. ``` Can anyone explain the logic for the program..........
I think that the language C has 0 as the value forfalseand all non-zero numbers astrue. So, from the viewpoint of an optimising compiler you get: ``` a = 24 || --i; a = TRUE OR --i; => "TRUE OR ..." is always TRUE, so just skip it! Hence: a == 1 (which means "TRUE") ``` And what abouti? Well, nothing happened, so it just keeps having its original value.
Assuming that all the header files are included. ``` void main() { int i; clrscr(); printf("india"-'A'+'B'); getch(); } ``` The Output of the following function is :ndia Can anyone please explain me this output?
``` int printf(const char *restrict format, ...); ``` When you doformat - 'A' + 'B', it's equal toformat + 1considering the ASCII values ofAandB. formatis the base address and when you doformat + 1it points to second memory location of this character string and from there it starts printing which isndia.
Hi I have a c file in program which is called helloQV.c I ran the commandgcc -Wall -ansi -std=c99 helloQV.c -o helloQV.cbut now I cannot edit the file helloQV.c, when I open the file in vim it turns out to be just a bunch of random symbols. I realized I should have named the-o HelloQV.cto something different. What can I do to undo that change so I can re-edit my helloQV.c file. Thanks
Your file showing up green on your terminal using ls means that your file is now an executable file because you’ve overwritten your file with gcc command. There is no way to get your original file back, I'm afraid.
I am learning pointers in C programming. A piece of code is: ``` #include <stdio.h> int main() { int ary[4] = {1, 2, 3, 4}; int *p = ary + 3; printf("%d\n", p[-2]); } ``` aryis the array and how is the*ppointing to theary+3and output coming is2.How is the pointer handling the array values? I looked intohttps://www.geeksforgeeks.org/pointer-array-array-pointer/but I did not found how pointer is influencing array there?
It is very easy to understand. We knowarris an array but thearrreference will always point to an address of a starting element of the array. So, for above example.arris point to address ofarr[0](value 1).arr + 3will point to thearr[3](value 4). That means pointerpis point toarr[3]. Now,p[-2]will move the pointer 2 address back and will point toarr[1](value 2). Hence the output 2 !
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 the following number: 14.2423421. This number is a float. I want to convert it into 142423421. So, I want the same number, without the point. It has to be an int. Obviously it mustn't be a string type. How to do it? Thank you everybody!
Count the number of decimals as suggestedhereand multiply your number by 10^(number of decimals)
I'm using the rand() function from the Standard c Library to generate numbers for a Monte Carlo simulation in the range 0 to 1 using: ``` (double)rand()/RAND_MAX ``` But I noticed that the result was slightly off. I checked at which value the generated numbers averaged out and it was slightly under the expected 0.5. I read that rand() is Modulo biased but I’m not using modulo here. Is there a more precise way to generate numbers between 1 and 0? Edit: I'm fairly new to Prngs so i didn't know that some prngs arent threadsafe. I should have mentioned that i used rand() multithreaded. Regardless, your answers helped me to find a faster and threadsafe rng.
It depends on your C implementation. Some have a higher quality implementation ofrandthan others. Maybe usearc4random, or some other crypto based PRNG instead.
According to POSIX, if we use aselect()to decide when we can use a read without blocking, is it possible that theread()is interrupted by a signal and returnsEINTR?
Your reads certainly can be interrupted by signals. All thatselectguarantees is thatreadwill not be blocked. It has absolutely nothing to say about possible interruption by signals. Fromman page: select() allows a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform a corresponding I/O operation (e.g., read(2), or a sufficiently small write(2)) without blocking. Moreover, how canselectpredict the future? It knows that right now socket has some data which can be read. How can it tell you if signal will be raised when you try to read this data?
I'm using the rand() function from the Standard c Library to generate numbers for a Monte Carlo simulation in the range 0 to 1 using: ``` (double)rand()/RAND_MAX ``` But I noticed that the result was slightly off. I checked at which value the generated numbers averaged out and it was slightly under the expected 0.5. I read that rand() is Modulo biased but I’m not using modulo here. Is there a more precise way to generate numbers between 1 and 0? Edit: I'm fairly new to Prngs so i didn't know that some prngs arent threadsafe. I should have mentioned that i used rand() multithreaded. Regardless, your answers helped me to find a faster and threadsafe rng.
It depends on your C implementation. Some have a higher quality implementation ofrandthan others. Maybe usearc4random, or some other crypto based PRNG instead.
According to POSIX, if we use aselect()to decide when we can use a read without blocking, is it possible that theread()is interrupted by a signal and returnsEINTR?
Your reads certainly can be interrupted by signals. All thatselectguarantees is thatreadwill not be blocked. It has absolutely nothing to say about possible interruption by signals. Fromman page: select() allows a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform a corresponding I/O operation (e.g., read(2), or a sufficiently small write(2)) without blocking. Moreover, how canselectpredict the future? It knows that right now socket has some data which can be read. How can it tell you if signal will be raised when you try to read this data?
According to the C standard the conversion specifier%is defines as: % Matches a single % character; no conversion or assignment occurs. The complete conversion specification shall be %%. However this code: ``` int main(int argc, char* argv[]) { int n; printf("%d\n", sscanf(" %123", "%% %d", &n)); return 0; } ``` compiled with gcc-11.1.0 gives the output 1 so apparently%%matched the" %"of the string. This seems to be a violation of "Matches asingle% character" as it also accepted the spaces in front of the % character. Question: Is it correct according to the standard to accept white spaces as part of%%directive?
According to the C89 Standard, at least, "Input white-space characters [...] are skipped, unless the specification includes a[,c, ornspecifier." (That's an old version of the Standard, but it's the one I had handy. But I don't imagine this has changed in more recent versions.)
I've readman 3p wait, but what I could only find was this statement: In this case, if the value of the argumentstat_locis not a null pointer, information shall be stored in the location pointed to bystat_loc. I could also find opengroup page on google, but it was almost exactly same withman 3p wait.Where can I find explicit statement that sayswait(NULL)is well defined?
I don't think you'll find an explicit statement, but this is typical wording for this situation. If they meant that NULL was not allowed, you would see a statement like "stat_locshall be a non-NULL pointer" or "stat_locshall point to an object..." or "ifstat_locis NULL, the behavior is undefined". In this case, it just means that if you pass a null pointer, the defined behavior is thatwaitjust ignores it, and doesn't store that information anywhere at all.
I want to learn C. I have downloaded mingw from sourceforge.net but after installing it I realised that it installed version 6.3.0 of GCC. as I know the latest version of GCC is 11.2. Does anybody know how to install latest version of GCC, and do I need to uninstall that mingw folder? I'm on the windows 10
Install MinGW-w64 gcc (for either 32-bit or 64-bit Windows) via MSYS2's package manager (pacman), or get a standalone build fromhttps://winlibs.comwhich requires no installation - just unzip (can coexist alongside other MinGW versions). If you're new to programming in C, I recommend using an IDE, like Code::Blocks for example.
I am attempting to compile a C program on macOS Catalina. The program will make use of bzip2 decompression. My code includes the line ``` #include <bzlib.h> ``` and I am trying to call the functionBZ2_bzBuffToBuffDecompress. However, when I rungcc myfile.c -o myfile.c.o, I get the following error: ``` ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 ``` I am just using a plain text editor and gcc, no IDEs and no CMake files. I suspect I may need a CMake file for this but I am not really sure how to proceed. Any assistance with this is greatly appreciated!
You need to link in the bzip library.gcc myfile.c -o myfile -lbz2. That command assumes the lib is installed into the standard location. Also, you are compiling a final executable so (by strong convention) it should not have a .o suffix.
``` $ ./main < input ``` If I were to check for new lines in python, I would open the file and then analyze the lines, but this almost seems like magic. ``` int main(){ int c, nl; nl = 0; while ((c = getchar()) != EOF) if (c == '\n') nl++; printf("%d\n", nl); return 0; } ``` How does it know to accept any input file without being stated within the code?
The<symbol in the shell is aninput redirection. It states that the contents of the given fileinputin this case, will be read as stdin. So any function such asgetcharthat reads from stdin will actually be reading from the fileinputin this case. A similar program in Python would also use functions that read from stdin instead of from a file.
This question already has answers here:What happens when I use the wrong format specifier?(2 answers)Closed2 years ago. Can you tell why this statement in C gives 0 as output ``` printf("Hello %f",-5/2); ``` Whereas ``` printf("Hello %d",-5/2); ``` is giving output as -2
Division of two integers produces a integer result (intin this case). The%fformat specifier expects an argument of typedouble. Using the wrong format specifier for a given argument triggersundefined behaviorwhich in this case gives you an incorrect result. If you want a floating point result, at least one of the operands to/must have a floating point type, i.e. ``` printf("Hello %f",-5.0/2); ```
I have ARM Cortex-M object file (.o) in which I have following code:BL $testFunc. In the same object file I can also find a implementation of thetestFunc. Can I get the absolute address that the call will be made during the program execution? I have ONLY the object file
$testFuncis an unresolved link. You have to link the object file with the C runtime and MCU initialisation code along with any other dependencies (libraries separate object modules) before an absolute address is determined. The compiler has no awareness of the memory environment of the target. The linker takes the separate object code modules and thelinker script(which defines the memory map) and resolves links and locates code and data. The linker can output a MAP file that will include the absolute addresses of all externally linker code and data items.
The size is defined as 15, but this program only runs 8 times for some reason and i don't know why. This part is the only issue. Once i removed it and replaced it with something that doesn't use ctime it ran 15 times. ``` for(int count = 0; count < size; count++) { printf("Plane ID : %d\n", planes[count].planeid); printf("Destination : %s\n", planes[count].destination); char * time_str; time_str = ctime(&planes[count].time); printf("Depart Time/Date : %s \n", time_str); count++; } ```
You increment count twice each loop: ``` for (int count = 0; count < size; count++) // ^^^^^^^ HERE { .. count++; // HERE } ``` Remove the secondcount++;on the end of function body.
I have ARM Cortex-M object file (.o) in which I have following code:BL $testFunc. In the same object file I can also find a implementation of thetestFunc. Can I get the absolute address that the call will be made during the program execution? I have ONLY the object file
$testFuncis an unresolved link. You have to link the object file with the C runtime and MCU initialisation code along with any other dependencies (libraries separate object modules) before an absolute address is determined. The compiler has no awareness of the memory environment of the target. The linker takes the separate object code modules and thelinker script(which defines the memory map) and resolves links and locates code and data. The linker can output a MAP file that will include the absolute addresses of all externally linker code and data items.
The size is defined as 15, but this program only runs 8 times for some reason and i don't know why. This part is the only issue. Once i removed it and replaced it with something that doesn't use ctime it ran 15 times. ``` for(int count = 0; count < size; count++) { printf("Plane ID : %d\n", planes[count].planeid); printf("Destination : %s\n", planes[count].destination); char * time_str; time_str = ctime(&planes[count].time); printf("Depart Time/Date : %s \n", time_str); count++; } ```
You increment count twice each loop: ``` for (int count = 0; count < size; count++) // ^^^^^^^ HERE { .. count++; // HERE } ``` Remove the secondcount++;on the end of function body.
Consider the structure below, where the sum of bitfield sizes are 64-bit. Why doessizeofsay this structure is 12 bytes, when it should be 8? ``` typedef struct wl_Ls { unsigned int total:17; unsigned int used:17; unsigned int entrySize:17; _Bool point:1; } wl_Ls; ``` [SOLUTION:] Using a 64-bit type fixes for first 2 or 3 members fixes it. Explanation is in the answer marked as Solution
Bitfields are not always guaranteed to be packed tightly together. Two of the situations where the compiler is allowed to insert padding between bitfields are: when two consecutive bitfields are not the same type, and when a bitfield doesn't fit into the number of bits that are still available in an "allocation unit" of the bitfield's type. Assumingunsigned intis 32 bits, all three pairs of consecutive bitfields in your structure qualify for at least one of those situations.
Aim - to insert an element into a struct array using recursion rather than for-loop. Error 1 at line 33 : expected expression before 'struct' Error 2 at line 33 : too few arguments to function 'insert' ``` #include <stdio.h> #include <stdlib.h> struct Array { int a[10]; int length; int size; }; void insert(struct Array *arr, int index, int n, int len) { if(len == index) { arr -> a[index] = n; } else { arr -> a[len] = arr -> a[len-1]; insert(struct Array *arr, index, n, len-1); \\ Error Line 33. } } int main() { struct Array arr = {{1,2,3,4,5},5,10}; return 0; } ```
When you call a function, don't specify the types of the parameters. Just pass them directly as you did with the last 3. ``` insert(arr, index, n, len); ```
so basically I wrote this code to print the greater number but it is not working.I am new to C and this confuses me a lot ``` #include <stdio.h> int greater(int a, int b); int main() { int a,b,x; printf("\n Enter two numbers:"); scanf("%d %d ",&a, &b); x=greater(a, b); printf("\n The greatest number is:%d", x); return 0; } int greater(int x, int y) { int great; if(x>y){ great=x; } else { great=y; } return great; }``` ```
The problem is the trailing white space inscanf, switch to: ``` printf("\n Enter two numbers:"); scanf("%d %d",&a, &b); x=greater(a, b); ``` See why:What is the effect of trailing white space in a scanf() format string?
``` #include <stdio.h> #define foo(x,y) x/y +x int main() { int i=-6,j=3; printf("%d",foo(i+j,3)); } ``` PROBLEM; this code is giving answering -8 is not it return -4 mathematically .. please explain ..help
foo(x,y)is defined asx/y +x, sofoo(i+j,3)expands toi+j/3 +i+j. Since/has higher precedence than+, this is equivalent toi + (j / 3) + i + j,notto(i + j) / 3 + i + jas you presumably intended. The best fix in this case is to not use a macro, but rather, to just write a normal function: ``` int foo(int x, int y) { return x / y + x; } ``` If, for whatever reason, that's not an option, then you need to add some parentheses: ``` #define foo(x,y) ((x) / (y) + (x)) ``` . . . but even this will give weird results if thexhas side-effects, because thexgets expanded twice, so those side-effects will happen twice. (And in some cases that will result in undefined behavior.)
Here, I have a typedef for a function pointer and then I also have a macro that points to the address 0x1234 that is of type "fptr". But I would like to know how can that macro be called with the arguments to call the resulting function? Thank you for your help. ``` #include <stdio.h> typedef void (*fptr)(int, int); // 0x1234 will be the address where the reference to fptr will exist #define FPTR_MACRO ((fptr)0x1234) void main(void){ //How should I call the FPTR_MACRO with the arguments to call that function? //FPTR_MACRO(1,1); } ```
If you insist on using macro as is, it would be ``` (*FPTR_MACRO)(1, 1); ``` But it would be easier to use if rewritten as ``` #define FPTR_CALL(x, y) ((*(fptr)0x1234)(x, y)) ``` And than used as ``` FPTR_CALL(1, 1); ```
Here, I have a typedef for a function pointer and then I also have a macro that points to the address 0x1234 that is of type "fptr". But I would like to know how can that macro be called with the arguments to call the resulting function? Thank you for your help. ``` #include <stdio.h> typedef void (*fptr)(int, int); // 0x1234 will be the address where the reference to fptr will exist #define FPTR_MACRO ((fptr)0x1234) void main(void){ //How should I call the FPTR_MACRO with the arguments to call that function? //FPTR_MACRO(1,1); } ```
If you insist on using macro as is, it would be ``` (*FPTR_MACRO)(1, 1); ``` But it would be easier to use if rewritten as ``` #define FPTR_CALL(x, y) ((*(fptr)0x1234)(x, y)) ``` And than used as ``` FPTR_CALL(1, 1); ```
I scan a process memory by injecting dll and read it's memory. The problem is that I also reads the memory of the dll. Does someone know what to do?
UseGetModuleInformation, which can accept both anHPROCESSfor your remote process and aHMODULEfor your injected DLL, and which returns the following information in aMODULEINFOstruct: ``` typedef struct _MODULEINFO { LPVOID lpBaseOfDll; DWORD SizeOfImage; LPVOID EntryPoint; } MODULEINFO, *LPMODULEINFO; ``` So you can know the start address of your injected DLL via thelpBaseOfDllfield and the end address vialpBaseOfDll + SizeOfImage. This can also work for a DLL in your current process usingGetCurrentProcessand e.g.GetModuleHandle.
I have two different structs in c file, struct A and B: ``` typedef Struct _A { float arr[4]; }A; typedef struct _B { float const x; float const y; }B; A* objA = (A*)malloc(sizeof(A)); B* objB = (B*)malloc(sizeof(B)); ``` what I need to do is assign arr values with values from struct B ``` objA->arr = {objB->x, objB->y, objB->x, objB->x}; /// getting an error here : expression must be a modifiable lvalue. ``` I have memcpy so far, but that ends in another error "expression expected". is there any way to do this? Thanks in advance!
You can't assign to an array directly. You'll need to either assign to each member individually: ``` objA->arr[0] = objB->x; objA->arr[1] = objB->y; objA->arr[2] = objB->x; objA->arr[3] = objB->x; ``` Or usememcpywith a compound literal as the source: ``` memcpy(objA->arr, (float[4]){objB->x,objB->y,objB->x,objB->x}, sizeof(float[4])); ```
I've been working with some C code and I would like to know what the difference is between next codes: ``` double myArray[5] = {0,0,0,0,0}; ``` and ``` double myArray[5]; memset(myArray,0,5*sizeof(double)); ``` Could there be a problem for replacing the second one with the first one? If so, what kind of problems might be?
Usingmemsetthis way makes assumptions regarding the representation of floating point numbers, specifically that the representation of all bits 0 corresponds to the value 0. If your system uses IEEE754 floating point representation (as are most systems you're likely to come across) this assumption holds. However, if you find yourself running your code on some exotic system that does not, then you might not get the result you expect.
I am trying to make a program to calculate the area of a rectangle but the function doesn't return any value This is the code as in cs50 sandbox ``` #include <stdio.h> #include <cs50.h> int calcrectarea(int len,int wid){ return len*wid; } int main(){ printf("enter length here:\n"); int x; scanf("%d",&x); printf("enter width here:\n"); int y; scanf("%d", &y); calcrectarea(x,y); } ```
Actually, the function returns a value. Maybe you want to see it, so just print the result: ``` #include <stdio.h> #include <cs50.h> int calcrectarea(int len,int wid){ return len*wid; } int main(){ printf("enter length here:\n"); int x; scanf("%d",&x); printf("enter width here:\n"); int y; scanf("%d", &y); printf("area is: %d", calcrectarea(x,y)); } ```
lldb by default shows assembly code unless I use breakpoints (withbreakpoint set -f file.c -l xx) where it shows source on runningnext. In gdb I can uselayout srcto switch to source mode, how can I switch to source mode in lldb?
There are a couple settings you need to switch to do this. I made a little Python command to coordinate toggling them back & forth here: https://github.com/llvm/llvm-project/blob/main/lldb/examples/python/disassembly_mode.py You can put that in your ~/.lldb directory and in your ~/.lldbinit do: command script import ~/.lldb/disassembly_mode.py That will give it the name toggle-disassembly, but you can call it anything you want by changing the last line in the .py file.
In below code, I declared a binary linked listNode *node = NULLin functionmain, and intended to create a node in functionTest. After that,nodeis stillNULL. Why? ``` #include <stdlib.h> typedef struct Node { int value; struct Node *left, *right; } Node; int Test(Node* node) { node = malloc(sizeof *node); node->value = 1; node->left = NULL; node->right = NULL; return 0; } int main() { Node* node = NULL; Test(node); if(node) { putchar('0' + node->value); } else { putchar('n'); } free(node); return 0; } ``` Why this code printsninstead of1?
This is because argument is passed by value. So, when you are passing node as argument to function, the actual NULL value is getting passed and any changes made to that value will not affect the node variable outside the function.
I write the following code and I expect that the data race would occur because of several thread may modifyaat the same time and get a wrong answer. ``` // test.c #include <stdio.h> #include <stdlib.h> int main(void) { int a = 0; #pragma omp paralle for for (int i = 0; i < 10000000; i++) { a = a + 1; } printf("a = %d\n", a); // correct answer = 10000000 return 0; } ``` But the output seems correct: ``` $ gcc test.c -std=c99 -fopenmp $ ./a.out a = 10000000 ``` I have executed it for several times and it always gave me correct answer.Why there is no data race occur? Is it just a coincide?(I know that I should usereductionbut I just wonder why it still work well withoutreduction.)
You've written#pragma omp paralle forwhen you meant#pragma omp parallel for(noticeparallelinstead of paralle). If you fix this then you'll see your data race.
The documentaions says AV_PIX_FMT_NV12 planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V) also linesize[1] and linesize[0] are 1920, but if I strlen(data[1]) ( UV components ) I get 1044587 this divided by the frame->heigth gives me 967,21... so the linesize is wrong?
It's 8 bits per channel, so uint8_t is correct. The "12 bits per pixel" comes from 8 bits Y + 2 bits U (8 bits for every 4 pixels) + 2 bits V (8 bits for every 4 pixels) = 12 bits per pixel on average. This is also why the UV plane is half as many bits as the Y plane; it's U+V data, but only for 1/4 of the pixels.
Does Linux have any way to obtain a milli or microsecond precision time for boot time, for converting boot time-relative timestamps into something like a Unix timestamp? The closest I've found is/proc/uptime(as suggested in places likethis answer), but unfortunately this only gets you to 10ms precision best-case. For context, I've got a camera being used with v4l that provides microsecond precision timestamps, but they're in time since boot. I need to convert these to Unix timestamps as they're being sent to another computer. Is this a hard thing to provide in some way that I'm unaware of? And if so, why do so many things use time since boot?
Useclock_gettime(CLOCK_BOOTTIME, &ts).
Does Linux have any way to obtain a milli or microsecond precision time for boot time, for converting boot time-relative timestamps into something like a Unix timestamp? The closest I've found is/proc/uptime(as suggested in places likethis answer), but unfortunately this only gets you to 10ms precision best-case. For context, I've got a camera being used with v4l that provides microsecond precision timestamps, but they're in time since boot. I need to convert these to Unix timestamps as they're being sent to another computer. Is this a hard thing to provide in some way that I'm unaware of? And if so, why do so many things use time since boot?
Useclock_gettime(CLOCK_BOOTTIME, &ts).
I have a string in C++ called temp and currently curious how that string could be represented in C. Unsure if it would constitute being a pointer or using an array. ``` string temp = ""; //c++ code char * temp; //c code ```
C doesn't have a native modifiable string class, so there's no simple parallel. If you want a modifiable buffer, you'll needchar temp[n] = "";(fixed size, automatic storage) orchar *temp = malloc(n); temp[0] = 0;(resizable, in heap). If you have no intention of changing the string, you can useconst char *temp = "";. (You can still changetemp, just not the string it points to.)
I have some large structure (> 64bytes), can I assure that each struct begins at a separated cacheline? Or is there some way to enforce that?
The C standard provides_Alignof (constant-expression)to request extra alignment. For a structure, apply it to the first element: ``` struct MyTag { _Alignas(64) char x[10]; }; #include <stdio.h> int main(void) { printf("%zu\n", _Alignof (struct MyTag)); // Prints 64. } ``` This requires that you have the cache line size as a compile-time constant. Compilers are not required to support extended alignments but will diagnose if the requested alignment is too large. If accepted by the compiler, this will provide the requested alignment for objects allocated by the compiler. However,mallocmight return addresses without the desired alignment. For this, usestruct MyTag *p = aligned_alloc(64,size);, wheresizeissizeof *pfor one structure orN* sizeof *pforNstructures.
I faced with some strange (for me) code in Linux kernel sources. There isxt_register_target()function: ``` int xt_register_target(struct xt_target *target) { u_int8_t af = target->family; mutex_lock(&xt[af].mutex); list_add(&target->list, &xt[af].target); mutex_unlock(&xt[af].mutex); return 0; } EXPORT_SYMBOL(xt_register_target); ``` This is an API function. So it seems that it must have some obvious (for API user) reason for the value it returns. But this function has no variability - it always returns 0. So basically it isvoid.What is the reason for such API coding pattern? Is this best practice or a mistake?
Digging into the git history, it seems this function did previously have failure conditions but those conditions were later removed inthis commit. So it made sense to keep the function's implementation the same to prevent changes to calling functions.
So the problem is to solve this: 1 + x + x^2/2! + x^3/ 3! +.... x^n/n! And, this is what i have done so far. ``` float sum(int x, int n) { float sum = 1; int fact, temp; for (int i= 1; i<=n; i++) { fact =1; //Caculate N! for (int j=1; j<n; j++) { temp = j; fact = fact *temp; } //Caculate X^N/N! sum += pow(x,i)/fact ; } return sum; } ``` But when i try N = 4, X= 2 it should be 7, instead it was 9.
You can do this: ``` #include<math.h> #include<iostream> using namespace std; float sum(int x, int n) { float sum = 1; int fact = 1, temp; for (int i= 1; i<=n; i++) { fact*=i; //Caculate X^N/N! sum += pow(x,i)/fact ; } return sum; } int main(){ cout<<sum(2,4)<<endl; return 0; } ```
My Code:- ``` #include<stdio.h> struct Demo{ int value; }; int main(){ struct Demo *l; l->value=4; } ``` Getting Segmentation fault (core dumped)
because L object doesn't point something. use this : ``` #include <iostream> using namespace std; struct Demo { int val; }; int main() { Demo* a = new Demo(); a->val = 10; cout<<a->val; } ```
``` #include <stdio.h> int main() { typedef int x[2]; x myArray[3] = {1, 2, 3, 4};//line 1 printf("\n%u", sizeof(myArray)); //line 2 printf("\n%d", myArray[1][0]);//line 3 return 0; } ``` Output : 24 3 Can anyone explain how line 3 gives output 3
typedef int x[2]; x myArray[3] = {1, 2, 3, 4}; is the same as ``` int myarray[3][2] = { {1, 2}, // myarray[0][0], myarray[0][1] {3, 4}, // myarray[1][0], myarray[1][1] {0, 0}, // myarray[2][0], myarray[2][1] }; ```
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'm tying to convert aMFRC522arduino chip to an USB device so as to use it natively on windows (with a cli or software) and without an Arduino. I don't know if I was clear (sorry for my bad english). Can anyone help me to do this.
No, you can't do that because you need some mediation between the RFID reader and the PC USB port. You don't have to use Arduino, but you do need a processor to "translate" the information from the reader and some hardware to speak to USB.
This question already has answers here:How do function pointers in C work?(12 answers)Closed2 years ago. There is the following code declaration: ``` int (*oled_format)(unsigned short F_gfx, unsigned char* oled_data, size_t oled_len, ...); ``` used in situations such as below: ``` format_rc = display_port->dev->oled_format(cmd, oled_data, cmd_len, color); ``` What does this do? Clearly it returns an int, but there does not seem to be any function description outside of the header file. Googling brought me to some C++ docs about explicit instantiation which are not very clear and sometimes vary syntactically:1, and2
It's the declaration of a function pointer. For those who are interested, the following StackOverflow answer explains how C's function pointers work: How do function pointers in C work?
Can anyone explain why the program is returning this error ?? (The Process returned -1073741819 (0xC0000005) ) ``` #include <stdio.h> void main() { void what(int A[]) { int i=0,j=0; int temp=0; for(int i=1;i<5;i++) { j=i-1; while(j>=0 && A[j]>A[j+1]) { temp=A[j]; A[j]=A[j+1]; A[j+1]=temp; j+j-1; } } for(int k=0;k<=4;k++) printf(A[k]); } int S[5]={20,10,20,30,15}; what(S); } ```
your program works correctly in sorting if you fix the problem at the time of initialization variablej ``` j = j-1; ``` also print the array elements like following: ``` printf("%i ", A[k]); ``` use above statement to print array element.
``` #include<stdio.h> void main() {int a=12,b=7; if(!a>=20) //this is the part can't identify b>>1; printf("b=%d",b);} ``` What does mean If(!a>=20) in C this programme?
The expression!a >= 20is the same as(!a) >= 20. And!is the logical-not operator. Ifais "true" (which all non-zero values are) then!awill befalse. Andfalseis implicitly convertible to theintvalue0(andtrueto1). So what the expression is doing is checking ifais "true" or "false" and compare the0or1result of that with the integer value20. And as both0and1are smaller than20the condition will befalse.
In C code I have a next structure: ``` typedef struct foo_s { int var_int; int arr_int[20]; }foo; ``` In particular stage I define afoopointer: ``` foo* struct_var = (foo*)malloc(sizeof(foo)); ``` In memory clear stage I have free(stuct_var) The question: Should I before the last statement explosively free array as ``` free(stuct_var->arr_int) ``` ?
Thearr_int[20]is a part of struct, you don't need to free it respectively. That is what are allocated bymalloc/calloc/reallocthey need to be cleaned up to avoid memory leak issue. Anyway if you make the inner array dynamic, then you will have to free it. ``` typedef struct foo_s { int var_int; int* arr_int; }foo; foo* struct_var = (foo*)malloc(sizeof(foo)); struct_var->arr_int = (int*)malloc(20 * sizeof(int)); ```
This question already has answers here:How do function pointers in C work?(12 answers)Closed2 years ago. There is the following code declaration: ``` int (*oled_format)(unsigned short F_gfx, unsigned char* oled_data, size_t oled_len, ...); ``` used in situations such as below: ``` format_rc = display_port->dev->oled_format(cmd, oled_data, cmd_len, color); ``` What does this do? Clearly it returns an int, but there does not seem to be any function description outside of the header file. Googling brought me to some C++ docs about explicit instantiation which are not very clear and sometimes vary syntactically:1, and2
It's the declaration of a function pointer. For those who are interested, the following StackOverflow answer explains how C's function pointers work: How do function pointers in C work?
Can anyone explain why the program is returning this error ?? (The Process returned -1073741819 (0xC0000005) ) ``` #include <stdio.h> void main() { void what(int A[]) { int i=0,j=0; int temp=0; for(int i=1;i<5;i++) { j=i-1; while(j>=0 && A[j]>A[j+1]) { temp=A[j]; A[j]=A[j+1]; A[j+1]=temp; j+j-1; } } for(int k=0;k<=4;k++) printf(A[k]); } int S[5]={20,10,20,30,15}; what(S); } ```
your program works correctly in sorting if you fix the problem at the time of initialization variablej ``` j = j-1; ``` also print the array elements like following: ``` printf("%i ", A[k]); ``` use above statement to print array element.
``` #include<stdio.h> void main() {int a=12,b=7; if(!a>=20) //this is the part can't identify b>>1; printf("b=%d",b);} ``` What does mean If(!a>=20) in C this programme?
The expression!a >= 20is the same as(!a) >= 20. And!is the logical-not operator. Ifais "true" (which all non-zero values are) then!awill befalse. Andfalseis implicitly convertible to theintvalue0(andtrueto1). So what the expression is doing is checking ifais "true" or "false" and compare the0or1result of that with the integer value20. And as both0and1are smaller than20the condition will befalse.
In C code I have a next structure: ``` typedef struct foo_s { int var_int; int arr_int[20]; }foo; ``` In particular stage I define afoopointer: ``` foo* struct_var = (foo*)malloc(sizeof(foo)); ``` In memory clear stage I have free(stuct_var) The question: Should I before the last statement explosively free array as ``` free(stuct_var->arr_int) ``` ?
Thearr_int[20]is a part of struct, you don't need to free it respectively. That is what are allocated bymalloc/calloc/reallocthey need to be cleaned up to avoid memory leak issue. Anyway if you make the inner array dynamic, then you will have to free it. ``` typedef struct foo_s { int var_int; int* arr_int; }foo; foo* struct_var = (foo*)malloc(sizeof(foo)); struct_var->arr_int = (int*)malloc(20 * sizeof(int)); ```
``` #include <stdio.h> int main() { int number = 08; printf("%d",number); return 0; } ``` or if it's invalid then why?
For the purposes of the problem you are solving on Project Euler, the leading0's in that matrix are just decorative padding, not meant to be interpreted as octal or anything else. So if you are putting together an array/matrix of numbers in your code, just drop the leading zeros from the input set you are copying from. For example, instead of this hypothetical declaration: ``` int row1[] = {08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08}; ``` Just change your code declaration to be: ``` int row1[] = {8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8}; ``` That's all you have to do.
``` int main(){ int fd = open("aaaaaa.txt", O_CREAT | O_RDWR, 0666); write(fd, "a", 1); system("more aaaaaa.txt"); unlink("aaaaaa.txt"); close(fd); return 0; } ``` I want to ask why this data is written to the file immediately(by 'more' I can see this), instead of being directly written to the kernel page cache(not really write in file) and after a period of time,then page cache be really written to file by flusher thread .
It is written to the kernel page cache. Andmorereads from the kernel page cache. The kernel page cache is shared by all processes, because it is in the kernel.
why my code is not printing all values of the array? ``` #include<stdio.h> #include<conio.h> int main() { int arr[5]={1,2,3,4,5}; int *a; a=&arr[0]; int i=0; for(i=arr[i];i<5;i++){ printf("%d",*a); a=a+1; } } ```
I guess this is homework, correct? Check the index of your loop. What you want to do is that yourforloops five times, regardless of the content of your array.
How to set the make file or my project so that during the build process it automatically creates a log file from the output of compiler errors and messages for c or c++ projects.
Its just i/o redirection and you can do it in many different ways. Appendeach error after compiling that file in makefile.@gcc -c file1.c 2>> error.logAs Martin york has said,make | tee log These are just some ways I can think of now. Do go throughthis guidefor learning on I/O redirection.
This question already has answers here:How "a<b<c" or "a>b>c" are evaluated in C(2 answers)Chaining multiple greater than/less than operators(6 answers)Compound condition in C: if (0.0 < a < 1.0)(4 answers)Closed2 years ago. The following code supposed to print true. But it is printing false. Does anyone know why is it so? ``` int main(void) { int a=15,b=10, c=1; if(a>b>c) { printf("true"); } else { printf("false"); } } ```
In C,a>b>cmeans(a>b)>c. It doesnotmean(a>b)&&(b>c). The value ofa>bis either 0 or 1 (false or true, respectively). Sincecis 1, neither of those possible values can be greater thanc, so the comparison is always false.
Input is like the image above. We have to take the input and add it in an array until there is no comma on the end. Thanks in advance.
Assuming you type the given line2,3,4,5,6and press enter to take input, you can easily take input with comma as ending factor with the help offgets()andstrtok()functions. ``` #include<stdio.h> #include<string.h> #include<stdlib.h> #define MAX_SIZE 100 int main(){ char buffer[512]; fgets(buffer, 512, stdin); int arr[MAX_SIZE], index=0; char* temp = strtok(buffer, ",\n"); while(temp!=NULL){ int x = atoi(temp); arr[index]=x; index++; temp = strtok(NULL,",\n"); } printf("The output is:\n"); for(int i=0; i<index; i++) printf("%d ",arr[i]); printf("\n"); return 0; } ``` How strtok() function works How fgets() function works
I'm having problems compiling LANShare's sourcecode.I need to compile this program because i need to use it on a 32-bit unix machine and there's no.deborappimagerelease file. This isLANShare. As you can see there's no config file and i don't know how i can proceed with compilation.I compiled from source many times but here there's no Readme nor instructions, then I opened anissuebut there's no response yet.
Found a solution, thanks ton. 1.8e9-where's-my-share m.Theese instructions should be valid for any Debian 10 install. To install qt tools: ``` sudo apt install qt5-qmake qt5-default ``` then to compile: ``` qmake -o Makefile LANShare.pro make ```
Why 10.5 become 10.0 after swap ? ``` #define swap(a,b) {int aux; aux=a; a=b; b=aux;} float x=10.5, y=3.75; swap(x,y); // x=3.75, y=10.0; ```
auxis of typeint, which will drop the decimal part of the argumentapassed toswap. In this case,swap(x, y)drops the decimal part ofxbefore it is assigned toyat the end.
I have opened a socket viaconnectand want to be able to read results blocking and write non-blocking. My current solution is to set the file descriptor to be non-blocking and thenselectwhen I do aread. It would be simpler instead to do something like ``` int sock = socket(...); connect(sock, ...); int reader = dup(sock); int writer = sock; fcntl(writer, F_SETFL, fcntl(writer, F_GETFL) | O_NONBLOCK); ``` Does the call tofcntlcause bothreaderandwriterto be non blocking (it sets it on the I/O object) or doesfcntlset non-blocking on the file descriptor?
If you read thefcntlman page carefully, you see the status flags are associated with afile description, not a file descriptor. Anddupsays the new and old file descriptorrefer to the same file description. So accesses toreaderandwritershould both be non-blocking.
I'm having problems compiling LANShare's sourcecode.I need to compile this program because i need to use it on a 32-bit unix machine and there's no.deborappimagerelease file. This isLANShare. As you can see there's no config file and i don't know how i can proceed with compilation.I compiled from source many times but here there's no Readme nor instructions, then I opened anissuebut there's no response yet.
Found a solution, thanks ton. 1.8e9-where's-my-share m.Theese instructions should be valid for any Debian 10 install. To install qt tools: ``` sudo apt install qt5-qmake qt5-default ``` then to compile: ``` qmake -o Makefile LANShare.pro make ```
Why 10.5 become 10.0 after swap ? ``` #define swap(a,b) {int aux; aux=a; a=b; b=aux;} float x=10.5, y=3.75; swap(x,y); // x=3.75, y=10.0; ```
auxis of typeint, which will drop the decimal part of the argumentapassed toswap. In this case,swap(x, y)drops the decimal part ofxbefore it is assigned toyat the end.
I have opened a socket viaconnectand want to be able to read results blocking and write non-blocking. My current solution is to set the file descriptor to be non-blocking and thenselectwhen I do aread. It would be simpler instead to do something like ``` int sock = socket(...); connect(sock, ...); int reader = dup(sock); int writer = sock; fcntl(writer, F_SETFL, fcntl(writer, F_GETFL) | O_NONBLOCK); ``` Does the call tofcntlcause bothreaderandwriterto be non blocking (it sets it on the I/O object) or doesfcntlset non-blocking on the file descriptor?
If you read thefcntlman page carefully, you see the status flags are associated with afile description, not a file descriptor. Anddupsays the new and old file descriptorrefer to the same file description. So accesses toreaderandwritershould both be non-blocking.
``` #include <stdio.h> #include <stdlib.h> int main() { float n; scanf("%f", &n); printf("%.3f", n); } ``` input:51444.325061 my output:51444.324 expected output:51444.325 why does I dont get the proper answer?
32-bitfloatcan encode about 232different values. 51444.325061is not one of them**. Instead the nearestfloatis exactly 51444.32421875. The next best choice would be 51444.328125. Printing 51444.32421875 to 3 decimal places is best as "51444.324". why does I dont get the proper answer? floatis too imprecise to encode 51444.325061 as OP desires. Usingdoublewill help. The same problem exists, yet only appears when about 16+ significant digits are needed. **Encodable finite values are of the form: some_integer * 2some_exponent.
Using GCC, I want to define a function pointer to a specific address, like this: ``` void (*fptr)(void) = 0x00400000; ``` Unsurprisingly, that throws a warning ``` Warning: initialization makes pointer from integer without a cast [-Wint-conversion] ``` I tried to cast the right-hand side like ``` void (*fptr)(void) = ((*)(void))0x00400000; ``` but that yields a syntax error. How can I cast this correctly so that the warning will go away?
You are missing the return type in the cast. It should be: ``` void (*fptr)(void) = (void (*)(void)) 0x00400000; ```
As the title says, what is the reason you free memory that you allocated using malloc, but never free memory allocated to a variable like an integer?
The compiler allocate space for local variables on the stack just by moving the stack pointer with the space needed for the variables. Before return, the stack is restore. When you callmalloc, the memory space is allocated in a so called theheap. Theheapis managed to keep allocated blocks untilfreeorreallocis called.
I've foundthisandthisand a few others but none really answer my question. Ive done: while ( *arr ) while ( *arr[i] != '\0' ) but i don't know if there's a better way
The first one is checking if the list of strings ends in a NULL pointer; the second is checking if the list of strings ends in an empty* string. *I'm making an assumption here thatiis zero; else this question makes no sense. Using NULL as the terminator of a list of strings is always the faster API design both for the creator of the list and the consumer of the list. Alternatively, you meant to ask ifwhile (*arr)is faster or slower thanwhile (*arr != '\0'). If your compiler isn't truly ancient these compile to the same thing so it makes no difference. Do whatever's easier to read.
Using GCC, I want to define a function pointer to a specific address, like this: ``` void (*fptr)(void) = 0x00400000; ``` Unsurprisingly, that throws a warning ``` Warning: initialization makes pointer from integer without a cast [-Wint-conversion] ``` I tried to cast the right-hand side like ``` void (*fptr)(void) = ((*)(void))0x00400000; ``` but that yields a syntax error. How can I cast this correctly so that the warning will go away?
You are missing the return type in the cast. It should be: ``` void (*fptr)(void) = (void (*)(void)) 0x00400000; ```
As the title says, what is the reason you free memory that you allocated using malloc, but never free memory allocated to a variable like an integer?
The compiler allocate space for local variables on the stack just by moving the stack pointer with the space needed for the variables. Before return, the stack is restore. When you callmalloc, the memory space is allocated in a so called theheap. Theheapis managed to keep allocated blocks untilfreeorreallocis called.
I've foundthisandthisand a few others but none really answer my question. Ive done: while ( *arr ) while ( *arr[i] != '\0' ) but i don't know if there's a better way
The first one is checking if the list of strings ends in a NULL pointer; the second is checking if the list of strings ends in an empty* string. *I'm making an assumption here thatiis zero; else this question makes no sense. Using NULL as the terminator of a list of strings is always the faster API design both for the creator of the list and the consumer of the list. Alternatively, you meant to ask ifwhile (*arr)is faster or slower thanwhile (*arr != '\0'). If your compiler isn't truly ancient these compile to the same thing so it makes no difference. Do whatever's easier to read.
Let's imagine I have ``` String x = "hello there"; ``` So I can print it from index e.g. 1 as: ``` Serial.println(x.substring(1)); ``` ello there I wanna do the same with ``` char x[] = "hello there"; ``` Any ideas?(Except using loops to print char by char)
You can use the & operator to get the string after the desired index like this: ``` Serial.println(&x[1]); ```
I'm working on an embedded project. I wantprintfto work with UART port. I did some google and some people suggest thatprintfcallsfputcand I needs to supply function definition offputcto work with UART port. Other people suggest_writeinstead. I am assuming thatprintfcallsfputc, which then calls_write? What I want to ask is, does the C standard define anything about this? (Is it guaranteed thatprintfcallsfputc?)
C spec doesn't define anything about this aside fromprintf()functions as if it calledfputc()multiple times. It is not guaranteed thatprintfcallsfputc. I want printf to work with UART port. Consider instead writing your ownUART_printf()that callsvsprintf()and then sends the string out to the UART.
why my program did not go in infinite loop. I have not used'\0'for testing string end in while loop, instead of that I have use0. Does'\0'and0same in C? If yes, then if0is in the middle of a string, thenprintfshould end printing the string right there. e.g.printf("%s", "hello how0 are you")should print'hello how' ``` int main( ) { char s[ ] = "No two viruses work similarly" ; int i = 0 ; while ( s[i] != 0 ) { printf ( "%c", s[i]) ; i++ ; } } ```
'\0'has the same meaning as0, but'0'doesn't have the same meaning as0. printf("%s", "hello how0 are you")will printhello how0 are you. printf("%s", "hello how\0 are you")will printhello how.
I am trying to invoke thesystem()command twice in one line. When compiling the code it does not seem to like the second instance ofsystem()which is used to execute a script usingawkoutput. Code snippet: ``` int main() { system("lsusb | sudo awk '/Terminus.*Hub$/{ system("/usr/bin/usbreset " $6) }'"); } ``` As you can see in the code interpreter/usr/bin/usbresetis no longer declared as a string and is causing the compilation error.
You need to escape the inner quotes. Try: ``` "lsusb | sudo awk '/Terminus.*Hub$/{ system(\"/usr/bin/usbreset \" $6) }'" ```
After entering any values ofp,n,r; the value ofiis only returning 0.0000. ``` int main() { int p,n; float r,i; i=p*n*r/100; printf("enter principle=\n"); scanf("%d",&p); printf("enter rate=\n"); scanf("%f",&r); printf("enter no.of years=\n"); scanf("%d",&n); printf("value of i=%f",i); return 0; } ```
The variablep, n, rare not initialized at the linei=p*n*r/100;. You have to do the calculationafterreading the values. ``` int p,n; float r,i; printf("enter principle=\n"); scanf("%d",&p); printf("enter rate=\n"); scanf("%f",&r); printf("enter no.of years=\n"); scanf("%d",&n); i=p*n*r/100; /* do calculation after reading values */ printf("value of i=%f",i); ```
According to the answer key, the answer is O(N). I didn't have enough time to see it carefully. I thought it was i++ and not i/=2 in the first loop so I wrote O(N^2). But now I am not sure what is the correct. I think it should be O(log n * log n). Code: ``` int count = 0; for (int i = N; i > 0; i /=2) for (int j = 0; j < i; j++) count++; ``` Image:
At the first iteration of the outer loop, the inner loop is performed N timesAt the second iteration, the inner loop is performed N/2 timesAt each subsequent iteration, the inner loop is performed half as many times as in the previous iteration The total number of iterations is equal to N + N/2 + N/4 + ... + 1, which is approximately equal to 2N. Therefore, the total number of iterations is O(N)
I am trying to update environment variables for VS 22 & vs code for using python and C but am unable to update it . It requires them all under same name but it fails every time. how can I fix it?
I expect that you have addedD:\python\Scripts\;D:\python\;D:\vs code\Microsoft VS Code\bin;something like this...but wait, you haven't configured the user interface. Add this somewhere in list%USERPROFILE%\AppData\Local\Microsoft\WindowsApps;and it will work.
I need help understanding how the expression below should be interepted, because I have no clue. help please. ``` Expression: 11U/22L*(3.75F-2)+3./6+.25/1.F; Choices: A) 0.5 B) 0.25 C) 0.0 D) 0.75 ```
U: unsigned intL: long intF: float integral literal: [signed] intFP literal (without suffix f/F): double 11U / 22L * (3.75F - 2) + 3. / 6 + .25 / 1.F-> unsigned / long * (float - int) + double / int + double / float Now, we need an understanding ofoperator precedenceandtype promotion (conversion). Then the expression evaluates to: unsigned / long -> promoted to long*(float - int) -> promoted to float+double / int -> promoted to double+double / float -> promoted to double Put the values in: 11U / 22L -> 0L*(3.75F - 2) -> 1.75F+3. / 6 -> 0.5+.25 / 1.F -> 0.25 => 0L * 1.75F + 0.5 + 0.25 => 0F + 0.5 + 0.25 => 0.5 + 0.25 =>(double) 0.75