question
stringlengths
25
894
answer
stringlengths
4
863
I have a 1280 inodes per block in a EXT2 filesystem. I want to know the status of the inode 1282, which I know is used. I read the first byte of the inode bitmap corresponding to the second group. I get 0x07, meaning 00000111, meaning that the inode 1282 is free, when it's not. What's failing in my understanding? Thanks
The first three inodes are marked as used. Your problem is you are reading the bits from left to right, whereas the lowest bit, i.e. the one on the right, shows you the state of the first inode, so you should be reading the bits from right to left.
so I am currently attempting to locally map my suspended thread when I pop my program into CFF explorer it says that the value of PIMAGE_NT_HEADERS is 00004550: however while attempting to map it by myself my value comes out to be 00400080: ``` typedef struct pe { PIMAGE_DOS_HEADER peDH; PIMAGE_NT_HEADERS peNH; } pe; PE.peDH = (PIMAGE_DOS_HEADER)imgBase; PE.peNH = (PIMAGE_NT_HEADERS)((u_char*)PE.peDH + PE.peDH->e_lfanew); printf("[?] - NT Headers section is located at: 0x%x\n", PE.peNH); ```
it says that the value of PIMAGE_NT_HEADERS is 00004550 No, it doesn't. Look at it again more carefully. It actually says theSignaturefield of theIMAGE_NT_HEADERSstruct is00004550. But you are not printing theSignature, you are printing thePIMAGE_NT_HEADERSpointer itself. Not the same thing. Change your print to this instead: ``` printf("[?] - NT Headers Signature is: 0x%08x\n", PE.peNH->Signature); ```
I've been experimenting with simple code and I noticed: ``` short x = 0x8765; int y = (int)x; printf("y = %d\n",y); ``` would print out "y = -30875". I'm wondering why is it the case since when I convert 0x8765 from hex into decimal I got y = 34661.
The bit pattern of0x8765is negative in a 16-bit signed two's complement integer, but positive in a 32-bit signed two's complement integer. In anint16_t: ``` 0b1000011101100101 //^ sign bit set ``` In anint32_t: ``` 0b00000000000000001000011101100101 //^ sign bit unset ```
How can I have two different structs that refer to each other? One holds a pointer to the other and I also have a forward declaration: ``` struct json_array_t; struct json_array_entry_t { enum json_type type; union { bool boolean; long long integer; double floating; char* string; struct json_array_t array; }; }; struct json_array_t { struct json_array_entry_t* entries; size_t len, cap; }; ``` I am getting these errors: ``` error: field ‘array’ has incomplete type 27 | struct json_array_t array; ```
You must first definestruct json_array_tand thenstruct json_array_entry_t. When you now define instruct json_array_entry_tan occurrence ofjson_array_tit and all its members are fully known to the compiler.
This question already has answers here:I can use more memory than how much I've allocated with malloc(), why?(17 answers)Closed2 years ago. I was messing around with the memset function and did this: ``` int* p = malloc(sizeof(int); memset(p, 0, 10000); ``` I was wondering why this is valid. I've only allocated 5 bytes of memory yet I can take up 10000 with memset. Why should I even malloc the memory if I can take up more than allocated? Could someone explain?
It'sundefined behaviour, as in you can do it but the results are not defined, as in unpredictable, as in the program might crash. In this case you can only write to the allocated region, orsizeof(int) * 5. Why doesn't C prevent you from doing this? It's because the language design philosophy is that the programmer knows what they're doing and to not get in the way.
I am loading apng fileusing stb_image_load. The code looks something like ``` stbi_uc* pixels = stbi_load("textures/viking_room.png", &texWidth, &texHeight, &texChannels, STBI_rgb_alpha); ... if (stbi_failure_reason()) std::cout << stbi_failure_reason(); if (!pixels) throw std::runtime_error("failed to load texture image!"); ``` Now stbi_failure_reason() returnno SOIbutpixelsis not empty and loads the texture perfectly. The first result on github about this was about malformed png headers, so I checked using pngcheck, but it says that the png file is OK. Any idea why this might be happening? I've also had trouble loading thisimageHowever it works with other images, is there any way I can avoid this in future?
There was an issue opened787for this and was fixed on a newer version (2.27)
I was wondering if there is a macros that I can use to place a global variable in another section. i.e my_array would be stored in bss. since it's uninitialized but I want to place it in .data section instead. ``` uint8_t my_array[]; int main() { return 1; } ```
If you're using gcc, you can use the__section__attribute to set the section: ``` __attribute__((__section__(".data"))) uint8_t my_array[5]; ``` Note that you'll also need to set a size for it, otherwise you only have a declaration instead of a definition.
Alloc N * N int array in C, When N = 1024, It Just Workd, When N = 2048, I get "segmentation fault ". The machine is Ubuntu 20.04 with 2GB memory. Is my memory not big enough? ``` 1 #include <stdio.h> 2 3 #define N 1024 4 5 int main() 6 { 7 int arr[N][N]; 8 9 for (int i = 0; i < N; i++) 10 for (int j = 0; j < N; j++) 11 arr[i][j] = i + j; 12 13 return 0; 14 } ```
Put the decleration of arr outside of main. As it is now you are running out of stack space.
I am loading apng fileusing stb_image_load. The code looks something like ``` stbi_uc* pixels = stbi_load("textures/viking_room.png", &texWidth, &texHeight, &texChannels, STBI_rgb_alpha); ... if (stbi_failure_reason()) std::cout << stbi_failure_reason(); if (!pixels) throw std::runtime_error("failed to load texture image!"); ``` Now stbi_failure_reason() returnno SOIbutpixelsis not empty and loads the texture perfectly. The first result on github about this was about malformed png headers, so I checked using pngcheck, but it says that the png file is OK. Any idea why this might be happening? I've also had trouble loading thisimageHowever it works with other images, is there any way I can avoid this in future?
There was an issue opened787for this and was fixed on a newer version (2.27)
I was wondering if there is a macros that I can use to place a global variable in another section. i.e my_array would be stored in bss. since it's uninitialized but I want to place it in .data section instead. ``` uint8_t my_array[]; int main() { return 1; } ```
If you're using gcc, you can use the__section__attribute to set the section: ``` __attribute__((__section__(".data"))) uint8_t my_array[5]; ``` Note that you'll also need to set a size for it, otherwise you only have a declaration instead of a definition.
Alloc N * N int array in C, When N = 1024, It Just Workd, When N = 2048, I get "segmentation fault ". The machine is Ubuntu 20.04 with 2GB memory. Is my memory not big enough? ``` 1 #include <stdio.h> 2 3 #define N 1024 4 5 int main() 6 { 7 int arr[N][N]; 8 9 for (int i = 0; i < N; i++) 10 for (int j = 0; j < N; j++) 11 arr[i][j] = i + j; 12 13 return 0; 14 } ```
Put the decleration of arr outside of main. As it is now you are running out of stack space.
I used a C / C++ code from the Internet, but my IDE gives me the following error on macos: ``` Use of undeclared identifier cfmakeraw ``` I now face the question, whether cfmakeraw is available on Macos / Unix ? Thank you 🙏
On your Mac, fire up Terminal and runman cfmakeraw. ``` SYNOPSIS #include &lttermios.h> void cfmakeraw(struct termios *termios_p); ``` So it is available, but you must include<termios.h>.
how can I debug STM32 board usinggdbwithoutstlinkor any other device. actually I am trying to design an equipment which can replace the STMC device, since ST was stopped making this devices
You cannot debug a bare metal system without a debugger. STM32 support JTAG, SWD debuggers. You still can program it without a programmer/debugger (using the integrated bootloader if present in your model) and put your debug string on an uart, but no conventional debuggin, so no gdb.
I am looking for a way to set a background image in gtk + 3 with c language , I already search and all the answer are for other languages or don't work anymore . Does anyone know a proper way to do it ?
For all problem encounter with the style in gtk i realize that using css for gtk wase the best answer , here some link that can be good to know Css + Gtk Overview Gtk + Css Properties
If I have 3 files: ``` header1.h header2.h header3.h ``` And I did#include "header1.h"in header2.h, then if I do#include "header2.h"in header3.h does header3.h have header1.h's declarations?
Yes, provided that there are no conditional compiling statements that may prevent such inclusions from happening. For example, in this situation, header1.h won't be included from header3: header2: ``` ... #ifndef THING #include "header1.h" #endif ... ``` header3: ``` ... #define THING #include "header2.h" ... ```
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.Closed3 years ago.Improve this question Is there a more elegant way to do something like this: ``` if(millis() - time >= 100) { time = millis(); if(toggle == 1){ dothis(); toggle = 0; } else { dothat(); toggle = 1; } } ```
Close to a matter of taste. IMHO the common way for toggling istoggle = 1 - toggle;. And if performance matters, dereferencing is normally more efficient than a test, so you could build a array of (pointers to) functions: ``` typedef void (*dofunc)(void); dofunc func[] = {&dothat, &dothis}; ... int toggle = 0; ... if((t = millis()) - time >= 100) { time = t; func[toggle](); toggle = 1 - toggle; } ```
We are supporting two modes of builds (32 & 64 bit). For that we are having two targets: For 32 bit we havemake32 For 64 bit we havemake64 Whenever user try to runmakecommand withmake32, It will run32bitbuild and same way for withmake64it will run64bitbuild. We have another target calledmakebothwhich runs both 32 & 64 bit builds sequentially. ``` makeboth: $(MAKE) make32 $(MAKE) make64 ``` Above make snippet is in top level GNUmakefile, where we are running several makefiles inside its child directories. I want to run both 32 & 64 bit builds in parallel when user passes targetmakeboth.Is it possible to do that ? Can anyone one please help here.
Arrange it so thatmakebothhas the other two as prerequisites. ``` makeboth: make32 make64 @echo makeboth done ``` Thenmake -jN makebothshould do the parallel build.
so I'm using NCurses for a project and the terminal I'm using it on accepts special escape sequences for custom features like playing audio. The position of the cursor doesn't matter while sending these escape sequences, however when using printf it doesn't get pushed to the output stream. Is there a way to write to bypass ncurses and write to the terminal directly? I heard about possibly restoring the streams and after giving them back to ncurses but that seems hacky.
I ended up finding a hacky solution since I only needed the escape codes to besentto the terminal emulator (cursor position & other context didn't matter) I used fputs to write to STDOUT and then used fflush() to push it to the terminal. ``` fputs("\033]16;2", stdout); fflush(stdout); ```
I used a C / C++ code from the Internet, but my IDE gives me the following error on macos: ``` Use of undeclared identifier cfmakeraw ``` I now face the question, whether cfmakeraw is available on Macos / Unix ? Thank you 🙏
On your Mac, fire up Terminal and runman cfmakeraw. ``` SYNOPSIS #include &lttermios.h> void cfmakeraw(struct termios *termios_p); ``` So it is available, but you must include<termios.h>.
how can I debug STM32 board usinggdbwithoutstlinkor any other device. actually I am trying to design an equipment which can replace the STMC device, since ST was stopped making this devices
You cannot debug a bare metal system without a debugger. STM32 support JTAG, SWD debuggers. You still can program it without a programmer/debugger (using the integrated bootloader if present in your model) and put your debug string on an uart, but no conventional debuggin, so no gdb.
I am looking for a way to set a background image in gtk + 3 with c language , I already search and all the answer are for other languages or don't work anymore . Does anyone know a proper way to do it ?
For all problem encounter with the style in gtk i realize that using css for gtk wase the best answer , here some link that can be good to know Css + Gtk Overview Gtk + Css Properties
If I have 3 files: ``` header1.h header2.h header3.h ``` And I did#include "header1.h"in header2.h, then if I do#include "header2.h"in header3.h does header3.h have header1.h's declarations?
Yes, provided that there are no conditional compiling statements that may prevent such inclusions from happening. For example, in this situation, header1.h won't be included from header3: header2: ``` ... #ifndef THING #include "header1.h" #endif ... ``` header3: ``` ... #define THING #include "header2.h" ... ```
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.Closed3 years ago.Improve this question Is there a more elegant way to do something like this: ``` if(millis() - time >= 100) { time = millis(); if(toggle == 1){ dothis(); toggle = 0; } else { dothat(); toggle = 1; } } ```
Close to a matter of taste. IMHO the common way for toggling istoggle = 1 - toggle;. And if performance matters, dereferencing is normally more efficient than a test, so you could build a array of (pointers to) functions: ``` typedef void (*dofunc)(void); dofunc func[] = {&dothat, &dothis}; ... int toggle = 0; ... if((t = millis()) - time >= 100) { time = t; func[toggle](); toggle = 1 - toggle; } ```
We are supporting two modes of builds (32 & 64 bit). For that we are having two targets: For 32 bit we havemake32 For 64 bit we havemake64 Whenever user try to runmakecommand withmake32, It will run32bitbuild and same way for withmake64it will run64bitbuild. We have another target calledmakebothwhich runs both 32 & 64 bit builds sequentially. ``` makeboth: $(MAKE) make32 $(MAKE) make64 ``` Above make snippet is in top level GNUmakefile, where we are running several makefiles inside its child directories. I want to run both 32 & 64 bit builds in parallel when user passes targetmakeboth.Is it possible to do that ? Can anyone one please help here.
Arrange it so thatmakebothhas the other two as prerequisites. ``` makeboth: make32 make64 @echo makeboth done ``` Thenmake -jN makebothshould do the parallel build.
so I'm using NCurses for a project and the terminal I'm using it on accepts special escape sequences for custom features like playing audio. The position of the cursor doesn't matter while sending these escape sequences, however when using printf it doesn't get pushed to the output stream. Is there a way to write to bypass ncurses and write to the terminal directly? I heard about possibly restoring the streams and after giving them back to ncurses but that seems hacky.
I ended up finding a hacky solution since I only needed the escape codes to besentto the terminal emulator (cursor position & other context didn't matter) I used fputs to write to STDOUT and then used fflush() to push it to the terminal. ``` fputs("\033]16;2", stdout); fflush(stdout); ```
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.Closed3 years ago.Improve this question Is there a more elegant way to do something like this: ``` if(millis() - time >= 100) { time = millis(); if(toggle == 1){ dothis(); toggle = 0; } else { dothat(); toggle = 1; } } ```
Close to a matter of taste. IMHO the common way for toggling istoggle = 1 - toggle;. And if performance matters, dereferencing is normally more efficient than a test, so you could build a array of (pointers to) functions: ``` typedef void (*dofunc)(void); dofunc func[] = {&dothat, &dothis}; ... int toggle = 0; ... if((t = millis()) - time >= 100) { time = t; func[toggle](); toggle = 1 - toggle; } ```
We are supporting two modes of builds (32 & 64 bit). For that we are having two targets: For 32 bit we havemake32 For 64 bit we havemake64 Whenever user try to runmakecommand withmake32, It will run32bitbuild and same way for withmake64it will run64bitbuild. We have another target calledmakebothwhich runs both 32 & 64 bit builds sequentially. ``` makeboth: $(MAKE) make32 $(MAKE) make64 ``` Above make snippet is in top level GNUmakefile, where we are running several makefiles inside its child directories. I want to run both 32 & 64 bit builds in parallel when user passes targetmakeboth.Is it possible to do that ? Can anyone one please help here.
Arrange it so thatmakebothhas the other two as prerequisites. ``` makeboth: make32 make64 @echo makeboth done ``` Thenmake -jN makebothshould do the parallel build.
so I'm using NCurses for a project and the terminal I'm using it on accepts special escape sequences for custom features like playing audio. The position of the cursor doesn't matter while sending these escape sequences, however when using printf it doesn't get pushed to the output stream. Is there a way to write to bypass ncurses and write to the terminal directly? I heard about possibly restoring the streams and after giving them back to ncurses but that seems hacky.
I ended up finding a hacky solution since I only needed the escape codes to besentto the terminal emulator (cursor position & other context didn't matter) I used fputs to write to STDOUT and then used fflush() to push it to the terminal. ``` fputs("\033]16;2", stdout); fflush(stdout); ```
I wrote this code in Sublime: ``` int main (int argc, char **argv) { printf("Hello World"); return 0; } ``` Saved it atC:\cygwin64\home\userashelloworld.c. Typed in this on Cygwin64 Terminal:$ gcc -o helloworld helloworld.c But I'm not seeing any output.Please help.
The windows executable can be obtained by:$ ./helloworld
This question already has answers here:Using Quick Sort in C to sort in reverse direction (descending)?(3 answers)Closed3 years ago. ``` void sort_array(void) { int sorted_arr[arr_count]; qsort(sorted_arr, arr_count, sizeof(*sorted_arr), compare_qsort); return; } ``` I can't figure out how to use qsort in reverse can anyone help me?
This would be how I would solve it: ``` int compare_qsort(const void *pointer1, const void *pointer2) { //Returns a sorted array in descending order. const int *pointeri = pointer1; const int *pointerj = pointer2; return *pointerj - *pointeri; } ``` Notice how you flip it so that thepointerjvariable is subtracting thepointerivariable. I found this other question that you could refer to:Using Quick Sort in C to sort in reverse direction (descending)?
Here's the idea of the code: The code is required to make a random number then keepon spouting random numbers until it reaches that number, but its always the same. heres the code: ``` #include <stdio.h> #include <math.h> int rdt () { long long int randomonium; randomonium=rand(); return randomonium; } int main (){ int rd; int no; while(1){ rd=rand(); printf("%d\n", rd); if (rd== rdt()){ break; } } return 0; } ```
You can put asrand(time(NULL));just before thewhileto change the random seed used byrand(). Don't forget to includetime.hin the code.
I am trying to get the contents of my adc register for debugging but I don't know how to print it with gdb. If the address register offset is0x08would I usep/x *0x08? I am getting a result but it is 64 bits and I'm expecting 32. Thanks.
Turns out I was trying to find the wrong address and using a confusing hex to binary converter. Thanks to @Eugene Sh. for helping.
Here's the idea of the code: The code is required to make a random number then keepon spouting random numbers until it reaches that number, but its always the same. heres the code: ``` #include <stdio.h> #include <math.h> int rdt () { long long int randomonium; randomonium=rand(); return randomonium; } int main (){ int rd; int no; while(1){ rd=rand(); printf("%d\n", rd); if (rd== rdt()){ break; } } return 0; } ```
You can put asrand(time(NULL));just before thewhileto change the random seed used byrand(). Don't forget to includetime.hin the code.
I am trying to get the contents of my adc register for debugging but I don't know how to print it with gdb. If the address register offset is0x08would I usep/x *0x08? I am getting a result but it is 64 bits and I'm expecting 32. Thanks.
Turns out I was trying to find the wrong address and using a confusing hex to binary converter. Thanks to @Eugene Sh. for helping.
The symbols -> appear in a line of code that I am trying to understand and someone told me it is a pointer. ``` *data = (uint8_t)base->FIFORD; ``` My interpretation is that the 8 bit integer pointer base points to a register called FIFORD. The value in FIFORD is then assigned to the pointer data. Is this correct? BONUS: If I wanted to store the values from FIFORD in a buffer to print, what would I need to do? Thanks much!
In your example, "base" is a pointer to a structure. There are two ways you can access variables in a structure with its pointer (base): (*base).FIFORDbase -> FIFORD Both do the same thing In this case, the FIFORD variable in the struct is extracted, casted to uint8_t and assigned to a, hopefully (Too little context to say), uint8_t pointer called data.
So this is the code i came up with but why is this not getting accepted as a valid solution on codechef. Constraints have been taken care of and both i/o formats are correct. THIS IS JUST A SIMPLE PRACTICE QUESTION NOT A CONTEST QUESTION. Thank you. ``` #include<stdio.h> int main(void) { int T; scanf("%d", &T); while (T > 0 && T < 10) { int N; int sum = 0; scanf("%d", &N); for (int i = 0;i < N;i++) { int A; scanf("%d", &A); sum += A; } if (sum%N == 0 ) printf("Yes\n"); else printf("No\n"); T--; } return 0; } ```
The problem specification says “1 ≤T≤ 10”. When the inputTis 10, the program in this question prints no output, because the codewhile (T > 0 && T < 10)never executes the body of the loop, sinceT < 10is false.
I am wondering if the complexity of this code is O(n) or is it O(count*n)? I made the parameter count and it is not dependent on the parameter n as you could see: ``` void change(int A[], int n, int x) { int i, j, count=0; for(i=0; i<n; i++) { if(A[i]==x) { count++; } } for(i=0; i<count; i++){ for(j=0; j<n-i; j++){ printf("Hello World"): } } } ```
The first loop isTheta(n). The time complexity of the second loop (as you've found depends on the value ofcount) is: ``` T(n) = n + (n-1) + ... + (n-count) = O(n * count) ``` Therefore, the final time complexity isO(n * count). And ascount = O(n), we can say the time complexity isO(n^2)in terms ofn.
I am trying to produce .h file from .wsdl using gsoap: ``` wsdl2h.exe -v -s -c++11 -o a.h a.wsdl ``` Witha.wsdlit is working like a charm, but withb.wsdlI am getting the unfriendly error: ``` SOAP 1.1 fault SOAP-ENV:Client [no subcode] "End of file or no input: message transfer interrupted" Detail: [no detail] ``` Any idea how to find out a rootcause of this? I suppose it is something with .wsdl or .xsd file, but how to identify it? Both .wsdl files are not created by me, but on first sight they look fine. When I imported problematic b.wsdl into SOAPUI i was able to send request / receive response. I also tried this web: https://www.wsdl-analyzer.com/ But unsuccesfully, it is showing me error also on a.wsdl which works fine with gSoap.
It was some whitespace which was preventing wsdl2h in parsing the wsdl / xsd file.
uintptr_tandintptr_tare numerical types big enough to contain pointers, my question is how do they relate to other numerical types when casting toward them. Specifically which types (int,long,long long,short,char,size_tetc.) cantNUM_TYPEbe defined as so that the next function does not corrupt the value ofn? ``` intptr_t cast_num(NUM_TYPE n){return (intptr_t) n;} ```
The optional types: intptr_thas a range ofat least[-0x7FFF...0x7FFF]. uintptr_thas a range of [0...at least0xFFFF]. UseINTPTR_MIN, INTPTR_MAX, UINTPTR_MAXfrom<stdint.h>to form condition code as needed. ``` intptr_t cast_long(unsigned long n) { _Static_assert(UIINTPTR_MAX >= ULONG_MAX, "unsigned long too big"): return (intptr_t) n; } ``` Note: Object pointers to/fromuintptr_tandintptr_tshould be converted throughvoid *. Function pointers may be too big.
I have the following code snippet for a PIC controller: ``` void __interrupt() ISR(void { // do some stuff } ``` when I use PC-Lint I always get the error message: Error 10: Expecting identifier or other declarator What can I do to handle the interrupt in PC-Lint?
You can define a dummy preprocessor macro by using the option-d__interrupt()=
I got this flowchart from a book on C. I get the differences between headers and libraries, however in my understanding shouldn't header files be the code before compilation and not library files.I still don't understand this flowchart 100%. Is it wrong or am I the one wrong here? EDIT: The name of the book is "Introduction to C Programming" by "Reema Thareja"
It looks like you are right: the ones in red (the one below too) should be header files.
I was just compiling a C file and made a typo: swappedargc[0]forargv[0]. This, of course, gave me an error message from gcc: ``` SlidingWindow_file.c:443:29: error: subscripted value is neither array nor pointer nor vector ``` This error message makes perfect sense to me, except for one thing: What is a vector in the context of plain C (seeing as how this was a C file, not C++)? I can't seem to find any information about such a thing.
vectorin that error message refers togcc vector extensions.
I'm trying to understand how to use the Linux kernel spinlocks. From reading the header, I think I have to first declare one and initialize it like this withspin_lock_init: ``` spinlock_t xxx_lock; spin_lock_init(&xxx_lock); ``` and then I can lock and unlock it withspin_lockandspin_unlock. I hope what I understood until here is correct. But what do I have to do to "invert" thespin_lock_init? How do I destroy the spinlock?
A spinlock doesn't require special finalization function (destructor). When a spinlock isunlocked, it isn't used by the kernel internally. So, if you don't intend to use an unlocked spinlock anymore, just forget about it.
I foundthis example; here the two threads threadDefault and threadCustomized are terminated by using pthread_exit followed by return. Why did the author write both instructions?
Mohith Reddy's answer is correct but misses the point. Of course the return statement is never executed sincepthread_exitdoesn't return, but it's there to suppress warnings from the compiler in case it's not aware thatpthread_exitdoesn't return.
What I have till now is this. I am not able to figure out how to take the input as mentioned and solve this problem? ``` #include<stdio.h> #include <stdlib.h> #include<float.h> int main() { char s[50]; float mil,min=FLT_MAX; while(scanf("%s@%f",s,&mil)!=-1) { printf("%s\n",s); if(mil<min) min=mil; } } ``` EDIT: My problem is that when I print the stringsinside the loop, "[email protected]" is printed whereas I want only "Zantro" to be stored insand 16.15 to be stored inmil
%sscans up until a whitespace. Scan up until a@instead. ``` while (scanf("%[^@]@%f", s, &mil) == 2) ``` Remember to specify the maximum buffer size in the scanning format to protect against overflows: ``` while (scanf("%49[^@]@%f", s, &mil) == 2) ```
The following is my code written in c language where I am trying to take strings as input and store them in a 2d array. ``` #include<stdio.h> #include<stdlib.h> #include<string.h> int main(){ int i,j,n; scanf("%d",&n); char a[n][n]; for(i=0;i<n;i++){ scanf(" %[^\n]",a[i]); } for(i=0;i<n;i++){ printf("%s\n",a[i]); } } ``` below is my input41112191218921234 my excepted output should look like below1112191218921234 the output which I am getting is below1112191218921234191218921234189212341234 can anyone explain what is wrong in my code? any help would be appreciated! thanks:)
You need to change: ``` char a[n][n]; ``` Into: ``` char a[n][n + 1]; ``` For a null-terminator. Without that, the char array won't be terminated and keep printing. You'll get the correct output afterwards: ``` $ gcc -o prog prog.c; ./prog 4 1112 1912 1892 1234 ```
How can I make .gif file from list of images (frames) on the computer drive using C? (It's better if it's using ImageMagick Library) Thanks In Advance.
With ImageMagick, you would read each frame into the stack, and then write a GIF with an adjoin option. ``` MagickWand * wand; wand = NewMagickWand(); MagickReadImage(wand, "frame_one.png"); MagickReadImage(wand, "frame_two.png"); MagickReadImage(wand, "frame_three.png"); MagickWriteImages(wand, "output.gif", MagickTrue); ``` Be sure to invokeMagickWandGenesis()before working with ImageMagick library, andMagickWandTerminus()at the end of the application. Also check which version of ImageMagick you wish to compile with: #include <wand/MagickWand.h>for ImageMagick-6#include <MagickWand/MagickWand.h>for ImageMagick-7 (preferred)
I'm just starting out teaching myself C I've learned that it is usual to create constants in mylib.h using #define CONSTANT = value However when I try to use that value I get a complete failure. Below I added the code of my mylib.h ``` #define MYLIB_H #include <stdio.h> #include <math.h> #include <stdlib.h> #include <stdbool.h> #define N_PEOPLE = 10 typedef struct { int status; int days; } Person; typedef struct { Person p[N_PEOPLE]; int sick; int healthy; int dead; int imune; } Model; int solve ( int test); ``` In this instance the code doesn't work. when I replace the linePerson p[N_PEOPLE];byPerson p[10];It does work.
When expanded,Person p[N_PEOPLE];will becomePerson p[= 10];. This is a syntax error. Remove the=from the definition: ``` #define N_PEOPLE 10 ```
The following is my code written in c language where I am trying to take strings as input and store them in a 2d array. ``` #include<stdio.h> #include<stdlib.h> #include<string.h> int main(){ int i,j,n; scanf("%d",&n); char a[n][n]; for(i=0;i<n;i++){ scanf(" %[^\n]",a[i]); } for(i=0;i<n;i++){ printf("%s\n",a[i]); } } ``` below is my input41112191218921234 my excepted output should look like below1112191218921234 the output which I am getting is below1112191218921234191218921234189212341234 can anyone explain what is wrong in my code? any help would be appreciated! thanks:)
You need to change: ``` char a[n][n]; ``` Into: ``` char a[n][n + 1]; ``` For a null-terminator. Without that, the char array won't be terminated and keep printing. You'll get the correct output afterwards: ``` $ gcc -o prog prog.c; ./prog 4 1112 1912 1892 1234 ```
How can I make .gif file from list of images (frames) on the computer drive using C? (It's better if it's using ImageMagick Library) Thanks In Advance.
With ImageMagick, you would read each frame into the stack, and then write a GIF with an adjoin option. ``` MagickWand * wand; wand = NewMagickWand(); MagickReadImage(wand, "frame_one.png"); MagickReadImage(wand, "frame_two.png"); MagickReadImage(wand, "frame_three.png"); MagickWriteImages(wand, "output.gif", MagickTrue); ``` Be sure to invokeMagickWandGenesis()before working with ImageMagick library, andMagickWandTerminus()at the end of the application. Also check which version of ImageMagick you wish to compile with: #include <wand/MagickWand.h>for ImageMagick-6#include <MagickWand/MagickWand.h>for ImageMagick-7 (preferred)
I'm just starting out teaching myself C I've learned that it is usual to create constants in mylib.h using #define CONSTANT = value However when I try to use that value I get a complete failure. Below I added the code of my mylib.h ``` #define MYLIB_H #include <stdio.h> #include <math.h> #include <stdlib.h> #include <stdbool.h> #define N_PEOPLE = 10 typedef struct { int status; int days; } Person; typedef struct { Person p[N_PEOPLE]; int sick; int healthy; int dead; int imune; } Model; int solve ( int test); ``` In this instance the code doesn't work. when I replace the linePerson p[N_PEOPLE];byPerson p[10];It does work.
When expanded,Person p[N_PEOPLE];will becomePerson p[= 10];. This is a syntax error. Remove the=from the definition: ``` #define N_PEOPLE 10 ```
I was wondering how void pointers are implemented. I tried to find it out on Godbolt with x86-64 (you can see ithere), but it didn't reveal anything. How are void pointers implemented? Edit:This is the code I used: ``` int main() { int volatile y = 123; void* volatile x = &y; } ``` All I was trying to see here is whatxwould look like. I put volatile so that gcc wouldn't eliminate it as dead code.
Generally speaking, all pointers on an x86-64 processor are simply 8 byte values containing some memory address. Only the compiler cares about what they point it.
I am getting input with the format: ``` <string 1> <string 2> ``` For example, "hello world". I have a length limit for both strings. Is there a quick way to put the strings in separate variables? At the end I am comparingstring 1with some other string, and until it matches I keep getting more strings (with the same format) from the user. Thanks a lot.
Accept the input from the user by formattingscanf()function as shown: ``` #include <stdio.h> #define MAX 100 int main(void) { char str1[MAX], str2[MAX]; printf("Enter two words separated by spaces: "); scanf("%s %s", str1, str2); // here's the main stuff printf("Variable 1 now contains: %s\n", str1); printf("Variable 2 contains: %s\n", str2); return 0; } ``` A sample output: ``` Enter two words separated by spaces: Hello World Variable 1 now contains: Hello Variable 2 contains: World ```
This question already has answers here:Is NULL always zero in C?(5 answers)Closed3 years ago. For exampleint *p = NULL;andint **pp = NULL;, p and pp all point to the address 0?
After type adjustments (appropriate casts or casts to some void pointer) to satisfyconstraintsthey'll compare equal to each other and equal to the null pointer constant (i.e.,0, some other integer constant expression equal to0or the same cast to(void*)0). Whether those differently typed null pointers will have the same representation and whether that representation is all-bits zero is technically unspecified. IOW, the following will always hold: ``` p == (void*)pp && p == 0 && pp == 0 //TRUE ``` but this might not (although it does on most platforms): ``` (uintptr_t)p == 0 && (uintptr_t)pp == 0 && 0==memcmp(&p, (char[sizeof(p)]){0}, sizeof(p)) && 0==memcmp(&pp, (char[sizeof(pp)]){0}, sizeof(pp)) //COULD BE FALSE ```
This question already has answers here:Is NULL always zero in C?(5 answers)Closed3 years ago. For exampleint *p = NULL;andint **pp = NULL;, p and pp all point to the address 0?
After type adjustments (appropriate casts or casts to some void pointer) to satisfyconstraintsthey'll compare equal to each other and equal to the null pointer constant (i.e.,0, some other integer constant expression equal to0or the same cast to(void*)0). Whether those differently typed null pointers will have the same representation and whether that representation is all-bits zero is technically unspecified. IOW, the following will always hold: ``` p == (void*)pp && p == 0 && pp == 0 //TRUE ``` but this might not (although it does on most platforms): ``` (uintptr_t)p == 0 && (uintptr_t)pp == 0 && 0==memcmp(&p, (char[sizeof(p)]){0}, sizeof(p)) && 0==memcmp(&pp, (char[sizeof(pp)]){0}, sizeof(pp)) //COULD BE FALSE ```
Inthis tutorialit shows the following example for exporting C functions ``` ./emcc tests/hello_function.cpp -o function.html -s EXPORTED_FUNCTIONS='["_int_sqrt"]' -s EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]' ``` I would like to do the same except that I use CMake like this ``` cd bin emcmake cmake ../src emmake make ``` What is the canonical way of specifying-sin emmake? Should I add it toCMakeLists.txtlike ``` set(EXPORTED_FUNCTIONS '["_int_sqrt"]') ``` or do something similar?
This is the simplest/cleanest way now: ``` target_link_options(target PRIVATE -sEXPORTED_FUNCTIONS=['_main','_foo','_bar']) ``` And if you have more -s settings (and you probably will) you can add them within this function call, or you can call target_link_options multiple times, both work. It seems quite accommodating, I haven't needed to escape anything.
Can I use a variable to define an array's size? ``` int test = 12; int testarr[test]; ``` Would this work, I don't want to change the size of the array after initialization. Theint test's value isn't known at compile time.
From C99 it is allowed but only for the automatic variables. this is illegal: ``` int test = 12; int testarr[test]; // illegal - static storage variable int foo(void) { int test = 12; static int testarr[test]; // illegal - static storage variable } ``` the only valid form is: ``` int foo(void) { int test = 12; int testarr[test]; // legal - automatic storage variable } ```
Here's the program: ``` #include <stdio.h> main() { printf("%d", "A"); // Can i know what the output from "printf" even means why the output is so strange } // this outputs: "4214884" in my compiler ``` As you see the output is so strange and can anyone of you explain this to me. Is this undefined behavior? Is this behavior described anywhere in theC standardso I can read about it
Yes, thisisundefined behaviour.%dexpects the argument to be an integer, here what you pass is the address of the first element of a string literal, which is a pointer type. As perC11,chapter 7.21.6.1/P9 [...]If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. That said, for a hosted environment,main()should beint main(void).
I'm trying to solve a C operation in one step without using a loop. I have: ``` unsigned int8 Dummy = 0x3F;//This values are for reference only, so can be different unsigned int8 Dummy_2 = 0x02; Dummy = Dummy ^ Dummy_2; ``` Now Dummy = 0x3D I must to set the Dummy bits to 0 the bits that are 1 in Dummy_2. My code works ok the first time but if I perform the code two times it toggles back to 1. I can do this with a loop but for the clarity of the code I'm trying to do it in one line.
I'd negate(*)Dummy_2and then use that as a mask: ``` Dummy &= (~Dummy_2); ``` (*) EDIT:As the busybee pointed out in the comments, "negate" is an arithmetic term. The proper term here would be "to complementDummy_2.
Can I use a variable to define an array's size? ``` int test = 12; int testarr[test]; ``` Would this work, I don't want to change the size of the array after initialization. Theint test's value isn't known at compile time.
From C99 it is allowed but only for the automatic variables. this is illegal: ``` int test = 12; int testarr[test]; // illegal - static storage variable int foo(void) { int test = 12; static int testarr[test]; // illegal - static storage variable } ``` the only valid form is: ``` int foo(void) { int test = 12; int testarr[test]; // legal - automatic storage variable } ```
Here's the program: ``` #include <stdio.h> main() { printf("%d", "A"); // Can i know what the output from "printf" even means why the output is so strange } // this outputs: "4214884" in my compiler ``` As you see the output is so strange and can anyone of you explain this to me. Is this undefined behavior? Is this behavior described anywhere in theC standardso I can read about it
Yes, thisisundefined behaviour.%dexpects the argument to be an integer, here what you pass is the address of the first element of a string literal, which is a pointer type. As perC11,chapter 7.21.6.1/P9 [...]If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. That said, for a hosted environment,main()should beint main(void).
I'm trying to solve a C operation in one step without using a loop. I have: ``` unsigned int8 Dummy = 0x3F;//This values are for reference only, so can be different unsigned int8 Dummy_2 = 0x02; Dummy = Dummy ^ Dummy_2; ``` Now Dummy = 0x3D I must to set the Dummy bits to 0 the bits that are 1 in Dummy_2. My code works ok the first time but if I perform the code two times it toggles back to 1. I can do this with a loop but for the clarity of the code I'm trying to do it in one line.
I'd negate(*)Dummy_2and then use that as a mask: ``` Dummy &= (~Dummy_2); ``` (*) EDIT:As the busybee pointed out in the comments, "negate" is an arithmetic term. The proper term here would be "to complementDummy_2.
I have the same question asthis one, except I'm writing C. How can I initialize a literal number to have the typesize_t? Basically, I have a macro that amounts to this: ``` #define myprint(S) { printf("hello %zu", S); } ``` and I would like to use it like this: ``` myprint(0); ``` But I'm getting the message: format '%zu' expects argument of type 'size_t', but argument has type 'int' I've tried writing0lu, but it does not work for all architectures.
There's no suffix specific tosize_t. You'll need to use a cast instead. ``` #define myprint(S) { printf("hello %zu", (size_t)S); } ``` Given how this is used, it's the best way to do it anyway.
I'm recoding printf and I have to respect a norm to not have more that 80 characters per line but my array of pointers to function is more than that so I'm wondering if there is way to split the inialization and the declaration of my array of pointers to function here is my array ``` void (*tfnc[8]) (va_list *, s_struct *) = {conv_c, conv_s, conv_p, conv_id, conv_id, conv_u, conv_x, conv_X}; ```
What's wrong with breaking down the statement to use more than one line? ``` void (*tfnc[8]) (va_list *, s_struct *) = {conv_c, conv_s, conv_p, conv_id, conv_id, conv_u, conv_x, conv_X}; ```
I want to read an unknown number of characters, which are not greater than 10. ``` char word[10]; for( i=0;i<10;i++){ if( !scanf("%c",&word[i])){ //terminate with 0 getchar(); break; } } ``` The problem is that number is also an character, so the if statement won't be executed. Is there any other solution to terminate the input of characters for example with 0.
Suggest: ``` char word[10]; if( scanf("%9s",word) != 1 ) { fprintf( stderr, "scanf for (max 9 char word) failed\n" ); exit( EXIT_FAILURE ); } ``` using%9sbecause the%sinput format conversion specifier always appends a NUL byte to the input. If the input is less than 9 characters, that is properly handled. If the input is greater than 9 characters, the9modifier will stop the input, so the input buffer is not overflowed. Such an overflow would result in undefined behavior.
I'd like to know where the function__cpuid_countis on osx. I'm assuming that it's inlibcbut running: ``` nm -g /usr/lib/libc.dylib ``` or ``` nm -g /usr/lib/libSystem.B.dylib ``` Does not list the function in the outputs. Is there a better way to locate where it is?
You can't find a__cpuid_countfunction because there isn't one. It's defined as a macro that expands to inline assembly incpuid.h.
signed: ``` short convetToSignedShort(uint8_t first, uint8_t second) { signed short j; j = (signed char)first + (signed char)second; printf("signed short: %d\n", j); return j; } ``` unsigned: ``` short convetToUnsignedShort(uint8_t first, uint8_t second) { unsigned short j; j = (unsigned short)first + (unsigned short)second; printf("unsigned short: %d\n", j); return j; } ``` I know that I am not using the correct way. I need for example0x01 0x01to be257, how can I do that?
Do something like this for unsigned: ``` uint16_t convertToUnsignedShort(uint8_t high, uint8_t low) { uint16_t j; j = ((uint16_t)high << 8) + (uint16_t)low; printf("unsigned short: %d\n", j); return j; } ``` For signed it makes less sense. What do you expect to happen with the sign bit of the low byte?
I'm reading through a library and found an enumeration that looks like this: ``` typedef enum { IS_SYNCED = 0; //Determines if device is in/out of sync IS_VALID_REF = 1; //Determines if device reference is valid } EVENT; ``` I'm wondering how the to check what the value ofIS_SYNCEDwould be?
You can compare enum values with==. ``` EVENT e = IS_SYNCED; if(e == IS_SYNCED) printf("Is synced event\n"); else if(e == IS_VALID_REF) printf("Is valid ref event\n"); else printf("Unknown event\n"); ``` prints: ``` Is synced event ``` You can also useswitch: ``` EVENT e = IS_SYNCED; switch(e) { case IS_SYNCED: printf("Is synced event\n"); break; case IS_VALID_REF: printf("Is valid ref event\n"); break; default: printf("Unknown event\n"); break; } ```
I tried installing CygWin64, but I cannot find any executables to build my code with in the C:\cygwin64 directory created. I tried Win-Builds but the setup doesn't load with any mirror I give it. It tries to connect 3 times then aborts. I tried MinGW-W64-Builds, but I cannot figure out how to install it. I can see a .sh file there, but I believe that is for Linux, so I do not know why because it says it is for Windows Is there even a way to use 64-bit GCC on Windows? I am trying to tie it to a Code::Blocks IDE as that one only comes with the 32-bit version of MinGW.
Check out out the MinGW-w64 + GCC personal build athttp://winlibs.com/. No installation required, just unzip. Examples on how to use are on the site, including on how to integrate with Code::Blocks IDE.
So in need to get a value between 1 and 8 (both inclusive). So I wrote a simple do/while loop in C. ``` #include <stdio.h> #include <cs50.h> int main(void) { int height; do { height = get_int("Height: "); }while (height > 9); } ``` Now this works and repeats until the value is below 9. But as soon I change the condition for the while from ``` while (height > 9); ``` to ``` while (height > 9 && height <0); ``` it starts to accept numbers higher than 9. Why is this happening and how can I fix it?
Changingwhile (height > 9 && height < 0towhile (height > 9 || height < 0)should do the trick. Ponder over it.
I have encountered some code doing this: ``` double a(30.0); char buff[30]; sprintf(buff , "%.4f%", a); std::cout << std::string(buff) << "!\n"; ``` Basically I was wondering about the trailing%, issprintf()defining what would happen if nothing follows a%?
I believe it leads to undefined behaviour. C11 Section 7.21.6.1 paragraph 4 says: After the %, the following appear in sequence:[...]— Aconversion specifiercharacter that specifies the type of conversion to be applied. Later, paragraph 9 says: If a conversion specification is invalid, the behavior is undefined. In your example, the percent sign is not followed by a conversion specifier, which I take to imply the specification is invalid, thus leading to undefined behaviour.
I can't add 5 to the file. I know that if you add 5 to the array, it will solve the problem. But I need no array. ``` int main(void) { FILE* a = fopen("bin.bin", "wb"); int b = 5; fwrite(b, sizeof(int), 1, a); fclose(a); } ```
I'm justguessinghere, but I think you get a build error because the first argument tofwriteshould be a pointer, but you provide anintvalue instead. This is easily solved by using the address-of operator&to get a pointer to the variableb: ``` fwrite(&b, sizeof b, 1, a); ```
Simple question but I couldn't find any full answer online. I have 3 projects, my desire outcome is that I run make and all 3 programs are transformed into executable files. ``` gcc -o server server.c gcc -o server2 server2.c gcc -o server3 server3.c ``` Is this achievable? How?
Thanks to @MadScientist for answering my question in the comments. I wish I could give him rep for this answer. The Makefile that worked for me was ``` .PHONY: all server server2 server3 all: server server2 server3 server: server.c gcc -o server server.c server2: server2.c gcc -o server2 server2.c server3: server3.c gcc -o server3 server3.c ``` After Makefile is created, entermakein the command line to execute the 3 gcc commands. By defaultmakewill callmake allwhich in sort will call server, server2, server3 as defined on this lineall: server server2 server3. I'm still not sure what.PHONYis all about.
I'm trying to write a script that parses the functions in a file, and in particular, the parameters of each function. So for example, if file X.c has function func(int a, char b), then I want to see output like ``` func int a char b ``` ctags gets me very close: ``` ctags -x --c-types=f file.c ``` shows me: ``` func function 106 file.c func ``` which is great, because file.c has a whole bunch of goofball macros and typedefs that confuse most C parsers. So is there a way to get ctags to show the parameters for a given function? All of the examples I've seen are for generating tag files, which I don't want to do.
It took me a while to find the answer, but the trick is to usectags-universal, which is an updated version of ctags. ctags-universal -x --c-kinds=f --_xformat="%N %S"filename
What is the difference between this: ``` int num = 5; int* num1 = &num; printf("%p", num1); ``` and this: ``` int num = 5; int* num1 = &num; printf("%p", &num1); ```
In the first case,printf("%p", num1);, you're printing the value ofnum1, which is the address ofnum. In the second case,printf("%p", &num1);, you're printing the address ofnum1.
Hello I´m fairly new to C programming and i want to convert a char array looking like ``` char numberlist[]="9,8 2,3 5,4 2,7 1,3"; ``` to a float that would be 9.8 ,i used ``` float a; a=atof(numberlist); printf("%.1f\n",a); ``` but that gave me 9.0 in return because it is 9,8 instead of 9.8 in the char array. How could i easily fix that, without touching the char array? Thanks in advance :)
For example ``` char numberlist[]="9,8 2,3 5,4 2,7 1,3"; float convertFirstNumber(const char *str, char delim) { char z[256]; size_t index = 0; while(*str && *str != delim) { if(*str == ',') z[index++] = '.'; else z[index++] = *str; str++; } z[index] = 0; return atof(z); } int main() { printf("%.1f\n",convertFirstNuber(numberlist, ' ')); } ```
My function looks something like this: ``` void Example(const unsigned char* bytes) { unsigned char buffer[2048] = {0}; strcpy(buffer, bytes); } ``` This does not work. How do I make this work?
you do need to convert anything. if you want to copy from one ``` void Example(const void *bytes, size_t len) { unsigned char buffer[2048]; memcpy(buffer, bytes, len); /* ...*/ } ``` example usage ``` int foo(void) { char str[] = "Hello world"; Example(str, sizeof(str)); } ```
``` char c = 250; c + = 8; ``` In the above operation I am not able to understand how overflow takes place, what will be the value of c after execution?
``` char c = 250; c + = 8; ``` Whencharis 8-bitunsigned,cwill first have the value of 250, then 250 + 8 --> 258. Then 258 is assigned tocand converted to 2 due conversion rules of assigning an out of range value to theunsignedchar. Whencharis 8-bitsigned,cwill first have an implementation defined value due to theconversionof the out-of-rangeintconstant 250 tochar, perhaps-6. Then 2 due to addition of 8. By C def ofoverflow, nooverflowoccurs, just conversions involving a narrowing.
My function looks something like this: ``` void Example(const unsigned char* bytes) { unsigned char buffer[2048] = {0}; strcpy(buffer, bytes); } ``` This does not work. How do I make this work?
you do need to convert anything. if you want to copy from one ``` void Example(const void *bytes, size_t len) { unsigned char buffer[2048]; memcpy(buffer, bytes, len); /* ...*/ } ``` example usage ``` int foo(void) { char str[] = "Hello world"; Example(str, sizeof(str)); } ```
``` char c = 250; c + = 8; ``` In the above operation I am not able to understand how overflow takes place, what will be the value of c after execution?
``` char c = 250; c + = 8; ``` Whencharis 8-bitunsigned,cwill first have the value of 250, then 250 + 8 --> 258. Then 258 is assigned tocand converted to 2 due conversion rules of assigning an out of range value to theunsignedchar. Whencharis 8-bitsigned,cwill first have an implementation defined value due to theconversionof the out-of-rangeintconstant 250 tochar, perhaps-6. Then 2 due to addition of 8. By C def ofoverflow, nooverflowoccurs, just conversions involving a narrowing.
``` char c = 250; c + = 8; ``` In the above operation I am not able to understand how overflow takes place, what will be the value of c after execution?
``` char c = 250; c + = 8; ``` Whencharis 8-bitunsigned,cwill first have the value of 250, then 250 + 8 --> 258. Then 258 is assigned tocand converted to 2 due conversion rules of assigning an out of range value to theunsignedchar. Whencharis 8-bitsigned,cwill first have an implementation defined value due to theconversionof the out-of-rangeintconstant 250 tochar, perhaps-6. Then 2 due to addition of 8. By C def ofoverflow, nooverflowoccurs, just conversions involving a narrowing.
I am working on writing a shell in c. One of my buildin I have to implement is 'echo', I wonder how do I get the value of $? if my command were such as 'ls filename ; echo $?'. In this case, I have to use fork to create a new process and use execv to run binary ls in the system, after execute ls, how do I know the exit status of ls?
After the call tofork, the parent process needs to wait for the child process to complete. It most likely does this usingwaitpid. When it callswaitpid, it can pass a pointer a memory location where it wants to get the "status information" of the child process, including its exit status. Seethewaitpiddocumentationfor details about how to interpret the "status information".
So when I execute the code below in gcc : ``` int main (int n) { if (n==5) return 0; else { printf ("%d ",n); main (n+1); } } ``` it produces the output1 2 3 4instead of (what I unreasonably expected)0 1 2 3 4or something different, becausenis not initialized anywhere. How does the compiler decide whethernis 1 or not?
As the default, the first parameter for the main function is the number of arguments, one of which is always the name of the program. So, when you execute your program, n (which equals to argc) is equal to 1, like this: ``` int main(int argc, char **argv) { /* do something here */ } ```
Calling conventions are complicated, sometimes when I debug a program in GDB I would like to know how the arguments are passed. For example, when I use thecallinstruction like this: ``` call nicefun(7) ``` I would like GDB to write me something like this: ``` I put 7 in rdi. ``` Is there such an option? Of course, checking how 7 is passed is easy, but the matter gets complicated with large structs, va_list's, etc...
Is there such an option? No. I would like to know how the arguments are passed. If you are debugging at assembly level, there isno substitutefor getting familiar with the calling conventions of your platform. If you are generally familiar with them, but forgot some detail and need a quick reminder,x/20i target_functionusually provides sufficient hint.
I can't find any errors in the code below, but every time I run it, the compiler (Xcode) returns hread 1: EXC_BAD_ACCESS (code=2, address=0x10000a025). I'm wondering if any of you have any answers to the problem. ``` int main(){ int *p,b; b=3; (*p)=38; b=(*p)+10; *p=b+1; printf("b,p=%d %d\n",b,*p); } ``` Thank you!
You are trying to dereference an uninitialized variable. Initialize it and it will work. For example: ``` int *p,b,c=38; b=3; p=&c; // now you can dereference it because it is initialized. // now when you do (*p) = 3; // you will be changing c to 3 ``` Or you can do this: ``` int *p; if (!(p=malloc(sizeof(*p))) return 1; // In case of failure of malloc (*p) = 38; // valid // you will also need to free the memory when you are done free(p); ```
In C, a directory is created like this: ``` mkdir("hello"); ``` but what if we don't know the name of this directory (or it's told by user)? How can we define it to a computer? (%s is not working)
I would recommend you to usesnprintfso you can take any type of input. ``` #include <stdio.h> int main() { char name[50]; int i = 5; snprintf(name, 50, "dir.%i", 5); mkdir(name, 0700); } ```
I know thatPythonis platform independent, but I don't understand how that works forCPython. If the interpreter and some of the modules are written inC, aren't those going to be platform dependent?
C is platform independent in the sense that it can be compiled for any machine for which a compiler is made to target that machine. That's why the Python source code is platform independent, even if a Python binary can only work on one platform.
I am using a software that converts a .MOV into a .MP4 video for use in the software.However, I want to be able to do this conversion outside of the software itself. When used, the software outputs a very high-quality .MP4 which allows you to scrub through the software's timeline easily because the video is not aggressively compressed and has high i-frames which are good for random frame seeking and scrubbing. So far any video I've tried to output in FFMPEG is very choppy to scrub through in the software. How can I emulate the .MP4 the software outputs with FFMPEG? (processing length is not an issue) ``` ffmpeg -i InputVideo123.mov -crf 10 -preset veryslow -vcodec h264 -qscale 0 OutputVideo123.mp4 ```
Add-g 1to make all frames keyframes. ``` ffmpeg -i input.mov -c:v libx264 -crf 10 -preset veryslow -g 1 output.mp4 ```
``` printf("%5s\n", "#"); ``` gives: ``` # ``` Is their a way to set field width of this string using an integer format specifier? Something like this, ``` printf("%%ds\n", 5, "#"); ```
From theprintf manual Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int. So in your example it would be: ``` printf("%*s\n", 5, "#"); ```
``` printf("%5s\n", "#"); ``` gives: ``` # ``` Is their a way to set field width of this string using an integer format specifier? Something like this, ``` printf("%%ds\n", 5, "#"); ```
From theprintf manual Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int. So in your example it would be: ``` printf("%*s\n", 5, "#"); ```
I have seenenumdeclarations like this: ``` enum ProgrammingLanguage: unsigned char { C = 0, CPlusPlus, Rust, Java, Javascript, Python }; ``` This only allocates one byte for this type. My question is, is this standard C or a GCC extension? Do I need to worry about portability if I decide to do this?
is this standard C No, this is not a part of C language. a GCC extension? No, this is not a GCC extension in C language. Do I need to worry about portability if I decide to do this? You need to worry about compiling such code at all with any C compiler. This is solely C++ feature. Then it is a macOS feature. Compiling it in Xcode in a C file works It is aclang extension.
this is my rect.h code --> the error code is C2143, syntax error. ``` #pragma once void draw_rect(const RECT*); double calc_area(const RECT*); void move_rect(RECT*, int, int); struct rect { int x, y, w, h; }; typedef struct rect RECT ```
You referenceRECTbefore declaring it. Move thetypedefto the top. ``` typedef struct rect RECT; void draw_rect(const RECT*); double calc_area(const RECT*); void move_rect(RECT*, int, int); struct rect { int x, y, w, h; }; ``` You are now referring a struct type before declaring it, but you're allowed to do that in this fashion. That said, you could avoid that "special" situation by moving thestruct rectdeclaration too. ``` struct rect { int x, y, w, h; }; typedef struct rect RECT; void draw_rect(const RECT*); double calc_area(const RECT*); void move_rect(RECT*, int, int); ```
I wanted to write a simple program to calculate the factorial of a given number using C. Yet my code seems to have some logical error that I can't detect. Would be glad for help. ``` int fact(int n); int main(void) { int num = get_int("Type number: "); printf("%i\n", fact(num)); } //define function int fact(int n) { for (int i = 1; i < n; i++) { n *= i; } return n; } ```
You can't usento calculate. You have to save total with another variable ``` int fact(int n) { int product = 1; for (int i = 1; i <= n; i++) { product = product * i; } return product; } ```
I'm new to C language so please don't be harsh on me. I want to run a program this way :./test -option 3,2 < text.txt I want to execute the program regardless of the file exists or not. So that./test -option 3,4,2 < text.txtis the same as./test -option 3,4,2withoutgetting the message*-bash: hehe: No such file or directory* Thanks
You can use a ternary: ``` [ -f test.txt ] && ./test -option 3,2 < test.txt || echo "" | ./test -option 3,2 ``` In order to avoid repeating the command, you can also use: ``` CMD="./test -option 3,2"; [ -f test.txt ] && $CMD < test.txt || echo "" | $CMD ``` Also, notice thattestis a command, consider using another name for your program.
The definition ofscandir()looks like this: ``` int scandir(const char *dirp, struct dirent ***namelist, int (*filter)(const struct dirent *), int (*compar)(const struct dirent **, const struct dirent **)); ``` What iscompar? What difference does it make what callback I pass there? The man page doesn't seem to say anything. Is it safe to pass NULL there? Can someone explain to me the purpose and usage of the 4th argument? I already did my research, and didn't find any useful information so, well, here I am.
It determines the order in which the items are listed, in a similar manner toqsort. Passing NULL is undefined behavior. Thanks for the comments.
This images below are from a header.hfile. As seen, If I am in the scope of a function, typingRCC->pops up the options, however, if I am not in the scope of any function, then it does not show them. What's the reason for that?
You can only place the code in the function body. You try to do it outside the function. That is the reason. Intellisense knows it and does not suggest it. Same is with macros. Preprocessor does not know anything about the C language. In the macro definition it acts exactly the same way. I personally do not like this kind of macros. Use normal inline functions for that. If you enable optimisations (even -Og) the function will be inlined https://godbolt.org/z/yd75jH
I just restart the C programming study. Now, I'm studying the memory storage capacity and the difference between bit and byte. I came across tothis definition. There is a calculation to a 32 bits system. I'm very confused, because in this calculation 2^32 = 4294967296 bytes and it means about 4 Gigabyte. My question is: Why 2 raised to 32 power results in a number in bytes instead of bits ? Thanks for helping me.
Because the memory is byte-addressable (that is, each byte has its own address).
I wanted to write a simple program to calculate the factorial of a given number using C. Yet my code seems to have some logical error that I can't detect. Would be glad for help. ``` int fact(int n); int main(void) { int num = get_int("Type number: "); printf("%i\n", fact(num)); } //define function int fact(int n) { for (int i = 1; i < n; i++) { n *= i; } return n; } ```
You can't usento calculate. You have to save total with another variable ``` int fact(int n) { int product = 1; for (int i = 1; i <= n; i++) { product = product * i; } return product; } ```
I'm new to C language so please don't be harsh on me. I want to run a program this way :./test -option 3,2 < text.txt I want to execute the program regardless of the file exists or not. So that./test -option 3,4,2 < text.txtis the same as./test -option 3,4,2withoutgetting the message*-bash: hehe: No such file or directory* Thanks
You can use a ternary: ``` [ -f test.txt ] && ./test -option 3,2 < test.txt || echo "" | ./test -option 3,2 ``` In order to avoid repeating the command, you can also use: ``` CMD="./test -option 3,2"; [ -f test.txt ] && $CMD < test.txt || echo "" | $CMD ``` Also, notice thattestis a command, consider using another name for your program.
The definition ofscandir()looks like this: ``` int scandir(const char *dirp, struct dirent ***namelist, int (*filter)(const struct dirent *), int (*compar)(const struct dirent **, const struct dirent **)); ``` What iscompar? What difference does it make what callback I pass there? The man page doesn't seem to say anything. Is it safe to pass NULL there? Can someone explain to me the purpose and usage of the 4th argument? I already did my research, and didn't find any useful information so, well, here I am.
It determines the order in which the items are listed, in a similar manner toqsort. Passing NULL is undefined behavior. Thanks for the comments.