question
stringlengths
25
894
answer
stringlengths
4
863
This question already has answers here:What is “two's complement”?(24 answers)Closedlast year. I am new to c. My Question. Why do some numbers end up negative when the value was positive?
Here is an explanation for the output you are seeing. 1000 in binary is 1111101000 (10 bits) and is stored in anint(signed 32 bits) When you cast that to anunsigned char(that has 8 bits), the top bits get "cut off". So you get:11101000which is232in decimal. As a (signed) char, the bits get interpreted as a negative number because the first (sign) bit is set, which in this case is -24. When you remove the sign bit,1101000=104 The "value" of the MSB is 128, so your computer does104 - 128 = -24. (Seehttps://en.wikipedia.org/wiki/Two%27s_complement) A long has the same or more bits as an int so the value does not change.
Is there a way to see what's inside the stdio.h or how it's implemented? I learned that the standard functions are declared in the stdio.h file and I can't find it in my computer plus I heard that there is another file where the body of the functions are all written, which is called the stdio.c file. Can anyone tell me WHERE this file is in my computer (I am using gcc compilier) or anyway to see how it is implemented?
As far as I know the c++ header files are stored inC:\Program Files (x86)\Windows Kits\10\Include\"some_version"\ucrtfor Windows, and in/usr/includefor linux. There you can find thestdio.hfile and any other of the standard c++ header files. Otherwise looking on the internet forstdio.hsource code is also an option
On Linux, the pseudo-code looks roughly like this: ``` setup_env(); pid = fork(); if (pid == 0) { // we are the child closeUnusedPipeEnd(); setup_child(); execve(); } closeOtherUnusedPipeEnd(); ``` posix_spawn uses file_actions to register what the child process would do in spawnp, which boils down to a clone() instead of fork(). However, I do not find Windows examples for how to close the unused end of the anonymous pipe in the child process. Is my only option to do this inside the child process, for example via stdin parsing or environment variables? Or what is considered best practice in Windows for anonymous pipes? The pipe handles are assumed to be created fromkernel32.CreateNamedPipeWandkernel32.CreateFileWand read handle foroverlapped IO(FILE_FLAG_OVERLAPPED).
One should usekernel32.SetHandleInformation()withHANDLE_FLAG_INHERITto only inherit the pipe end used in the child process.
So I am writing a program that uses text files. I have a line of code that goes like this. ``` pfw = fopen(fileName, "w"); ``` I am trying to make that program to create a txt file in this relative path ``` ./TextFiles/ ``` I have no idea how to implement a fileName variable in the file path. I usually do it like this when I have static fileName and program doesn't ask me to give it a file name or where fileName is not a variable and it works. ``` pfw = fopen("./TextFiles/fileName.txt", "w"); ```
#definethe relative path if configuration files are not being used ``` #define BASE_DIR "./TextFiles/" char* finalName = malloc (strlen(BASE_DIR) + strlen(fileName) + 1); if (!finalName) { /* error handling */ } sprintf (finalName, "%s%s", BASE_DIR, fileName); FILE* pfw = fopen(finalName, "w"); /* ... */ // free after usage free (finalName); ```
I have a simple floating-point glib variant object whose value I need to update, but there doesn't seem to be any functions to actually do that. The only way seems to be to create a new variant object and update all places that have references to this object. The problem is that it's practically hard to impossible to update the references, and it would be much easier to just set the value inside the already existing variant object. Is it even possible?
No,GVariantis immutableafter construction by design. This makes it safe to use across multiple threads. The only way to update the value of aGVariantis to create a newGVariantwith the new value.
So I have this script and I want to replace printed "Dont" with "Lets". I don't want to use system() since the effect is different. ``` #include <stdio.h> int main(){ printf("Dont do this"); /* Replace printed "Dont" with "Lets" */ return 0; } ```
Try\r: ``` #include <stdio.h> int main(){ printf("Dont do this"); printf("\rLets"); printf("\n"); return 0; } ```
Considering the following code snippet. ``` for (int state = 1; state < 1 << n; state ++ ) if (state & 1) for (int t = state; t; t &= t - 1) ``` The first for-loop is to enumerate all subsets of n elements, but what subset does thetrepresent.
``` for (int t = state; t; t &= t - 1) ``` This loop is removing the least-significant1bits fromt, one by one. So an initial value ofstatelike 63 (binary111111) would go to 62 (111110), then 60, (111100), 56 (111000), 48 (110000), 32, (100000), and finally 0.
I'm a new student in the field of coding. I'm trying to understand the concept of array. I wrote a code for sort an array. I will attach my code with this. Please describe what is the mistake on it. ``` #include<stdio.h> void main(){ int a[5]={25,3,4,56,2}; int i,j,temp; for(i=0;i<5-1;i++){ for(j=1;j<5;j++){ if(a[i]>a[j]){ temp=a[i]; a[i]=a[j]; a[j]=temp; } } } for(i=0;i<5;i++){ printf("%d ",a[i]); } } ``` The output: 2,25,56,3,4 in this order.
The problem is with this line: ``` for(j=1;j<5;j++){ ``` Change it to: ``` for(j=i+1;j<5;j++){ ``` Otherwise it will swap previously sorted elements. The fixed version starts looking at the first elementafterthe one being processed.
I have a C code, When I run the code, different symbols appear where there should be underscores. ``` int main(void){ char matrix[32][63]; int i,j; for(i=0;j<32;i++){ for(j=0;j<63;j++){ matrix[i][j]='_'; } } int n; printf("Enter number of iteration: "); scanf("%d",&n); fillOnes(matrix,0,31,32,n); for(i=0;i<32;i++){ for(j=0;j<63;j++){ printf("%c",matrix[i][j]); } printf("\n"); } return 0; } ``` why am i getting output like this instead of underscore and how can i fix it.
As explained in the comments by @Sedenion Your loop intializing your matrix has an error. ``` int i,j; for(i=0;j<32;i++) { for(j=0;j<63;j++) { matrix[i][j]='_'; } } ``` Do you see anything wrong here? :)
I have the following code, if I change "W" for "Wb" it works identical, Why? ``` void wrte (){ //tpeDta roundLotSze[] = {65,66,67,68}; tpeDta roundLotSze[] = {66,65,6767,75}; FILE * fle = fopen(".//bse//fleNmber.dat", "w"); fwrite(&roundLotSze,sizeof(roundLotSze),1,fle); fclose(fle); } ``` It looks like the parameter forfopendoesn't work. Just using these functions change the behavior of writing data and the output. What is the reason behind this behavior?
The difference is how newlines are read / written. On Linux or other UNIX-like systems, there is no difference between"w"and"wb". On Windows using"w", writing a byte with the value 10 will result in two bytes with values 13 and 10 being written. This is due to newlines on Windows being represented by both a carriage return (ASCII 13) and a linefeed (ASCII 10), while on UNIX-like systems a newline is just linefeed.
``` #include <stdio.h> int main() { int i; int j; int k; for(i = 1, j = 0, k = 3 ; i <= 5, j <= 6, k > 1 ;i++, j++, k--); { printf("%d%d%d", i, j, k); } } ``` Why is this program printing 321 instead of 212? I get 321 when I execute the program but I think it should be 212. I cannot understand why it is printing 321.
That's because you have a semicolon at the end of theforloop, so the code runs essentially like this: ``` // first you increment i,j and decrement k until k is 1, so twice for(i = 1, j = 0, k = 3 ; i <= 5, j <= 6, k > 1 ;i++, j++, k--) {} // then you print the values printf("%d%d%d", i, j, k); ```
``` #include <stdio.h> int main() { int i; int j; int k; for(i = 1, j = 0, k = 3 ; i <= 5, j <= 6, k > 1 ;i++, j++, k--); { printf("%d%d%d", i, j, k); } } ``` Why is this program printing 321 instead of 212? I get 321 when I execute the program but I think it should be 212. I cannot understand why it is printing 321.
That's because you have a semicolon at the end of theforloop, so the code runs essentially like this: ``` // first you increment i,j and decrement k until k is 1, so twice for(i = 1, j = 0, k = 3 ; i <= 5, j <= 6, k > 1 ;i++, j++, k--) {} // then you print the values printf("%d%d%d", i, j, k); ```
What are the different ways to find the number of elements in a int array pointer which is allocated with malloc? int* a = malloc(...)
There are zero ways to do that outside of keeping track of it separately from the allocation.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closedlast year.Improve this question I'm writing first program in C Language but I'm unable to compile it. Please help me!
You need to save the file. Press CTRL + S. You can also see you haven't saved it at the blue "1" on the left side of your VS Code sidebar. If you don't save it, you're just trying to compile an empty file.
Trying to get a value back that usually should return 20 to 30 asswith this code ``` int s = sentences / wordcount * 100; ``` bothsentencesandwordcountcome out as the values they should neither of which are 0. The result of them would be small (0.20 to 0.30) so thinking it might be to do with that?
Try casting the division to a floating point (FP) value explicitly, this should prevent the result of ``` sentences / wordcount ``` from being floored to zero. You should only need to cast one to be a FP value. Try ``` int s = (double) sentences / wordcount * 100 ```
Let's assume the phone is rooted and arm binaries can be installed. Can I make a console binary using Android Studio withprintfoutput? Is there a step-by-step guide to writing and compiling such binaries with a traditional C Programint main()with Android Studio or creation of theAndroid.mkfile There are some projects on GitHub doing this: https://github.com/strazzere/android-unpacker/tree/master/native-unpacker And https://github.com/Shabbypenguin/DexPwn
``` #include <stdio.h> int main() { printf("Hello, world\n"); return 0; } ``` Then: ~/Library/Android/sdk/ndk/24.0.8215888/toolchains/llvm/prebuilt/darwin-x86_64/bin/clang --target=aarch64-linux-android21 helloworld.c -o helloworldadb push helloworld /data/local/tmp/helloworldadb shell /data/local/tmp/helloworld
I am doing all my assignments in a single .c file by writing functions, but now it seems that it affects the run time. Does it mean that if I do not call a function but define it then the function is also compiled and hence it slows down the program?
No. The only thing it affects is compile and link time and to some degree startup/load time (becauese of larger binary) Most compilers will strip (i.e. remove) unused code when optimizations are turned on.
Let's say I have this struct ``` typedef struct { int AM; char* name, surname; }Item; ``` and I want to define a constant NULLitem with AM = -1 and NULL name/surname. Is there a way to do it with #define?
``` #define NULLitem (const Item){ .AM = -1, .name = NULL, .surname = NULL } ``` That's a C99compound literal.
I've tryed to print out some array of strings but faced error: excess elements in char array initializer Please make a hint what's worng with this code? Step 1 change '' with "" nothing changed, the same error. Step 2 change maschar to *maschar, it helped, thaks. ``` #include <stdio.h> #include <stdlib.h> int main() { char maschar[] = {'char', 'mas', 'got'}; int lenchar = sizeof(maschar) / sizeof(*maschar); for (int i = 0; i< lenchar; i++) printf("%s\n", *(maschar+i)); return 0; ```
Step 1 change '' with "" nothing changed, the same error. Step 2 change maschar to *maschar, it helped, thaks. ``` char *maschar[] = {"char", "mas", "got"}; int lenchar = sizeof(maschar) / sizeof(*maschar); for (int i = 0; i< lenchar; i++) printf("%s\n", *(maschar+i)); ```
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.Closedlast year.Improve this question For example: temp->next = NULLis same as(*temp).next = NULLlist->next->next = tempis same as ??
It's the same as(*(*list).next).next = temp
CAs you see in this code I'm trying to print the below pattern, Is the code is right to print the pattern cuz in my computer it show's wrong. ``` //To print this type of pattern //5 5 5 5 5 5 //5 5 5 5 5 //5 5 5 5 //5 5 5 //5 int i, j, a=5; for(i=0; i<=5; i++) { for(j=i; j<=5; j++) { printf("%d", a); } printf("\n"); } ```
``` #include <stdio.h> int main(void) { int height = 5; char line[height*2]; for(int i=0; i<height*2; i+=2) { line[i]='0'+height; line[i+1]=' '; } for (int i=0; i<height; ++i) { printf("%.*s\n",2*(height-i), line); } return 0; } ``` Result ``` Success #stdin #stdout 0s 5532KB 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 ```
This question already has answers here:Compound condition in C: if (0.0 < a < 1.0)(4 answers)Closedlast year.This post was edited and submitted for review10 months agoand failed to reopen the post:Original close reason(s) were not resolved I have done this code in my VS-code using Mingw GCC compiler and I got the output "No" instead of "Yes"? It is clear that 5>4>3, then what is the reason behind it? ``` #include <stdio.h> int main() { int a = 4; if (5 > a > 3) printf("Yes"); else printf("No"); return 0; } ``` ``` Expected Output: Yes Original Output: No ```
(5 > a > 3)does not mean what you think it means. It translates to(5>a) > 3, and(5>a)evaluates to1. Then,1>3evaluates to false, so you get "No". To do what you want, you doif ( (5 > a) && (a > 3) ).
Forerrno, there are a bunch of library functions, likestrerror(), etc. to convert or print the error code. But what about the error codes returned by library functions? E.g.write()will returnEAGAIN,EBADF, etc. Where do these symbols come from? Are they compatible withstrerror()&co?
EAGAIN,EBADFetc. are symbols for system error numbers,defined inerrno.h. They are compatible withstrerrorand related functions. Note thatwritedoesn’t return one of these values on error; on error, it returns -1, and setserrnoappropriately. Few functions return error numbers; amusingly enough, one of them isstrerror_r, which returns 0 on success, orEINVALorERANGEon failure.
I'm currently learning to program in C and I can't understand why my terminal outputs: "zsh: trace trap ./a.out" when running my code. This is my code: ``` #include <stdio.h> #include <string.h> int main() { char str[] = "Hello "; char str2[] = "Wolrd!"; strcat(str, str2); printf("%s\n", str); return 0; } ``` This is what I type in the terminal: ``` gcc test.c ./a.out ```
The problem isstris allocated based on the size of the literal you are initialing it with.strcatpresumes you have enough room to concatenate both strings. changestr[]tostr[100]and it would work because you have sufficient space for both strings. This fixes your problem but you need to understand arrays, memory allocation and read the expectations of the functions likestrcat.
I am facing problem to understand this line of code. ``` printf("\033[2J\033[1;1H"); ``` This printf statement is used to clear the terminal in c. Can anybody explain this to me? Thanks.
Take a look at the list of ANSI escape sequences:https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797 ESC[2J: erases the entire screen General information:https://en.wikipedia.org/wiki/ANSI_escape_code
In the MDR32(similar with STM32) microcontroller, there is a 16-bit STAT register that describes the ethernet status, the documentation says that 7..5 bits indicate the number of received packets, how can I get this value and save it inuint16_tvariable?
Depending on how you read your notation, to get bits 5, 6 and 7 from an integer you can simply do: ``` auto ethStatus = (stat >> 5) & 7; ```
I would like to use__weakin a library I am creating, but I want to make sure it is compliant with a known "C-number" standard. Which standard introduced this? Or is it a non-standard compiler extension that most compilers have supported? (Either through the keyword or__attribute__.) EDIT: Probably should not have used the term "keyword", mostly interested if "weak" in some form is a standard?
__weakis not part of the C standard. __weakis a compiler extension specific to the compiler, for example available on Keil and COSMIC compiler.__attribute__is a compiler extensions from gcc GNU C compiler, available for example on clang, TASKING Compiler, TI Arm Compiler, and so on. For example,__weakis invalid on gcc. You can browseSTM32CubeF4/cmsis_compiler.hfor some compiler-specific macros definitions for STM32Cube project forsomecompilers. It is common, because of the popularity ofELF format, which has the support for weak symbols.
I am struggling with swapping from Arduino/Wire library to ESP-IDF's I2C driver. I got stuck at the very first stage, trying to simply read the register. The function I use isesp_err_t i2c_master_write_read_device(i2c_port_t i2c_num, uint8_t device_address, const uint8_t* write_buffer, size_t write_size, uint8_t* read_buffer, size_t read_size, TickType_t ticks_to_wait). The problem I face is that mywrite_bufferis uint16_t. How to get over it? Thanks
You need to pass to the function a pointer to the buffer and the size of that buffer. If you want to write a simple uint16_t variable: ``` uint8_t *write_buffer = (uint8_t*)&old_buffer; size_t write_size = 2 ``` Take into consideration that you are responsible to accomodate the memory for that buffer, so make sure the uint16_t variable is not destroyed before the write function has finished.
Suppose I have the following C line: ``` int a = 4 + 7; ``` When compiling this line, GCC will always produce something likemov DWORD PTR [rbp-X], 0xb, as the result of this computation is constant and known at compile time. Is there a way to disable this behaviour to have a mov 4, add 7 instead? A quick search led me to the -O0 or -OG flags, but they turn off other kinds of optimizations, such as the fact that functions should be aligned in memory.
Is there a way to disable this behaviour to have a mov 4, add 7 instead? No. Evaluation of elementary constant expressions is built into the compiler.
is using definitions in c like this: ``` #define C1 42 #define C2 10 #define finalC C1 * C2 ``` inefficient as this code will be ALWAYS run during run-time even though the calculation might not be needed?
as this code will be ALWAYS run during run-time even though the calculation might not be needed? The multiplication will most likelynotbe executed at run-time. For example, this short function: ``` #define C1 42 #define C2 10 #define finalC C1 * C2 int foo() { return finalC; } ``` maycompileinto: ``` foo(): push rbp mov rbp, rsp mov eax, 420 pop rbp ret ``` and that's without any optimization flags! The macro expansion happens before the compiler processes the code; and it is allowed, and tends to, evaluate constant expressions. PS - The compiler used was GCC 11.3 and the target architecture is x86_64.
I created and initialized System V semaphores withsemget()andsemctl()in the main function, but thesemop()function is called in a different function. I simply passed the ids of the semaphores as parameters to that function. It looks something like this: ``` int manageProcesses(int* data, int* numProcesses, int semId, int mutex, int time) { semop(mutex, &semwait, 1); ... } ``` Does this work or shouldsemop()be called in the same function assemget()andsemctl()?
Does this work or shouldsemop()be called in the same function assemget()andsemctl()? The id of a semaphore set, as obtained fromsemget(), is a process-scoped handle on an object (the semaphore set) with kernel persistence. Once you obtain one, you can use that anywhere in the program in conjunction withsemctl()and / orsemop(), until and unless you remove the semaphore set viasemctl(..., IPC_RMID), or some other process removes it.
I am trying to debug my c program using ``` gcc -g -lm -lpthread -std=c99 -w terminalproject.c ``` and then ``` gdb a.out ``` but when I typelayout next, it shows me assembly code not c code. How to switch to C code in layout? EDIT: I am using Red Hat Linux 6, I tried to run it in Ubuntu, It is showing C code. p.s my code has pthreads in it.
This command: ``` gcc -g -lm -lpthread -std=c99 -w terminalproject.c ``` iswrong. Use this instead: ``` gcc -g -std=c99 -pthread terminalproject.c -lm ``` You shouldneveruse-w(suppress all warnings) flag, unless you desire painful debugging sessions. layout srcsaysNo source Available. This likely means that you are using updated GCC, but ancient GDB. Try building recent GDB release from source -- it's usually not hard.
I am trying to write a simple C program without including standard libraries and trying to compile and run with gcc. but I was getting segmentation fault( core dumped ) main.c: ``` int main(){} ``` commands executed: gcc main.c -c -ffreestandinggcc main.o -e main -nostdlib./a.out output: Segmentation fault (core dumped) any help would be greatly appreciated.
Besides the problem mentioned in the comments, there is also a problem during the link time. If you run it with the flag-nostdlib, it will ignore the symbolsymbol _start, which is part of a default library,crt0.o.
I am trying to write a simple C program without including standard libraries and trying to compile and run with gcc. but I was getting segmentation fault( core dumped ) main.c: ``` int main(){} ``` commands executed: gcc main.c -c -ffreestandinggcc main.o -e main -nostdlib./a.out output: Segmentation fault (core dumped) any help would be greatly appreciated.
Besides the problem mentioned in the comments, there is also a problem during the link time. If you run it with the flag-nostdlib, it will ignore the symbolsymbol _start, which is part of a default library,crt0.o.
I know a similar question is already asked here for example: Malloc a 2D array in C However, my question is not how to create one but rather if I should prefer to use for a mathematical 2D matrix a "real" 2D array (with pointers of pointers) or rather a flattened 1-dimensional array with proper indexing.
I think the only case it can be important is when you are doing operations that depends on the neighbors of the matrix. In this case, using a 2D matrix is a bit better because it avoids cache misses. This is specially important for problem solutions that use dynamic programming optimization . I believe it can also be important for image processing, where many operations are applied in a rectangle of pixels.
I am trying to access an element usingtemp_param->mat_ptr[0][0]but it produces an errorFormat specifies type 'int' but the argument has type 'int *'. What is the problem? ``` #include <stdio.h> typedef int matrix[4][4]; matrix mat; typedef struct tnode { matrix *mat_ptr; } params; params temp_param; int main() { temp_param.mat_ptr = &mat; /* temp_param->mat_ptr[0][0] produces an error "Format specifies type 'int' but the argument has type 'int *'" */ printf("%d", temp_param->mat_ptr[0][0]); return 0; } ```
The type of expressionparams.mat_ptris a pointer to 2D array. Therefore is must be dereferenced before being accessed like 2D array. Moreovertemp_paramis a struct, not a pointer to struct. Therefore its members are accessed via.operator rather than->. Try(*temp_param.mat_ptr)[0][0]
I'm trying to write a 479x639 matrix ofints to a.txtfile. Preferably each line will include one entry followed by a,, so that I can input the data on MATLAB. I used the following code to try and write the raw data to a.txt: ``` FILE *f = fopen("output.txt", "w"); fwrite(output, sizeof(int), 479*639, f); fclose(f); ``` All I get is atxtwith corrupted data. The rest of the program runs smoothly. Any suggestions?
Try this out and tell me if it works ``` #include <stdio.h> int main() { int output[479][639]; // Add values into output 2D matrix FILE *f = fopen("output.txt", "w"); for (int i = 0; i < 479; i++) { for (int j = 0; j < 639; j++) { fprintf(f, "%d, ", output[i][j]); } fprintf(f, "\n"); } fclose(f); return 0; } ```
This question already has answers here:How to read a line from the console in C?(14 answers)Closedlast year. I have a string that I want to execute in C file and I'd like to get the string from standard input. ``` echo "Here is some random text.\n" | ./main.c ```
Read fromstdinlike any otherFILEstream. ``` #include<stdio.h> int main() { char line[BUFSIZ]; fgets(line, sizeof(line), stdin); printf("stdin: %s", line); } ```
I have thisfile.bat: ``` cd "C:\Program Files(x86)\Anydesk" && anydesk.exe ``` If i double click on it it works fine and does what i want. Now i try to launch this bat file inside of my C program : ``` system("path\\file.bat"); ``` But it does nothing. I see a super fast cmd opening and nothing else. I am wondering maybe it is failing because it is calling another application? But i am not sure. How to make this work?
.bat is not an executable. It is a script which is processed by cmd.com. So you need to execute it, with your .bat as a parameter: ``` system("cmd /C path\\script.bat"); ``` The/Ckey will tell your cmd, to execute the bat and exit, once the bat is finished. You can use/Kfor debug purposes (execute and remain open after completion).
It's follow-up question to:How to detect non IEEE-754 float, and how to use them? In theory, can we assume that c float always support negative numbers?
Can floats not suport negative or even 0? I don't think the intention is to allow not supporting negative or zero: ISO/IEC9899:2017Characteristics of floating types <float.h>... The following parameters are used to define the model for each floating-point type:s sign (±1)b base or radix of exponent representation (an integer > 1)e exponent (an integer between a minimum emin and a maximum emax)p precision (the number of base-b digits in the significand)fk nonnegative integers less than b (the significand digits) C23 wording adds stronger assertion ISO/IEC 9899:202x (E)Floating types shall be able to represent zero (all fk == 0) and all normalized floating-point numbers (f1 > 0 and all possible k digits and e exponents result in values representable in the type
Can someone help me to understand what exactly means this error message; ``` Error[Lp011]: section placement failed unable to allocate space for sections/blocks with a total estimated minimum size of 0x1cc1c bytes (max align 0x4) in <[0x08000000-0x0801b7ff]> (total uncommitted space 0x1b740). Error while running Linker ``` I know it is about the running out of memory, but I don't understand how much memory.
As the linker says, there is atotal uncommitted space 0x1b740but your program usestotal estimated minimum size of 0x1cc1c bytes. 0x1b740is 112448 bytes, and0x1cc1cis 117788 bytes, giving a difference of5340 bytes. Your program is 5340 bytes over the limit.
I have a working visual studio 2019 project with a simple nuget package, where if I right click 'ClassLibrary2' and click 'pack' it packages my project into a NuGet package I want to package this folder NxTestware, when I include the folder in my project and try to pack again, it results in errors that come from inside the source folder, like it is trying to build the contents of that folder Is there some way in visual studio I can tell it that when I click 'pack', do not build the contents of the NxTestware folder?
After trying I can't reproduce your issue on my side, please check your project's csproj file, and refer to this document:How to: Exclude files from the build.
I am working on reversing a simple binary using Ghidra. The decompile results in this line of codeif ((param_1 != 4) && (func0(param_1 + 1), param_1 + 1 == 0x32))The param_1+1==0x32 section is confusing me as I'm just not familiar with the syntax and am not sure what it is doing inside a boolean expression.
That's the comma operator. In this case, it's just unnecessarily confusing, as an alternative decompilation could have avoided it, e.g., these are equivalent: ``` if ((param_1 != 4) && (func0(param_1 + 1), param_1 + 1 == 0x32)) { doStuff(); } ``` ``` if (param_1 != 4) { func0(param_1 + 1); if(param_1 + 1 == 0x32) { doStuff(); } } ```
I have seen some program that useintinstead of other type likeint16_toruint8_teven though there is no need to useint let me give an example, when you assign9to anint, i know that9takes only 1 byte to store, so is other 3 bytes free to use or are they occupied? all i'm saying is, doesintalways takes 4-bytes in memory or it takes byte accordingly and 4-bytes is the max-size i hope you understand what im saying.
The size of all types is constant. The value that you store in an integer has no effect on the size of the type. If you store a positive value smaller than maximum value representable by a single byte, then the more significant bytes (if any) will contain a zero value. The size ofintis not necessarily 4 bytes. The byte size of integer types is implementation defined.
I'm working on translating a C program to assembly MIPS. I have multiple conditions in a single if-statement. It'sif (n == 0 || (n > 0 && n % 10 != 0)). When this condition is true, it reassign the variableansto 0. This is what I have done so far: ``` beqz n label1 ``` What should I do when I have multiple conditions?
Anifstatement directs execution to one of two locations: The start of the THEN block, or the start of the ELSE block (or immediately after the THEN block if it doesn't have an ELSE block.) So we can break down the conditions as follows: n == 0: Go to the THEN blockn <= 0: Go to the ELSE block or after IFn % 10 == 0: Go to the ELSE block or after IFGo to the THEN block
I have an array of strings. How can I get the char "v" from the second element in the array? ``` char* name = "Ziv"; char* name2 = "Avinoam"; char* name3 = "Matan"; char** stringsArray[3] = { name, name2, name3 }; printf("v is: %c", *(stringsArray[1])[1]); // I want to get "v" from "Avinoam" ```
The type ofstringsArrayis not correct, what you have is an array of pointers to pointer tochar, you need an array of pointers tochar: ``` char* stringsArray[] = {name, name2, name3}; ``` Indexing is the same as in a 2D array, you could use pointer notation: ``` printf("v is: %c", *(*(stringsArray + 1) + 1)); ``` But using square brackets is much clearer: ``` printf("v is: %c", stringsArray[1][1]); ``` Live sample:https://godbolt.org/z/TMjf1GcE9
I am usingIWDas a wireless daemon in userspace. Driver and firmware are loaded. When the socket is called by IWD usingnl80211, it passes tonl80211and thancfg80211in kernel space. At kernel space how do they know which driver to call or pass requests to which driver? Socket is created using this: ``` fd = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, NETLINK_GENERIC); ``` And this fd is used to pass requests to kernel space. [edits] Similar concept of socket is used in this code:How to use netlink socket to communicate with a kernel module? It is using same socket creation and calling to communicate between userspace and kernel space.
As explained by @stark in a comment: You are using NETLINK_GENERIC protocol, so will call the Generic Netlink code. The other question is using a user-written module that registers protocol 31. wiki.linuxfoundation.org/networking/generic_netlink_howto
I'm studying a code that contains: ``` ... SDL_Rect rect(0, 0, 100, 50); ... ``` But when I do it, i get the following error: ``` error: expected declaration specifiers or ‘...’ before numeric constant 49 | SDL_Rect rect(0, 0, 100, 50); ``` Can someone tell me why?
If you're compiling as C, this is invalid. There are no constructors in C. The compiler is interpreting the first part of your code as a forward declaration, and the latter part confuses it. Just define the SDL_Rect as such ``` SDL_Rect rect; rect.x = 0; rect.y = 0; rect.w = 100; rect.h = 50; ``` Here is the libsdl reference:https://wiki.libsdl.org/SDL_Rect Although since you're studying code, you probably want to just compile this as C++ as it appears that is what it was written in.
Let say I have this preprocessor check: ``` #if(-6 & 5) #error "No 2's complement signed int" #endif ``` What would happen if I cross compiled from, say, a two's complement machine toward a one's complement machine. Would the compiler use the arithmetic of the target machine, or the one of the compiling machine ? Thanks
C 2018 6.10.1 4 says, for evaluation of expressions in#ifand#elifdirectives: … For the purposes of this token conversion and evaluation, all signed integer types and all unsigned integer types act as if they have the same representation as, respectively, the typesintmax_tanduintmax_tdefined in the header<stdint.h>… These types are of course used during program execution, so their behaviors are those of the execution environment.
I'm trying to build LMDB from master branch, because Windows incremental file growth patch is not merged into release branch. I'm using CMake and MSVC compiler. And I'm trying to buildlmdbas a static library. Error I get is: mdb.c(55,19): error C2143: syntax error: missing ')' before '__cdecl' This is the line #55 from mdb.c, plus a few lines that follow it: ``` typedef NTSTATUS (WINAPI NtCreateSectionFunc) (OUT PHANDLE sh, IN ACCESS_MASK acc, IN void * oa OPTIONAL, IN PLARGE_INTEGER ms OPTIONAL, IN ULONG pp, IN ULONG aa, IN HANDLE fh OPTIONAL); ``` Any idea what is causing this and how to fix it?
It turns out that the problem wasadd_definitions(-DWIN32_LEAN_AND_MEAN)that was in another cmake of an external library.
I made astruct Triangleand I made a function to calculatep(perimeter/2). When I call the function insideprintfit works. But when I call the same function as a simple arithmetic statement it doesn't work and gives me following error ``` called object 'p' is not a function or function pointer ``` Source code: ``` #include <stdlib.h> typedef struct{ int a, b, c; } Triangle; int perimeter (Triangle t){ return t.a + t.b + t.c; } float p (Triangle t){ return perimeter(t) / 2.0; } int main() { Triangle t = {3, 4, 5}; //float p = p(t); printf("p = %.2f\n",p(t)); return 0; } ```
``` //float p = p(t); ``` You cannot use the same name for a function and a variable. Change yourfloat ptofloat aand it should work. Or rename your function to, sayperimeterinstead of justp. Also in general, it is better to use slightly longer, clear and descriptive names for functions.
We know there exists#pragma oncewhich prevents source file to be included more than once, but how to make preprocessor (with conditional compilation) which prevents the inclusion of the file in another file more than twice (once and twice is possible, but more than doesn't include).
something like this? ``` // so72049366.h file #ifndef SO72049366_TWICE #ifndef SO72049366_ONCE #define SO72049366_ONCE #else #define SO72049366_TWICE #endif i++; #endif ``` ``` // so72049366.c file #include <stdio.h> int main(void) { int i = 0; #include "so72049366.h" printf("%d\n", i); #include "so72049366.h" printf("%d\n", i); #include "so72049366.h" printf("%d\n", i); } ``` Output ``` 1 2 2 ```
We know there exists#pragma oncewhich prevents source file to be included more than once, but how to make preprocessor (with conditional compilation) which prevents the inclusion of the file in another file more than twice (once and twice is possible, but more than doesn't include).
something like this? ``` // so72049366.h file #ifndef SO72049366_TWICE #ifndef SO72049366_ONCE #define SO72049366_ONCE #else #define SO72049366_TWICE #endif i++; #endif ``` ``` // so72049366.c file #include <stdio.h> int main(void) { int i = 0; #include "so72049366.h" printf("%d\n", i); #include "so72049366.h" printf("%d\n", i); #include "so72049366.h" printf("%d\n", i); } ``` Output ``` 1 2 2 ```
I have the following code ``` #include <stdio.h> //#define arraySize 5 #define arraySize 500 void func(double B[arraySize][arraySize]) { B[0][0] = 5; } int main(void) { double Ar2D[arraySize][arraySize]; func(Ar2D); printf("%f", Ar2D[0][0]); } ``` Code works fine when I test it in a linux virtual machine, but when I run it in minGW, it crashes if I set arraySize to 500 (works fine in minGW if I set arraySize to 5). What is the best way to fix this?
You really should avoid using the stack for large things. It's also a security risk as stack overflows wan be abused by hackers (e.g. to try to attempt running arbitrary code). Better is to use the heap, you can do this by replacing ``` double Ar2D[arraySize][arraySize]; ``` with ``` double** Ar2D = (double**)malloc(arraySize * arraySize * sizeof(double)); ``` and of course don't forget tofree(Ar2D);
In C++ we can decorate our return types with "[[nodiscard]]" which triggers a compiler warning if the results are unused. This is particularly useful to enforce error codes ``` auto dont_forget_to_check = do_something_important(); assert(dont_forget_to_check); ``` Does something like this exist for C?
There's no standard way to do this, but gcc does support thewarn_unused_resultattribute for this. ``` __attribute__ ((warn_unused_result)) int foo() { return 5; } int main() { foo(); return 0; } ``` Compiler output: ``` [dbush@db-centos7 ~]$ gcc -g -Wall -Wextra -o x1 x1.c x1.c: In function ‘main’: x1.c:11:8: warning: ignoring return value of ‘foo’, declared with attribute warn_unused_result [-Wunused-result] foo(); ^ ```
Can anybody explain what is written in this structure in C ``` struct Structure { int i; void (*function)(struct Structure*); } ; ```
Here's a "working example": ``` #include <stdio.h> struct Structure { int i; void (*function)(struct Structure *); }; void foo(struct Structure *); void bar(struct Structure *); int main(void) { struct Structure a = {0, foo}; struct Structure b = {42, NULL}; // don't call b.function() just yet!! a.function(&b); b.function(&a); } void foo(struct Structure *a) { if (a->function == NULL) a->function = bar; printf("value from foo: %d\n", a->i); } void bar(struct Structure *a) { printf("value from bar: %d\n", a->i); } ```
I'm trying to understand the basic of pointers, and done this code: ``` int c = 3; int try(int a){ ++a; return 0; } int main(){ try(c); printf("%d\n",c); return 0; } ``` How do I manage to print 4 with pointers? I know that I can do it like this: ``` int c = 3; int try(int a){ ++a; return a; } int main(){ c = try(c); printf("%d\n",c); return 0; } ``` but I really want to learn how to pass those values through functions via pointers. Furthermore, any great book recommendation for solid C learning is always welcome. Thanks in advance.
``` int c = 3; void pass_by_ref(int *a) // Take a Pointer to an integer variable { ++(*a); // Increment the value stored at that pointer. } int main(){ pass_by_ref(&c); // Pass the address of the variable to change printf("%d\n",c); return 0; } ```
``` #include<stdio.h> int main(){ int i,j,rows; printf("Input number of rows : "); scanf("%d",&rows); for (i=1;i<=rows;i++) { for (j=1;j<=i;j++) printf ("%d",i); printf ("\n'); } return 0; } ``` I am new to c programming can anyone help to convert this for loop into while loop? Thanks
Any for loop as: ``` for (e1; e2; e3) { *block* } ``` is strictly equivalent to (only if there is nocontinuein the block): ``` e1; while (e2) { *block* e3; } ``` Ife2is empty, then it could be replaced by1during translation.
From time to time I see this code: ``` #define X1 (13) #define X2 ((size_t)13) ``` As I understand, the (outer)()are redundant here. Is that correct? UPD: Some software development guidelines may require it. For example: MISRA C:2004, Rule 19.4 (required): C macros shall only expand to a braced initialiser, a constant, aparenthesised expression, a type qualifier, a storage class specifier, or a do-while-zero construct. However, MISRA C:2012 has: ``` #define MY_NULL_2 ( void * ) 0 #define sqrt( x ) ( _BUILTIN_sqrt ( x ) ) ```
I don't believe the first example needs parentheses, but always parenthesizing macro bodies is a reasonable habit. The second one will produce unexpected grouping if you remove the outer parentheses from the definition and then invoke it in the contextX2[a].
I'm currently reprogramming some C libraries. So my question is: Why doesmemchrtake anconst void *spointer and not simply an character pointer? I see that you could probably search for other stuff, but the function is literally calledmemchrso why use a void pointer? Thanks in advance!
C’s early development involved a fair amount of treating things as individual bytes and allowing programmers access to the bytes that represented objects. The namememchrreflects that history and cannot readily be changed now. voidwas added to the language to provide a type that represents, in a sense, “something is there, but this is flexible.” The first parameter tomemchrhas typeconst void *because the routine may be used to search for a byte in any type of object, not necessary an object that is primarily an array of characters.
``` #include <stdio.h> void main(void) { int price; scanf("%d", &price); switch (price) { case 1000: // what i want - case pay >= 1000 // code (no break - intentional) case 500: // ....... - case pay >= 500 // code default: break; } } ``` I'm new to this. Is there any alternative toswitchwithoutbreakand also able to use comparisons, not constant, in aswitch?
Just series ofifstatements then : ``` if (price >= 1000) { // do something } if (price >= 500) { // do some more stuff } ``` You may also want to use#definefor those magic numbers(1000, 500 ...). Or Enumerate them usingenum.Althoughswitch()looks like a function, it's a statement block.
I would like to save an array of linked lists in a binary file, but I don't know how to assign the dynamic memory due to the varying lengths of linked lists for each bucket. And to access a random position containing the whole linked list without reading the whole file, like a kind of index file? Some tip?
I will make these assumptions: Every (non-“null”) element of each list is anintThere areMAX_INTor fewer elements in each list Make your file (remember to open in binary mode) have the following structure: Output anintcontaining the number of items in the first listOutput eachintin that listRepeat for each subsequent list This scheme has two drawbacks: each list has a (large) maximum number of elementsyou must traverse each list twice to save (first to learn the length, again to save each item) It has the advantage of being very quick and direct to load.
Normally I compile code (all in a single file main.c) with the intel oneapi command prompt like so ``` icl.exe main.c -o binary_name ``` I can then run binary_name.exe without issue from a regular command prompt. However, when I recently exploited openmp multithreading and compiled like so. ``` icl.exe main.c -o binary_name /Qopenmp /MD /link libiomp5md.lib ``` Then, when I try to run it through an ordinary command prompt, I get this message: I'd ultimately like to move this simple code around (say, to another computer with the same OS). Is there some procedure through a command prompt or batch file for packaging and linking a dynamic library? It is also looking like statically linking for openmp is not supported on windows
Either make a statically linked version, or distribute the dependency DLL file(s) along with the EXE file. You can check the dependencies of your EXE withDependency Walker.
In embedded C code, we don't explicitly initialize global variables to 0, as the boot code will do that when system boots.There are two global variables in my code, for example, A and B. My code will promise that A will no longer be larger than B as long as they have a zero initial value.But when I check a Coverity reported issue, it supposed A might be larger than B. It seems that Coverity didn't think they both have an initial value 0.
From Synopsys's reply, Coverity doesn't track global variables. It infers from context that a defect is possible when the values of the variables are unknown.Here's a reference article.
I'm using the C SQLite library. I need to obtain the value of a blob from a row. The row is in a table that does not have any row id. This causes sqlite3_blob_open to return an error - that rowid is not present in the table. Software like DB Browser for SQLite is able to query the value of these blobs, so there must be a way to do it.
The answer is to use sqlite3_step() in conjunction with sqlite3_column_blob()
For example, given a function ``` void func(const int* a, int* b){ *b = 2 + *a; } ``` Should I emmit the const if func is often called like so:func(ptr, ptr)?
The wordconstin your function definition documents that the function will not change the object whose address is passed as the first argument to the function. It says thatais a pointer to a "constant integer". So if your function does not change the object thatapoints to, it makes sense to keep theconst. While it is not necessary to include theconst, it is good practice to do so. If you do not intend to change the object thatapoints to but your code attempts to modify*aanyways, this should be an error that your compiler will detect.
``` #include <stdio.h> int main() { unsigned long int sum = 0LL; long i; for (i = 0LL; i < 100000000; i++) { sum = sum + i; } printf("%i", sum); } ``` that's all of my code, and I am curious why it prints 887459712 instead of 4999999950000000, and how to fix this
Yoursumis declaredunsigned long int, which is big enough for your expected result.The problem is not overflow. The problem is yourprintfstatement is wrong. You told it to print a "normal" sized int with%i, which only goes up to about 4.2 billion. You should tellprintfto print anunsigned long int, using%lluIt should be: ``` printf("%llu", sum); ``` IDEOne Link Results ``` Success #stdin #stdout 0s 5376KB 4999999950000000 ```
When the if statement is deleted, the code runs without problems. What is the reason for that? This code gives the Greatest Common Divisor (GCD) of two numbers (m and n) the user should input. ``` #include <stdio.h> int main() { int m, n, r; scanf("%d,%d", &m, &n); if (m < n) { r = m; m = n; n = r; } do { r = m % n; m = n; n = r; } while (r != 0); printf("%d\n", m); return 0; } ```
It is not important whethermis greater thann. Ifminitially is less thannthen in the first iteration of the do-while loop ``` do { r = m % n; m = n; n = r; } while (r != 0); ``` mwill be greater thanndue to the statement ``` m = n; ``` For example let's assume thatmis equal to2andnis equal to10. Sorequal tom % nwill be equal to2and in fact these statements ``` m = n; n = r; ``` swapmandnin the first iteration of the loop.
Is the memory thatt2points to still reachable after the assignment? ``` #include<stdio.h> int main() { double *t1 = (double *)calloc(6, sizeof(double)); double *t2 = (double *)calloc(6, sizeof(double)); t2=t1; free(t1); return 0; } ``` Is the above code recommended? Will it cost memory leak? Or, does the memoryt2points to just align with whatt1points to in this case? Should I just simply usedouble *t3 = t1instead?
Is the memory that t2 points to still reachable after the assignment? No Is the above code recommended? No. Will it cost memory leak? Yes, the memory pointed to byt2is leaked. Or, does the memory t2 points to just align with what t1 points to in this case? It does but the originalcallocmemory is lost. Should I just simply usedouble *t3 = t1instead? Yes if you just want another pointer variable to the same address.
I would like to understand why when I execute this code ``` #include <stdio.h> #include <unistd.h> int main() { write(1, "6", 1); printf(" | "); write(1, "6", 1); } ``` I get this output ``` 66 | % ``` Instead of ``` 6 | 6% ``` even with sleep before and after the printf it doesn't fix it. Thanks
Try fflush(stdout); The file I/O is buffered to improve performance. Fflush writes the buffers out. Mixing the 2 may still give you surprises, so I would not recommend doing it.
This question already has answers here:Format specifier in scanf for bool datatype in C(3 answers)Closedlast year. There are times when I use stdbool.h while practicing coding. At this time, if the format modifier of scanf is given as %d, the following error message occurs. c:\project\hello\hello\hello.c(11): warning C4477: 'scanf' : format string '%d' requires an argument of type 'int *' but variadic argument 3 has type 'bool' It seems to compile, but it doesn't seem to properly recognize true/false or 0/1 inputs at runtime. I wonder if there's something I'm missing out on.
You are passing abool(or_Bool) toscanf. When using%d, you should pass the address of anint. If yourboolis namedx, then use: ``` int temporary; if (1 != scanf("%d", &temporary)) { fprintf(stderr, "Error, scanf did not work as expected.\n"); exit(EXIT_FAILURE); } x = temporary; ``` (Forexit, insert#include <stdlib.h>in your source code.)
I was wondering if I have a code like this: ``` struct something{ int x; float y; }; int main(void) { struct something *p; p = malloc(sizeof(struct something)); p->x = 2; p->y = 5.6; return 0; } ``` what's the content of *p (with *) if called somewhere? Is it the address of the structure or what?
Here's an example of the usage of*p- that is, dereferencing the pointer: ``` #include <stdio.h> #include <stdlib.h> struct something { int x; float y; }; int main(void) { struct something *p; p = malloc(sizeof *p); p->x = 2; p->y = 5.6; struct something s; s = *p; // dereference p and copy into s free(p); // now check s: printf("%d, %.1f\n", s.x, s.y); // prints 2, 5.6 } ```
I want to removegotostatements in my C code. The following shows my C code. ``` void placeFruit(void) { resetfruitX:fruitX=rand()%20; if(fruitX==0||fruitX==width) goto resetfruitX; resetfruitY:fruitY=rand()%20; if(fruitY==0||fruitY==height) goto resetfruitY; } ``` Can anyone help me?
``` void placeFruit(void){ do fruitX=rand()%20; while(fruitX==0||fruitX==width); do fruitY=rand()%20; while(fruitY==0||fruitY==width); } ```
I know that in C, you can print floats and doubles in scientific notation using "%e" and "%le" respectively and that you can print integers using "%d". Is there a way to print integers using scientific notation? I tried "%de", but that didn't work. For instance, I want 6000000 to print as 6e+06.
Can you print an integer in scientific notation? A simple approach is to convert to adoubleand then print.@Eric Postpischil ``` printf("%e\n", (double) some_int_type_object); ``` This is insufficient when the integer precision and value exceedsdouble- typically about 53 bits. Recommend to uselong doubleto handle wider integer types. This still may not meet precision requirements. ``` printf("%Le\n", (long double) some_integer_type_object); ``` Toportablyhandle 64-bit integers obliges custom code.
Noob question. I want to compilebar.cwith object filefoo.oto an executablebar. I have this in a Makefile: ``` bar: foo.o cc bar.c foo.o -o bar ``` I run$ make -nand get : ``` cc -c -o foo.o foo.c cc bar.c foo.o -o bar ``` I'm looking at the first line of outputcc -c -o foo.o foo.c. I didn't write an explicit rule compilingfoo.ctofoo.o. Doesmakedo this implicitly when it sees a.otarget?
Yes, GNU make has acatalogof built-in rules: Compiling C programsn.o is made automatically from n.c with a recipe of the form ‘$(CC) $(CPPFLAGS) $(CFLAGS) -c’. Linking a single object filen is made automatically from n.o by running the linker (usually called ld) via the C compiler. The precise recipe used is ‘$(CC) $(LDFLAGS) n.o $(LOADLIBES) $(LDLIBS)’. so you could just write: ``` bar: bar.o foo.o ```
Withgcc, is it possible to compile with-fstack-protector, but omit for a specific function. For example, say i have two functions. ``` void a() { ... } void b() { ... } ``` Can I tell the compiler to compile a program that will use a canary before the saved return address ofa, but no canary forb?
You'd have to test if it works (inspect the generated code at Godbolt) but it looks like you can do, for example: __attribute__ ((no_stack_protector)) void foo () { ... } no_sanitizelooks like an intriguing option, I wonder who uses that.
I write a function that returns a randomintbetween 1 and 6. But when I call this function inmain, it gives same number. Where's the problem? ``` int count, diceRoll; srand(time(NULL)); for (count = 0; count < 6; count++) { diceRoll = (rand() % 6) + 1; return diceRoll; } ```
Your function has multiple problems: the prototype is missingyou reinitialize the pseudo random number generator from the current time at each call, hence you get the same value forrand()until the time changes, which takes one full second.theforloop is useless as you always return the value ofdiceRollinside its body. You should initialize the PRNG once at the beginning of the program and use: ``` int rand6(void) { return 1 + rand() % 6; } ``` There is a very small bias in this function as the number of possibilities forrand()is not a multiple of6.
I only found how to do it in C++ which is somthing like CreateFile(.... FILE_SHARE_READ | FILE_SHARE_WRITE, ....) but found nothing on how to do it in C.
What you are asking for is not possible in plain ISO C, which only offers the functionfopen. However, on Microsoft Windows, you can call the platform-specific functionCreateFile, which offers this feature as an extension. You can use this function also when using the C programming language. It is not restricted to C++. The Microsoft documentation of the Windows API does not distinguish between C and C++, so when it refers to C++, it also means C.
In the document, I found thatfgets_unlocked()is not thread-safe. However, I am not sure that can I usefgets_unlocked()without using any lock in a multi-threaded code, but ensure that each thread will access a different file (no two threads will access the same file)?
If each thread usesfgetsof any kind to read from different files and write to different buffers, you're safe. There's nothing shared between threads in that case.
hey im reading some code and I see this: const struct struct_entry *(*enter)(const struct struct_entry *entry); can you explain to me how can I dessect it ? what I understand is it is creating two struct's one calledenterand anotherentryam I right ?
... (*...)(...)is a function pointer. There are three types here. enteris a pointer to a function. Its sole parameterentryis a pointer to astruct struct_entry, this struct being constant. Its return value is a pointer tostruct struct_entry, this struct being constant. (Thatconstshouldn't be there.) Some of the above was obtained by applying theSpiral Rule.
``` #include <stdio.h> int main() { int n; scanf("%d", &n); int L[n]; // ... return 0; } ``` I'm asking if I can give the number of elements in an array as needed using a variable . The teacher told us that this method is not recommended and I did not understand why. Thanks for answering for my question .
This declaration ``` int L[n]; ``` is a declaration of a variable length array. Variable length arrays are conditionally supported by compilers. So it is not excluded that you can meet a compiler that does not support such declarations. Pay attention to that in this declaration the value of the variablenshall be greater than0. As such an array has automatic storage duration then its size should not be vary big. Otherwise you should allocate memory for the array dynamically.
A bit of an embarrassing question but I'm confused about operator precedence here: ``` typedef struct { char arr[1024]; } SomeStruct; mySomeStruct.arr[42] ``` Since array access has a higher operator precedence than member access, shouldn't this actually meanmySomeStruct.(arr[42]), which just doesn't make any sense; what exactly am I trying to access inmySomeStruct? The compiler throws an error if I trymySomeStruct.(arr[42]), which checks out. This implies that what's actually happening is(mySomeStruct.arr)[42], but doesn't this violate operator precedence? Thanks!
See Eugene's comment. .and[]have the same precedence and are evaluated left to right.
I wanted to use thedialog.hlibrary from thedialogLinux package but when I try to make a radiolist (checklist with flag parameter set to 1) it gives me a segmentation fault. I assume it has to do with the list of strings (char**) but I have been unable to find a fix for it. In this code on line 10 the error occurs: ``` #include <dialog.h> int main() { int distro; char dist1[] = "Ubuntu"; char dist2[] = "Gentoo"; char *distros[2] = {dist1,dist2}; init_dialog(stdin, stdout); // start dialog distro = dialog_checklist("Select Distro","Select One",0,0,0,2,distros,1); end_dialog(); // end dialog } ``` Incase anyone needs it:man page for dialog.h
It appears I read the documentation wrong, the list was supposed to contain {tag, item, status} for each item.
This question already has answers here:Is volatile modifier really needed if global variables are modified by an interrupt?(2 answers)Closedlast year. I'm trying to wait for an interrupt to continue with the execution of the code, something like this: ``` bool flag = false; void interrupt_handler (uintptr_t context) { flag = true; } void main() { CallbackRegister(event, interrupt_handler,0); while(!flag); } ``` But it always stays in the while loop even when the interrupt occurs. Does anyone know why? I'm currently using MPLABX with a SAMD21J17 microcontroller.
You need to change: ``` bool flag = false; ``` to: ``` volatile bool flag = false; ``` The reason is that withoutvolatilethe compiler is allowed to assume that the flag never changes after it has been read once, but you want it to read the flag repeatedly.
The texture that gets rendered to the window is bound to Framebuffer 0. Is it possible to bind this texture to a texture unit, for use as a uniform sampler2D in a drawcall?
No. The default framebuffer (which is what is provided by the window system) has no corresponding texture object that you could sample from. If you want to sample from any render output, you are going to need to create a custom framebuffer object and render to some texture object attachments that you can then sample from. Another option is to blit the default framebuffer color buffer into another framebuffer color attachment. See:https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBlitFramebuffer.xhtml
This question already has answers here:Is volatile modifier really needed if global variables are modified by an interrupt?(2 answers)Closedlast year. I'm trying to wait for an interrupt to continue with the execution of the code, something like this: ``` bool flag = false; void interrupt_handler (uintptr_t context) { flag = true; } void main() { CallbackRegister(event, interrupt_handler,0); while(!flag); } ``` But it always stays in the while loop even when the interrupt occurs. Does anyone know why? I'm currently using MPLABX with a SAMD21J17 microcontroller.
You need to change: ``` bool flag = false; ``` to: ``` volatile bool flag = false; ``` The reason is that withoutvolatilethe compiler is allowed to assume that the flag never changes after it has been read once, but you want it to read the flag repeatedly.
The texture that gets rendered to the window is bound to Framebuffer 0. Is it possible to bind this texture to a texture unit, for use as a uniform sampler2D in a drawcall?
No. The default framebuffer (which is what is provided by the window system) has no corresponding texture object that you could sample from. If you want to sample from any render output, you are going to need to create a custom framebuffer object and render to some texture object attachments that you can then sample from. Another option is to blit the default framebuffer color buffer into another framebuffer color attachment. See:https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBlitFramebuffer.xhtml
I need to lighten the code, and then eliminate the underlyingifthat check if the subtraction are<0and if the condition is true I multiply * -1 in order to have subtraction >0 (absolute value). I wonder if there is a function or some operator able to perform the calculation directly inabsolute value? ``` int i, j, N, max, s, s1; s = v[i] - v[j]; s1 = i - j; if (s1 < 0){ s1 *= -1; } if (s < 0){ s *= -1; } ```
As the comments say: ``` s = abs(x - y) ``` The manpage forabs(and also labs, llabs):https://linux.die.net/man/3/abs It looks like you're doing this in a for loop of some sort (i,j arehopefullyloop indices, otherwise you need to name your variables more descriptively). In that case, you should be able to architect it such thatjis never greater thanifor a performance increase.
I've tried to find this online, but all the other questions are about code that is nothing related to what I'm looking for. I'm trying to see if I can have multiple executing lines in a ternary operator: ``` #include <stdio.h> int main() { int i == 1; i = 1?{printf("H");printf("J")}:printf("H"); } ``` The output of this is the error: ``` Error: expected expression before ‘{’ token ``` What is wrong here to cause that?
I'm trying to see if I can have multiple executing lines in a ternary operator You can, using a comma operator ``` i = 1?printf("H"),printf("J"):printf("H"); ```
I am trying to build a C ELF binary on linux and try to execute it directly on another machine. (Sent via scp linux command) The problem is that even when I build the ELF binary with all needed libs, when I try to execute it on the remote machine, I got this error: ``` /tmp/25636: error while loading shared libraries: libnftnl.so.11: cannot open shared object file: No such file or directory ``` Since I can't executesudo apt install -y libfuse-dev libmnl-dev libnftnl-devto install my libs on the remote machine , I wanted to know if it was possible to package all the dependancies within the ELF binary, so that the ELF binary can be executed in a standalone way. bguess.
@जलजनक was right. adding the-staticflag works, but the thing is that you have to add it at the right place ! For me it was right after the-o OUTPUT_FILEand beforeCFLAGSandLDFLAGS. Thank you all for your help.
I am using STM32F407 and lwip with uC-OS and I want to take ip from dns. I try to call this function. ``` ip_addr_t TargetIp; dns_gethostbyname("www.google.com", &TargetIp, NULL, NULL); ``` But, this function return -5 (ERR_INPROGRESS). In addition if I write "192.168.10.15" instead of "www.google.com" there was no problem. How can I take ip with DNS or another method.
I solved! I fixed function call of dns_gethostbyname ``` dns_gethostbyname("www.google.com", &TargetIp, dnsFound, NULL); ``` and I wrote a callback function which name is dnsFound like this. ``` void dnsFound(const char *name, ip_addr_t *ipaddr, void *arg) { dns_gethostbyname("www.google.com", &TargetIp, dnsFound, NULL); } ```
Can anyone explain to me how this code snippet works? ``` typedef int (*compare)(const char*, const char*); ```
It is a declaration of an alias for the type pointer to function that has the return typeintand two parameters of the typeconst char *. ``` typedef int (*compare)(const char*, const char*); ``` Using the alias you can declare a variable of the pointer type as shown in the demonstration program below ``` #include <string.h> #include <stdio.h> typedef int (*compare)(const char*, const char*); int main( void ) { compare cmp = strcmp; printf( "\"Hello\" == \"Hello\" is %s\n", cmp( "Hello", "Hello" ) == 0 ? "true" : "false" ); } ``` wherestrcmpis a standard C string function declared like ``` int strcmp(const char *s1, const char *s2); ``` and the pointer (variable)cmpis initialized by the address of the function.
I know that different data type will align. But I can't figure out why the size of this structure is 12. ``` #include <stdio.h> struct ABC { char a; char b; int k; char c; }; int main() { struct ABC a; printf("%lu\n", sizeof(a)); //12 return 0; } ```
Ok it works like this Here are the rules: chars are aligned to 1 byte ints are aligned to 4 bytes The entirety of the struct must be aligned to a multiple of the largest element. the final struct will be ``` struct ABC { char a; // Byte 0 char b; // Byte 1 char padding0[2]; // to align the int to 4 bytes int k; // Byte 4 char c; // Byte 8 char padding1[3]; // align the structure to the multiple of largest element. // largest element is int with 4 bytes, the closest multiple is 12, so pad 3 bytes more. } ```
I have a BST with id as a key as follows: ``` struct node { int id; char name[100]; struct node *right; struct node *left; }; ``` Here is the code to search an id: ``` struct node* search(struct node *root, int x) { if(root==NULL || root->id==x) return root; else if(x>root->id) return search(root->right, x); else return search(root->left,x); } ``` But what if I want to search for a name? Is it possible? Any suggestion? Thanks
Ofcourse it is possible. You can usestrcmpor any other function of your own for that. However the BST is created on the keyidso you aren't going to benefit from the reduced search complexity which BST provides.
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.Closedlast year.Improve this question I have a function which receives an address of a pointer to an array, I want the function to iterate that array, how exactly should I write the function's code? example of the function, and the function's call: ``` int example(int** arr, int n){} k = example(&arr, n); ``` Using*arr, gives me the address of the first object in the array, using**arrgives me the value of the first object in the array.But how do I access the next objects of the array is what I'm struggling with, let's say I want to iterate through the array in a for loop for example.
Just treat*arras an array ``` int *array = *arr; for(int i = 0; i < n; i++) { // do something with array[i]; } ```
In C, why can't I write: ``` char **expectedPINs01 = { "0", "5", "7", "8", "9" }; ``` Cause I got: warning: initialization of ‘char **’ from incompatible pointer type ‘char *’ But it is possible to write: ``` char *expectedPINs01[] = { "0", "5", "7", "8", "9" }; ``` What's the difference?
When you writechar **you are getting enough space for one pointer. If you want this to behave like an array, you then have tomallocspace sufficient for the size of the array and fill in the entries. When you writechar *x[5]you get enough space for 5 pointers. When you use the initialization shorthand, you can omit the5because the compiler can see from your initializer that you want there to be space for 5 pointers, and it reserves enough space for them and then uses the initializer shorthand to fill them in for you.
i used "psinfo_t" struct for printing cpu usage, start time of the processes in Solaris. But our companie's server was moved to Linux(Red Hat Linux), so i can't compile my c code because it has psinfo_t struct. where can i find that?
On Solaris (proc(5)),psinfo_tis a type found in<procfs.h>. This does not exist on Linux, and the two/procfilesystems have various differences. Under Linux (proc(5)),/proc/[pid]/statcontains the usual information found withps(1). Here is the simplest of examples, printing information about the current process. ``` #include <stdio.h> int main(void) { FILE *self = fopen("/proc/self/stat", "r"); char buffer[512]; while (fgets(buffer, sizeof buffer, self)) printf("%s", buffer); fclose(self); } ```
If I use: ``` fread(&buffer, 16384, 1, file); // Read 16384 bytes once? ``` instead of: ``` fread(&buffer, 1, 16384, file); // Read a byte 16384 times? ``` to read a plain text document file, would it succeed? Is it efficient?
It should have no effect on speed, but it affects your ability to perform partial reads. A single object is read as a unit: If you ask for a single 16384-byte object, and it can only read 16383 bytes,fread()fails and you are told nothing was read (the file pointer is still advanced by an unknown amount, though).If you ask for 16384 1-byte objects, and it falls short, you'll knowexactlyhow much you got (which will also tell you how far the file pointer was advanced). In short, if you want 16384 bytes and anything less is a failure, sure, ask for it as a single unit. But usually, you want to be in a vaguely useful state in the event of a partial read, so you should ask for it as 16384 individual bytes.
If I use: ``` fread(&buffer, 16384, 1, file); // Read 16384 bytes once? ``` instead of: ``` fread(&buffer, 1, 16384, file); // Read a byte 16384 times? ``` to read a plain text document file, would it succeed? Is it efficient?
It should have no effect on speed, but it affects your ability to perform partial reads. A single object is read as a unit: If you ask for a single 16384-byte object, and it can only read 16383 bytes,fread()fails and you are told nothing was read (the file pointer is still advanced by an unknown amount, though).If you ask for 16384 1-byte objects, and it falls short, you'll knowexactlyhow much you got (which will also tell you how far the file pointer was advanced). In short, if you want 16384 bytes and anything less is a failure, sure, ask for it as a single unit. But usually, you want to be in a vaguely useful state in the event of a partial read, so you should ask for it as 16384 individual bytes.
Let's say I have a structure named "example" which has a member named data which stores data allocated on the heap: ``` typedef struct _EXAMPLE { signed char *data; size_t size; } example_t; example_t *example_alloc(size_t size) { example_t *ret = malloc(sizeof *ret); ret->size = size; ret->data = calloc(size, sizeof *ret->data); return ret; } example_t *a = example_alloc(10), b = *a; ``` Is the value inb.datastored on the stack or the heap? Does it point to the data ina?
Pointers are just values. In the same way thatb.sizeis just a copy ofa->size,b.datais a copy of the same pointer value thata->dataholds. It points to the same location, wherever that may be. Care must be taken, asfreeinga->datainvalidatesb.data, and vice versa, which may result inUndefined Behaviorif accessed.