question
stringlengths
25
894
answer
stringlengths
4
863
How to get RI pin status of serial port on a windows platform? I want to read the current state (ON or OFF) , when i get a call on a modem I can set the DTR pin with : EscapeCommFunction(hSerial,SETRTS); But cant find an answer online on how to check the RI pin STATUS
You have to useGetCommModemStatusfunction.
How to get RI pin status of serial port on a windows platform? I want to read the current state (ON or OFF) , when i get a call on a modem I can set the DTR pin with : EscapeCommFunction(hSerial,SETRTS); But cant find an answer online on how to check the RI pin STATUS
You have to useGetCommModemStatusfunction.
I have read that using #pragma omp critical upon one statement like that is inefficient, i do not know why? ``` double area, pi, x; int i, n; ... area = 0.0; #pragma omp parallel for private(x) for (i = 0; i < n; i++) { x = (i+0.5)/n; #pragma omp critical area += 4.0/(1.0 + x*x); } pi = area / n; ```
A naive compiler/runtime would do at each iteration: take a lockcompute `4.0 / (1.0 + x*x)performarea += ...release the lock An alternative would be not to use locks, but performarea += ...with an atomic instruction. In both cases, this is way less efficient that using a reduction clause, in which each thread runs without any synchronization, and the reduction (possibly tree-based) only happens at the end of the OpenMP region.
I saw that linux kernel is usingstruct list_headto save the children of a process. What if the process has no forked children? will it return null or not? how may I check if a process has no children?
The fileinclude/linux/list.hcontains many useful functions for manipulating lists. One of the functions in this file islist_empty(), which returns the result of checking whether the listheadis equal to itself (head -> next), if true, the list is empty. If the child process list isn't empty, you can use thelist_for_each_entry_safemacro/function to iterate through the list safely.
I have this structure, and I would like to pass the data to Example_Data->data. ``` typedef struct { uint8_t *data; /*!< Pointer to allocated data. */ uint32_t size; /*!< Length of data allocated. */ } Example_Data ``` Since this is an array data type, unfortunately I have no idea how I should pass the data to this pointer. I have a question, how to append new data to this pointer?
Allocate memory todata, then copy your data withmemcpy: ``` uint8_t someData[100] = {0}; Example_Data exampleData = {0}; exampleData.data = malloc(sizeof(someData)); if(exampleData.data != NULL){ memcpy(exampleData.data, someData, sizeof(someData); }else{ //malloc failed, handle error } ```
I have a C/C++ winapi program that I'd like to extend a command line functionality to (which I've seen done in C#, but never C++). If the executable is opened with no arguments, it opens the window as normal, but when called from a command line with arguments such as an input or output file, the window does not open and all user interaction is done through the command line. How could I accomplish this? Preferably I'd like to be able to do it in C, as that's where my WinMain() function is. Thanks in advance for any help!
There isLPSTR lpCmdLineparameter inWinMain. You can useCommandLineToArgvWfunction to parselpCmdLine. When necessary parameters exist, you will not create or show program window and do the job.
``` float lgt = light.read(); if(isnan(lgt)){ printf("Failed to read light!"); } else{ printf("%f\n",lgt); } ``` Second printf always print '%f' in the console instead of 'lgt' value. Why could this happen? I'm using Mbed Studio.
Why floating point formats in Mbed Studio don't work? Because you are compiling your program with newlib nano version that does not support floating point format inprintffamily.
When you run a C program, is it possible to get its binary code (which you execute with./foo) from its TEXT segment? If I just copy all the TEXT segment to a file, then can I execute it and run the same program? I am working with Ubuntu.
is it possible to get it binary code If you run your program under the debugger, then you can copy the bytes from anywhere in the process space, being data or code. then i can execute it and run the same program? Simple answer: No! An executable file is a lot more than just a memory dump.
I tried to run this program in Visual stdio and usedWUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUBas input. After running it, it's showingSegmentation fault (core dumped). How to solve this? ``` #include <stdio.h> #include <string.h> int main() { char string[201]; int i, j; scanf("%s",string); for(i=0;i<strlen(string); i++){ if(string[i]=='W' && string[i+1]=='U' && string[i+2]=='B'){ for(int k=i; k<i+3; k++){ string[k]='o'; i=i+2; } } } puts (string); } ``` I want to know whats wrong with my program here
You cannot accessstring[i+2]when I is equal tostrlen(string) - 1. You can access string[i+1] which will be the terminating nul char. Change the upper limit of you for loop.
I have this structure, and I would like to pass the data to Example_Data->data. ``` typedef struct { uint8_t *data; /*!< Pointer to allocated data. */ uint32_t size; /*!< Length of data allocated. */ } Example_Data ``` Since this is an array data type, unfortunately I have no idea how I should pass the data to this pointer. I have a question, how to append new data to this pointer?
Allocate memory todata, then copy your data withmemcpy: ``` uint8_t someData[100] = {0}; Example_Data exampleData = {0}; exampleData.data = malloc(sizeof(someData)); if(exampleData.data != NULL){ memcpy(exampleData.data, someData, sizeof(someData); }else{ //malloc failed, handle error } ```
I have a C/C++ winapi program that I'd like to extend a command line functionality to (which I've seen done in C#, but never C++). If the executable is opened with no arguments, it opens the window as normal, but when called from a command line with arguments such as an input or output file, the window does not open and all user interaction is done through the command line. How could I accomplish this? Preferably I'd like to be able to do it in C, as that's where my WinMain() function is. Thanks in advance for any help!
There isLPSTR lpCmdLineparameter inWinMain. You can useCommandLineToArgvWfunction to parselpCmdLine. When necessary parameters exist, you will not create or show program window and do the job.
``` float lgt = light.read(); if(isnan(lgt)){ printf("Failed to read light!"); } else{ printf("%f\n",lgt); } ``` Second printf always print '%f' in the console instead of 'lgt' value. Why could this happen? I'm using Mbed Studio.
Why floating point formats in Mbed Studio don't work? Because you are compiling your program with newlib nano version that does not support floating point format inprintffamily.
When you run a C program, is it possible to get its binary code (which you execute with./foo) from its TEXT segment? If I just copy all the TEXT segment to a file, then can I execute it and run the same program? I am working with Ubuntu.
is it possible to get it binary code If you run your program under the debugger, then you can copy the bytes from anywhere in the process space, being data or code. then i can execute it and run the same program? Simple answer: No! An executable file is a lot more than just a memory dump.
I tried to run this program in Visual stdio and usedWUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUBas input. After running it, it's showingSegmentation fault (core dumped). How to solve this? ``` #include <stdio.h> #include <string.h> int main() { char string[201]; int i, j; scanf("%s",string); for(i=0;i<strlen(string); i++){ if(string[i]=='W' && string[i+1]=='U' && string[i+2]=='B'){ for(int k=i; k<i+3; k++){ string[k]='o'; i=i+2; } } } puts (string); } ``` I want to know whats wrong with my program here
You cannot accessstring[i+2]when I is equal tostrlen(string) - 1. You can access string[i+1] which will be the terminating nul char. Change the upper limit of you for loop.
I was working on a code using libmosquitto v3.1.x and I couldn't find a method to capture the dup flag of a message. Nb1: From my understanding dup flag indicates that the message was already send but was not acknowledged by recipient. Nb2: I was referringhttps://mosquitto.org/api/files/mosquitto-h.htmlfor libmosquitto API descriptions.
At time of writing of this answer dup flag functionality is not supported by libmosquitto (v1.04.15). Its better to use an advanced library likePahoif you are working ony anything serious.
In aswitch/casestatement, thecasestatements is for checking the condition, so why should it execute the statements which are false? Even if it continues execution of all the cases up to the end of the program ifbreakis not given, won't thecasestatement check the condition. Isn't its internal working same asif/elsestatements? If not, then how does it work internally? Language: C
No, a case label (which isn't a statement) doesn't check any condition. In fact it doesn't do anything at all (notice how you can have multiple cases in a row?) and doesn't produce any code. Upon entering the switch, execution jumps to the matching case. And that's it. Once you're in the block, the labels don't do anything, but abreakwill get you out.
I use C language and I have problem with malloc ``` double** matrix = malloc(matrixSize * sizeof(double*)); for (size_t i = 0; i < matrixSize; i++) { matrix[i] = malloc(matrixSize * sizeof(double)); } return matrix; }` ```
malloc returns a void-pointer void*malloc(size_t size); so you will have to typecast this to double** ``` double** matrix = (double**)malloc(matrixSize * sizeof(double*)); ```
As mentioned by the title, I would like to achieve something like this: ``` void my_exit(int status) { #ifdef _GCOV __gcov_flush(); #endif _exit(status); } ``` But I do not know if there is a_GCOV(or something similar) defined when compiling with--coverage. Any idea will be appreciated!
Doesn't seem to be: ``` $ true | gcc -E - -dM > no-coverage.h $ true | gcc -E - -dM --coverage > coverage.h $ diff no-coverage.h coverage.h ```
This question already has answers here:C puts() without newline(4 answers)Closed2 years ago. I only know and only useprintf(), but I want to try a function that can output something without the use of%parameters. I want to do something like this: ``` printf("Hello, %s.\n", name); ``` But no longer using%for it. Something like: ``` foo("Hello, "); foo(name); foo(".\n"); ``` Is there a function that acts like this?
Usefputs() ``` fputs("Hello, ", stdout); fputs(name, stdout); puts("."); ``` Note that this can only print strings, not other types of data like you can withprintf(). There'sputc()andfputc()for single characters. There's alsoputs()that writes only tostdout, but it also adds a newline at the end, so you can't use it as a replacement for yourprintf(), except for the last part that ends with newline.
I was reading some introductory material on programming in C. The following example was presented: ``` int matrix[][] = {{ 1,2,3}, {5,6,7}}; ``` As gcc (7.5.0 in my case) and clang (6.0.0 in my case) did not compile, I tried several C standards (c89, c90), but none worked. Is there a C standard version in which this is valid?
It is not legal in C. The error message is self-explanatory: declaration of 'matrix' as multidimensional array must have bounds for all dimensions except the first you need to provide all the sizes except the first: ``` int matrix[][3] = {{ 1,2,3}, {5,6,7}}; int matrix[][2][3] = {{{ 1,2,3}, {5,6,7}}, {{ 1,2,3}, {5,6,7}}}; /* etc etc*/ ``` Is there a C standard version in which this is valid? NO
``` #define BUFF_SIZE 96-48 ``` I printedBUFF_SIZEin x64 and it printed 48 but I'm not sure what the meaning of96-48actually is.
Every macro in C and C++ are literal values, put into place by the compiler. So 96-48 means literally 96 minus 48, that is equal to 48. When you have the snippet: ``` 1 #include <stdio.h> 2 3 #define BUFF_SIZE 96-48 4 5 int main(void) { 6 printf("%d\n", BUFF_SIZE); 7 return 0; 8 } ``` The compiler literally putsprintf("%d\n", 96-48);in your code.
I'm actually a beginner in assembly (Nios II) and I know that a functions parameters are stored in the registers (r4 -> r7) But I wonder if f these registers contain the actual value of the parameter or it's adress ? for example the C function : ``` int add (int x, int y) {} ``` Does r4 contain 'x' or '&x' ?
Here's the ABI for Nios II:https://www.intel.com/content/dam/www/programmable/us/en/pdfs/literature/hb/nios2/n2cpu_nii51016.pdfFrom the table, we can tell that arguments are passed indeed in registersr4-r7, and each one of them holds 32 bits. From the same document we learn that int is 4 bytes. That means thatxwill be passed inr4.&xis not passed here, as this is call-by-value. If you want to access the address ofx, good compiler will try first to see if it's ever needed, and only after giving up, will allocate memory on the stack frame.
I'm actually a beginner in assembly (Nios II) and I know that a functions parameters are stored in the registers (r4 -> r7) But I wonder if f these registers contain the actual value of the parameter or it's adress ? for example the C function : ``` int add (int x, int y) {} ``` Does r4 contain 'x' or '&x' ?
Here's the ABI for Nios II:https://www.intel.com/content/dam/www/programmable/us/en/pdfs/literature/hb/nios2/n2cpu_nii51016.pdfFrom the table, we can tell that arguments are passed indeed in registersr4-r7, and each one of them holds 32 bits. From the same document we learn that int is 4 bytes. That means thatxwill be passed inr4.&xis not passed here, as this is call-by-value. If you want to access the address ofx, good compiler will try first to see if it's ever needed, and only after giving up, will allocate memory on the stack frame.
The title says it all. Can function be passed as argument in variadic function and if so, how can I access it? ``` #include <stdio.h> #include <stdarg.h> #include <math.h> void func(double x, int n, ...){ va_list fs; va_start(fs, n); for (int i = 0; i < n; i++) { va_arg(fs, *); //this is where I get confused } } int main(){ double x = 60.0 * M_PI / 180.0; func(x, 3, &cos, &sin, &exp); } ```
The second argument tova_argsis the type to convert to. In this case each function has compatible types, specifically they take a singledoubleas an argument and return adouble. The type of a pointer to such a function isdouble (*)(double), so that it what you would use for the type. ``` double (*f)(double) = va_arg(fs, double (*)(double)); double result = f(x); ``` Also, don't forget to callva_end(fs);after the loop.
The title says it all. Can function be passed as argument in variadic function and if so, how can I access it? ``` #include <stdio.h> #include <stdarg.h> #include <math.h> void func(double x, int n, ...){ va_list fs; va_start(fs, n); for (int i = 0; i < n; i++) { va_arg(fs, *); //this is where I get confused } } int main(){ double x = 60.0 * M_PI / 180.0; func(x, 3, &cos, &sin, &exp); } ```
The second argument tova_argsis the type to convert to. In this case each function has compatible types, specifically they take a singledoubleas an argument and return adouble. The type of a pointer to such a function isdouble (*)(double), so that it what you would use for the type. ``` double (*f)(double) = va_arg(fs, double (*)(double)); double result = f(x); ``` Also, don't forget to callva_end(fs);after the loop.
If I have this ``` int (*p)[2]; ``` and try to do ``` *(*(p))=5; ``` it will throw segFault. it should. But if I have ``` char (*p)[2]; *(*(p))=5; //works *(*(p+1))=7; //works ``` Can some one explain why pointer to2d char arraytreated differently thanpointer to 2 d int arrayin C
Unfortunately,works(apparently) is one of the possible outcomes of an ill-formed program. The pointer has no memory assigned to it,dereferencing itis undefined behavior. It can also make the compiler shoot you down, as discussed inthis Q&A. As for the works part,here you can see it doesn't, (139 return code is a segmentation fault btw).
If I have this ``` int (*p)[2]; ``` and try to do ``` *(*(p))=5; ``` it will throw segFault. it should. But if I have ``` char (*p)[2]; *(*(p))=5; //works *(*(p+1))=7; //works ``` Can some one explain why pointer to2d char arraytreated differently thanpointer to 2 d int arrayin C
Unfortunately,works(apparently) is one of the possible outcomes of an ill-formed program. The pointer has no memory assigned to it,dereferencing itis undefined behavior. It can also make the compiler shoot you down, as discussed inthis Q&A. As for the works part,here you can see it doesn't, (139 return code is a segmentation fault btw).
In cygwin I stumbled on something weird (from my perspective). va_list type is declared in wchar.h. In linux and mingw it is declared elsewhere more explicit (vadefs.h for mingw for example). Can anyone point out why this choice was made ? Thanks
stdarg.h is provided by the compiler: ``` $ cygcheck -l gcc-core | grep stdarg /usr/lib/gcc/x86_64-pc-cygwin/10/include/cross-stdarg.h /usr/lib/gcc/x86_64-pc-cygwin/10/include/stdarg.h ``` there is ``` typedef __gnuc_va_list va_list ```
I'm using SDCC to compile for a STM8 microcontroller. Compiling the following file results in a seemingly unnecessarydivinstruction - which is very slow on the STM8. ``` char a[1]; char b; void foo() __interrupt(1) { char c = a[0]; b = c >> 0; } void main() { } ``` Compiling withsdcc -mstm8 file.cresults in the following assembly: ``` _foo: clr a div x, a ld a, _a+0 ld _b+0, a iret ``` The function seems to work as expected, however I can't see why the first two instructions are required.
Looks like that's a bug somewhere in the compiler because ifb = c >> 0is changed tob = c << 0,b = c + 0,b = a[0]... then no such thing happens. The behavior is observed on both optimized and unoptimized code. But if you optimize for size (--opt-code-size) then only thedivis there, theclrinstruction isn't emitted. You might want toreport that to the developers Demo on Compiler Explorer
Problem Is there a way I can generate linker/compiler flags for function libraries, given one or more source files? Details Software specifications: Operating System:Ubuntu 20.04 LTS x86_64Kernel:5.11.0-27-generic
There's a handy tool you can use to generate compiler/linker flags for your code. It's calledpkg-config, and you can use it like so: ``` gcc file.c $(pkg-config --cflags <library>) $(pkg-config --libs <library>) ``` I'd recommend defining a variable containing all of your dependencies, then using a shell script or other means to generate thepkg-configoutput for that library.
Sample code I've written code somewhat like the following: ``` #include <stdio.h> #include <stdlib.h> struct record { ... }; void record_cleanup(struct record *record) { printf("Deleting record %p\n", record); free(record); } int main(void) { struct record record; ... record_cleanup(&record); ... return EXIT_SUCCESS; } ``` Error However, upon compiling, I received an error: ``` warning: attempt to free a non-heap object ``` What is causing this, and why?
Your problem is coming fromfree(record) Inrecord_cleanup: free(record); Inmain: struct record record; /* stack-allocation; cannot be free()ed */ ... record_cleanup(&record); /* calls free(record), which isn't allowed */
i'm new to C programing and i was testing some code when i compiled it this error came up: ``` fatal error: 'conio.h' file not found #include <conio.h> ``` this was on the top of the code i was testing: ``` #include <stdio.h> #include <conio.h> ... ``` i searched about this error but i only found answers related to windows and ubuntu i'm running mac os
conio.his not a standard library header, and the functions it declares are not standard library functions - it's specific to anancientimplementation that isn't used much anymore. If the code you're trying to build usesconioroutines likegetch(), then it won't build on a Mac.
To begin with, the application I'm working on uses libxml2 to parse XML and to validate this XML against a schema, and I cannot use another XML-parsing library. The schema contains type information for elements in the XML, and I'm trying to get this type information but am not succeeding. Example schema: ``` <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="rootElement" type="xsd:integer"/> </xsd:schema> ``` Example XML ``` <rootElement>13</rootElement> ``` What I want to get from libxml2 is information about the fact that the rootElement can only contain an integer value, as prescribed by thetype="xsd:integer"bit. I'm most interested in the simple types, i.e.xsd:integer,xsd:string,xsd:double,xsd:boolean, etc. If an element is a complex type, the exact type is not important.
The libxml2 API simply doesn't support inspection of schemas, only validation.
I'm not sure if I understand the conditionals using = NULL and != NULL. Is this ``` if (somethin->example == NULL) { do task A return; } else { do task B } ``` the same as this? ``` if (somethin->example != NULL) { do task B } else { do task A return; } ```
Yes, they are equivalent. ==is the inverse of!=. If you both invert the condition and swap theifandelseblocks the two changes cancel out. These are equivalent: ``` if (a) { foo(); } else { bar(); } ``` and ``` if (!a) { bar(); } else { foo(); } ```
``` #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { // write code here printf("%d\n", a); return EXIT_SUCCESS; } static int a = 10; ``` how to reference a static global variableain the comment position? I know that placeabefore main will not cause this problem. I just want to know if there is any related syntax to do this?
You could add atentative definitionforabeforemainlike this: ``` #include <stdio.h> #include <stdlib.h> static int a; // tentative definition int main(int argc, char *argv[]) { // write code here printf("%d\n", a); return EXIT_SUCCESS; } static int a = 10; // "full" definition ``` Although if you do that, you may as well just move the full definition to that point.
I am trying to determine how the complexity of an given algorithm grows with N. ``` 1. float epsilon = 0.001; int a = 0; int b = N - 1; while (b - a > epsilon) { int m = (int)((b + a) / 2); if (arr[m] > 0) b = m; else a = m; } 2. void f(int n) { if (n == 0) printf("Hello\n"); else { f(n - 1); f(n - 1); } } f(N); ``` For the first one, i think it will be o(n) = N , but i am not sure. Could someone explain how to find complexity of first and second algorithm?
First algorithm: As written, it makes little sense thata,bbeints and notfloats, and I'll assume the latter. AlsoNinstead ofN-1. Observe that on every iteration, the distance betweenaandbis halved, as long as it exceedsepsilon. Hence the number of iterations isceiling(lg(N/epsilon)), the time it takes to reduce fromNto less thanepsilon.
How to write a program in c that gets single integer and another integer that is more than 3 digits at least and after that the single integer goes to the left side of the three digits number and the right side as well. Note: I need help for the left side right side number For example: I mean if I got 5 and 100 it should be 51005
something like this: ``` int a = 5, b = 100; int length = 1; int tmp = b; while (tmp /= 10) length++; int left = 10; for (int i = 0; i < length; i++) left *= 10; int result = (left * a) + (10 * b) + a; std::cout << result; ``` Also, you can playhere.
I am writing some C code and have been formatting strings like this ``` int buffer[8]; snprintf(buff, 8, "%3d", someNumberVariable); my_lcd_stringout(buffer); ``` This formats any texts that grows in size to be pushed to the left. For example, imagine the _ character is a space: ``` "__7__" "_74__" "748__" ``` Does anybody know how I can reverse this pushback? so that my increasing numbers are formatted this way as they grow (without leaving the characters there when they shrink of course): ``` "__7__" "__74_" "__748" ```
" %-3d" The minus makes it left-aligned.
Here is the sample program. ``` #include<glib.h> void call_me(gpointer data, gpointer user_data) { g_usleep(1); g_print("I am called!\n"); } int main(int argc, char *argv[]) { GThreadPool* th_pool = g_thread_pool_new((GFunc)call_me, NULL, 200, TRUE, NULL); for(int i = 0; i < 10; ++i){ g_thread_pool_push(th_pool, (void*)10, NULL); } return 0; } ``` I think the solution is to join the threads in the thread pool because the problem is main thread returns before all the threads get their time. But, I could not find a function in Glib. If there is other way to solve the problem, could you please highlight them?
Callg_thread_pool_free (th_pool, TRUE, TRUE). It will wait for all pending tasks to finish running, and then free the memory used by theGThreadPool.
How to write a program in c that gets single integer and another integer that is more than 3 digits at least and after that the single integer goes to the left side of the three digits number and the right side as well. Note: I need help for the left side right side number For example: I mean if I got 5 and 100 it should be 51005
something like this: ``` int a = 5, b = 100; int length = 1; int tmp = b; while (tmp /= 10) length++; int left = 10; for (int i = 0; i < length; i++) left *= 10; int result = (left * a) + (10 * b) + a; std::cout << result; ``` Also, you can playhere.
I am writing some C code and have been formatting strings like this ``` int buffer[8]; snprintf(buff, 8, "%3d", someNumberVariable); my_lcd_stringout(buffer); ``` This formats any texts that grows in size to be pushed to the left. For example, imagine the _ character is a space: ``` "__7__" "_74__" "748__" ``` Does anybody know how I can reverse this pushback? so that my increasing numbers are formatted this way as they grow (without leaving the characters there when they shrink of course): ``` "__7__" "__74_" "__748" ```
" %-3d" The minus makes it left-aligned.
Here is the sample program. ``` #include<glib.h> void call_me(gpointer data, gpointer user_data) { g_usleep(1); g_print("I am called!\n"); } int main(int argc, char *argv[]) { GThreadPool* th_pool = g_thread_pool_new((GFunc)call_me, NULL, 200, TRUE, NULL); for(int i = 0; i < 10; ++i){ g_thread_pool_push(th_pool, (void*)10, NULL); } return 0; } ``` I think the solution is to join the threads in the thread pool because the problem is main thread returns before all the threads get their time. But, I could not find a function in Glib. If there is other way to solve the problem, could you please highlight them?
Callg_thread_pool_free (th_pool, TRUE, TRUE). It will wait for all pending tasks to finish running, and then free the memory used by theGThreadPool.
I'm currently following a tutorial to program raycasting, the tutorial is in C and I'm rewriting it in Python, but I can't understand the following line and so can't translate it in python : ``` float aTan = -1/tan(ra); ry = (((int)py>>6)<<6-0.0001; rx = (py-ry)*aTan+px; ``` Where ry and rx are the y and x coordinates of the intersection between, I think, the first horizontal line and the ray. Moreover, ra is the angle of the ray. The lines with aTan and rx are just maths so I understand them but the writing of ry is not familiar for a python student like me, could you enlighten me ?
The ">>" operator is the right shift, so integer division by power of two. Numerically ``` ry = (((int)py>>6)<<6-0.0001; ``` is equivalent to ``` ry = (py // 64) * 64 - 0.0001 ``` (since2^6 == 64)
I have not seen any thread talk about this specific error so here is the problem: I have set up a C project in Clion and I configured inSetting -> Build,Execution,Deployment -> Toolchainsa file usr/bin/make as theMake. I could run my code yesterday but today, i get the warning in a red window popping-up:Error running 'makefile': Cannot build 'makefile'when I try to run my code. What could possibly cause this?
It seems like you’re trying to run the makefile instead of the program that is built by it. Have you tried doing a build first? Or maybe you should try to clean the project too. Have a look a the blog post of JetBrainshttps://blog.jetbrains.com/clion/2020/06/makefile-projects-in-clion/. There’s a gif that shows how to clean the project. Hope this helps, if not maybe post your makefile so we can check if it has any errors.
I was trying to initialise a array made by pointer: the code I used was: ``` int c = 15; Struct *Pointer[c] = {NULL}; ``` but C give me a error message which says: ``` "message": "variable-sized object may not be initialized", ``` but when I change my code to: ``` Struct *Pointer[15] = {NULL}; ``` it worked! Is there any way to fix it? I can't use 15 instead of variable "c" Cheers!
You need to make a loop to initialize the array: ``` for (int i = 0; i < c; i++) Pointer[i] = NULL; // set all of these values to NULL ``` Now,Pointerwill be of sizec. Also, this link may help, too:Array[n] vs Array[10] - Initializing array with variable vs real number
I ran across this program while writing a graphical frontend to the GNU Coreutilsshredprogram. When a user drags in a file that has spaces in it, such asmy private data.docxthe GTK+ DND service represents those spaces as%20. Using that example i would get (for the filename)my%20private&20data.docx. I need to convert those to space characters because I use thefopenfunction fromstdio.h.fopenrefuses to open filenames like that because it does not recognize%20as a representation for a space.
No, you do not replace%20with spaces. You decode the URL into a filename, withg_filename_from_uri: ``` gchar * g_filename_from_uri (const gchar *uri, gchar **hostname, GError **error); ``` and usage therefore ``` gchar *filename = g_filename_from_uri(uri, NULL, NULL); ``` at its simplest.
I was trying to initialise a array made by pointer: the code I used was: ``` int c = 15; Struct *Pointer[c] = {NULL}; ``` but C give me a error message which says: ``` "message": "variable-sized object may not be initialized", ``` but when I change my code to: ``` Struct *Pointer[15] = {NULL}; ``` it worked! Is there any way to fix it? I can't use 15 instead of variable "c" Cheers!
You need to make a loop to initialize the array: ``` for (int i = 0; i < c; i++) Pointer[i] = NULL; // set all of these values to NULL ``` Now,Pointerwill be of sizec. Also, this link may help, too:Array[n] vs Array[10] - Initializing array with variable vs real number
I ran across this program while writing a graphical frontend to the GNU Coreutilsshredprogram. When a user drags in a file that has spaces in it, such asmy private data.docxthe GTK+ DND service represents those spaces as%20. Using that example i would get (for the filename)my%20private&20data.docx. I need to convert those to space characters because I use thefopenfunction fromstdio.h.fopenrefuses to open filenames like that because it does not recognize%20as a representation for a space.
No, you do not replace%20with spaces. You decode the URL into a filename, withg_filename_from_uri: ``` gchar * g_filename_from_uri (const gchar *uri, gchar **hostname, GError **error); ``` and usage therefore ``` gchar *filename = g_filename_from_uri(uri, NULL, NULL); ``` at its simplest.
Ok so I have the following typedef declaration: ``` typedef void (__fastcall* INFINITYHOOKCALLBACK)(_In_ unsigned int SystemCallIndex, _Inout_ void** SystemCallFunction); ``` and I have the following function declaration: ``` NTSTATUS IfhInitialize( _In_ INFINITYHOOKCALLBACK InfinityHookCallback); ``` So my question is how would I declare and define a CallBack function that can be passed to the above function ?
Just define it following the typedef: ``` void __fastcall MyCallback(unsigned int SystemCallIndex, void** SystemCallFunction) { // ... } ``` And pass it with its name: ``` IfhInitialize(MyCallback); ```
How can I use acontinuestatement in a ternary operator? ``` for (i = 0; i < arr_size - 1; i++) { ar[i] == 1 || ar[i] == 2 || ar[i] == 3 ? count++ : continue; } ``` I can replace it like this. ``` for (i = 0; i < arr_size - 1; i++) { ar[i] == 1 || ar[i] == 2 || ar[i] == 3 ? count++ : count; } ```
You can't usecontinuein this way as it is astatement, and the operands of the ternary operator must be aexpression. Like any operator, its result has a value which can be used in other expressions. If it were allowed to usecontinuein the way you want, what would the value of the expression be? It doesn't make sense to use in that way. The ternary operator isn't appropriate for what you want. It should be rewritten as anifstatement: ``` if (ar[i] == 1 || ar[i] == 2 || ar[i] == 3) { count++; } ```
I have a massive C++ code to probe into from github and it would be helpful if I can generate a dependency diagram for the code base. Ideally I would like to know what function triggers other ones in the code and where are they located. Is there any program/software that does this? Thanks
This is called acall graph. One option iscflowtogether withpycflow2dotanddot. More options can be found at:https://stackoverflow.com/a/17844310/1959808 Example C file: ``` /* * simple demo for pycflow2dot, use with: * cflow2dot -i example.c -f png * for help: * cflow2dot -h */ #include <stdio.h> void say_hello(char *s) { printf(s); } void hello_1() { say_hello("Hello 1 !\n"); } void hello_2() { say_hello("Hello 2 !\n"); } int main(void) { hello_1(); hello_2(); } ``` From this file, with the command: ``` cflow2dot -i example.c -f png ``` the following image is produced:
Whenever I want to include a header in my source code, the IDE doesn't allow me to type the.hextension. If I type<stdio.h>it accepts only<stdio>, and I'm unable to type any further. I made no changes to the default settings built-in to the IDE. I am using the latest version1.37.1. I have to manually #include header files fromEdit > Insert "include<..>". Any suggestions on how I can disable this behaviour of the IDE?
I consider this to be just on the right side of the on/offtopic definition, using the exception for "tools regularily used by programmers".So I recommend to find out your configuration for "drop rest of word for auto completion" (within editor completion preferences). It could be active and I suspect you do not want it active. If this does not help, but seems kind of interesting, read for inspirationhttps://www.geany.org/manual/1.23.1/index.html#editor-completions-preferencesand bearby sibling pages.
why I can not assign it like this: ``` char c1 []="Odin"; c1=c1+1; ``` Note that I include #include<string.h>
Quoting thereferencefor your problem: Assignment Objects of array type cannot be modified as a whole: even though they are lvalues (e.g. an address of array can be taken), they cannot appear on the left hand side of an assignment operator: So, sincecin your code is an array object i.e. a type of an array, it cannot appear on the left-hand side of an assignment operator.
I have a massive C++ code to probe into from github and it would be helpful if I can generate a dependency diagram for the code base. Ideally I would like to know what function triggers other ones in the code and where are they located. Is there any program/software that does this? Thanks
This is called acall graph. One option iscflowtogether withpycflow2dotanddot. More options can be found at:https://stackoverflow.com/a/17844310/1959808 Example C file: ``` /* * simple demo for pycflow2dot, use with: * cflow2dot -i example.c -f png * for help: * cflow2dot -h */ #include <stdio.h> void say_hello(char *s) { printf(s); } void hello_1() { say_hello("Hello 1 !\n"); } void hello_2() { say_hello("Hello 2 !\n"); } int main(void) { hello_1(); hello_2(); } ``` From this file, with the command: ``` cflow2dot -i example.c -f png ``` the following image is produced:
Whenever I want to include a header in my source code, the IDE doesn't allow me to type the.hextension. If I type<stdio.h>it accepts only<stdio>, and I'm unable to type any further. I made no changes to the default settings built-in to the IDE. I am using the latest version1.37.1. I have to manually #include header files fromEdit > Insert "include<..>". Any suggestions on how I can disable this behaviour of the IDE?
I consider this to be just on the right side of the on/offtopic definition, using the exception for "tools regularily used by programmers".So I recommend to find out your configuration for "drop rest of word for auto completion" (within editor completion preferences). It could be active and I suspect you do not want it active. If this does not help, but seems kind of interesting, read for inspirationhttps://www.geany.org/manual/1.23.1/index.html#editor-completions-preferencesand bearby sibling pages.
why I can not assign it like this: ``` char c1 []="Odin"; c1=c1+1; ``` Note that I include #include<string.h>
Quoting thereferencefor your problem: Assignment Objects of array type cannot be modified as a whole: even though they are lvalues (e.g. an address of array can be taken), they cannot appear on the left hand side of an assignment operator: So, sincecin your code is an array object i.e. a type of an array, it cannot appear on the left-hand side of an assignment operator.
Givenchar *line = {'a','\0','b','\0', 'c', '\0'} how would you make it so thatchar **str_arrwould point/be assigned to all the substrings withinline? str_arr[str_arr_index] = lineworks only for the first substring, but anything after it is just NULL
``` str_arr = malloc(3 * sizeof (char *)); str_arr[0] = &line[0]; str_arr[1] = &line[2]; str_arr[2] = &line[4]; ``` There is no way to do it programmatically because there is no way to know how many substringslinecontains. (Just as there is no way from the output of the code above to know thatstr_arrnow has three pointers to three substrings.)
Hi so i'm new at coding in C and i'd like to know how to compare several variables. Cause my if statement is only working for the first variable and ignore the ||. ``` scanf("%d %c %d", &nbsaisi, &op, &nbsaisi2); if((op != multi) || (op != plus) || (op != moins) || (op!= divi)) { printf("You haven't entered a valid operator.\n"); exit(1); } ```
You should enter inside the if block only if all the conditions are met, so in your case your conditions should be in&&and not in|| ``` if((op != multi) && (op != plus) && (op != moins) && (op!= divi)) { printf("You haven't entered a valid operator.\n"); exit(1); } ```
I want to check if the string has only capital letters, but I would like to know if it is possible to check if a letter in the string is equal to a range of numbers in the ASCII table. this is what I wrote until now: ``` #include <stdio.h> #include <string.h> void main() { int length, x = 0, counter = 0; printf("Enter your password length: "); scanf("%d", &length); char password[length]; printf("Enter your password: "); scanf("%s", &password); } ``` I don't know how to continue from there. Thanks in advance for helping!
After taking the string from the user, all you need to do is iterating the string you created and checking if the char at that index is between 65 and 90. ascii table
I dont want use "if", i want change it to something short, how i can make it without "if" ? ``` int a,b,c; scanf ("%d %d %d",&a,&b,&c); if (a%2!=0) printf("%d ",a); if (b%2!=0) printf("%d ",b); if (c%2!=0) printf("%d ",c); ```
Even if I can't see a reason for it, if you really want, you can do it without any if or conditional operator like this: ``` char *f[] = { "", "%d " }; printf(f[a & 1], a); printf(f[b & 1], b); printf(f[c & 1], c); ``` More important, check the return value ofscanf(), and provide aMCVEin your questions: ``` #include <stdio.h> int main(void) { int a,b,c; if (scanf("%d%d%d", &a, &b, &c) == 3) { char *f[] = { "", "%d " }; printf(f[a & 1], a); printf(f[b & 1], b); printf(f[c & 1], c); } return 0; } ``` Test ithere.
I have two (very long) c code files,foo1.candfoo2.c, and a library which I don't have access to its source codelibfoo.a. In all three files, they use a function calledMyFooFunc. Now I just want to interceptMyFooFunccalls fromfoo1.c, have my own implementation, but do not intercept the function calls in the other two files. Is there any way I can do that, without rename theMyFooFuncfunction name? Thanks for any suggestions.
If you don't want to change "foo1.c", the most simple way is to compile it wrapped in another source file. Don't compile it on its own then. This wrapper changes the name of the function with a preprocessor macro, as Eric suggested. ``` // foo1altered.c #define MyFooFunc MyAlternateFooFunc #include "foo1.c" ```
Hello I want to define some custom statements. For example in Polish language we have letters 'a' than 'ą' and than 'b' and I want to do something like this ``` #define a > b && ą > b ``` I need this to comprasion in if statement to sort words so this should work like ``` if(ą > a) //false from define ```
No, you can't do that. You would have to do that with either a (inline) function, or a function like macro. And if it is for sorting, you should keep in mind that that would sort based on integral representation of the character, which is not necessarily alphabetical.
// This is the code its part of my college assignment ``` #include <stdio.h> #include <stdlib.h>// header file for rand and srand function #include <time.h> int main() { srand(time(0)); // time is used for different values int result = rand() % 1112 + 1000; // 1112 is max value & 1000 is min value. Also This formula worked in range between (-999 to 999) printf("%d", result); return 0; } Output: 1702 1810 and so on... ``` I noticed this during my college assignment...
rand() % 1112may become values in the range 0 to 1111. You should dorand() % (1112 - 1000 + 1) + 1000because the offset from 1000 should be in the range 0 to1112 - 1000.
Hello I want to define some custom statements. For example in Polish language we have letters 'a' than 'ą' and than 'b' and I want to do something like this ``` #define a > b && ą > b ``` I need this to comprasion in if statement to sort words so this should work like ``` if(ą > a) //false from define ```
No, you can't do that. You would have to do that with either a (inline) function, or a function like macro. And if it is for sorting, you should keep in mind that that would sort based on integral representation of the character, which is not necessarily alphabetical.
// This is the code its part of my college assignment ``` #include <stdio.h> #include <stdlib.h>// header file for rand and srand function #include <time.h> int main() { srand(time(0)); // time is used for different values int result = rand() % 1112 + 1000; // 1112 is max value & 1000 is min value. Also This formula worked in range between (-999 to 999) printf("%d", result); return 0; } Output: 1702 1810 and so on... ``` I noticed this during my college assignment...
rand() % 1112may become values in the range 0 to 1111. You should dorand() % (1112 - 1000 + 1) + 1000because the offset from 1000 should be in the range 0 to1112 - 1000.
I am unable to understand why this code is displaying 20 30 40 as output. Can anyone explain how the relational expression written in if statement is understood by the C Compiler ? This is the image of code of the C Program ``` #include <stdio.h> int main() { int i = 20, j = 30, k = 40; if (i > j == k) { printf("%d %d %d ",--i,j++,++k); } else { printf("%d %d %d ",i,j,k ); } return 0; } ``` Output: 20 30 40
first thing to consider is operator precedence. the operator > is evaluated before the operator == and it returns a value. in this case, i > j is wrong so it returns zero. then it checks if zero equals to k which is 40 and it isn't. so it goes to else branch.
When I execute the next code it runs fine ``` // Example program #include <string.h> #include <stdio.h> int main() { char *dbString = strdup("172.0.0.1:5000"); char *port = strchr(dbString, ':'); printf("port = %s\n", port); if (port) *port++ = '\0'; printf("port = %s\n", port); return 0; } ``` But if I execute the next code I got an error. ``` // Example program #include <string.h> #include <stdio.h> int main() { char *port = (char*) ":5000"; printf("port = %s\n", port); if (port) *port++ = '\0'; printf("port = %s\n", port); return 0; } ``` Could you explain to me the reason for the error?
In your second example,":5000"is a string literal. The compiler places the string literal in a readonly memory section. You are trying to change that string which is ilegal.
How can I exclude the "10" from the output? Code: ``` #include <stdio.h> int main() { int num[2] ,*j, *k; printf ("Enter the Minimum value: "); scanf ("%d" , &num[0]); printf ("Enter the Maximum Value: "); scanf ("%d" , &num[1]); j = &num[0], k = &num[1]; printf("The maximum Numbers are: "); while ((*j < *k) && (*j != *k)) { ++(*j); printf(" %d" , *j); } printf ("\n"); return 0; } ``` Output: Enter the Minimum value: 1 Enter the Maximum Value: 10 The maximum Numbers are: 2 3 4 5 6 7 8 910
You can pre-increment the*jvalue in the actual test condition of thewhileloop; also, you don't need the!=test, as that will already be included in the<comparison: ``` while (++(*j) < *k) { printf(" %d", *j); } ```
What does this mean: ``` *variablename++ = ','; ``` I have seen stuff likei++which does:i = i + 1this I guess. But what does it mean if you assign a thing to it like the above (first one)?
This is a common way to assign elements of an array (by using a pointer) inside a loop. Without knowing the exact type, it's equivalent to something like: ``` { type *old_pointer = variablename; // Substitute type for the actual type variablename = variablename + 1; *old_pointer = ','; } ``` The important part here is that the variable must be a pointer. You can't do it using non-pointer types likeint. That's because the suffix increment operator returns anrvalue(see e.g.this value category referencefor details), and rvalues can't be assigned to. But if the rvalue is a pointer, then it can be dereferenced to become an lvalue, which can then be assigned to.
How can I exclude the "10" from the output? Code: ``` #include <stdio.h> int main() { int num[2] ,*j, *k; printf ("Enter the Minimum value: "); scanf ("%d" , &num[0]); printf ("Enter the Maximum Value: "); scanf ("%d" , &num[1]); j = &num[0], k = &num[1]; printf("The maximum Numbers are: "); while ((*j < *k) && (*j != *k)) { ++(*j); printf(" %d" , *j); } printf ("\n"); return 0; } ``` Output: Enter the Minimum value: 1 Enter the Maximum Value: 10 The maximum Numbers are: 2 3 4 5 6 7 8 910
You can pre-increment the*jvalue in the actual test condition of thewhileloop; also, you don't need the!=test, as that will already be included in the<comparison: ``` while (++(*j) < *k) { printf(" %d", *j); } ```
What does this mean: ``` *variablename++ = ','; ``` I have seen stuff likei++which does:i = i + 1this I guess. But what does it mean if you assign a thing to it like the above (first one)?
This is a common way to assign elements of an array (by using a pointer) inside a loop. Without knowing the exact type, it's equivalent to something like: ``` { type *old_pointer = variablename; // Substitute type for the actual type variablename = variablename + 1; *old_pointer = ','; } ``` The important part here is that the variable must be a pointer. You can't do it using non-pointer types likeint. That's because the suffix increment operator returns anrvalue(see e.g.this value category referencefor details), and rvalues can't be assigned to. But if the rvalue is a pointer, then it can be dereferenced to become an lvalue, which can then be assigned to.
So I am implementing a filesystem FUSE. I would like to know in which directory I am located when calling a function (specifically "mkdir"). Is there a way to know that? Or a way to keep track of directories when the user uses the "cd" command? The "getcwd" function always returns the root directory.
The libfuse deamon is operating as root, and not in the context of the user operating on the mounted filesystem. This is whygetcwdin your fuse code always returns the root directory. However, you do have access to some of the calling user's attributes, in particular their PID number, withfuse_get_context()->pid(seelinux how to intercept unauthorized process access to the file,base with FUSE( cryfs or gocryptfs )) Using the PID you can fetch the user's current directory by callingreadlink()on/proc/$pid/cwd(seehttps://unix.stackexchange.com/questions/509420/get-working-directory-of-logged-in-users)
Right now I have this code, ``` #include <stdio.h> void fib(){ double pi = 0; double n = 4; double d = 1; double a; clock_t begin = clock(); for (int i = 1; i < 100000000; i++){ a=2*(i%2)-1; pi+=a*n/d; d+=2; } clock_t end = clock(); double time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf(pi); printf(time_spent); }; int main() { fib(); return 0; } ``` and I get cannot convert 'double' to 'const char*'` on printf(pi); and printf(time_spent); How can I get pi and time_spent to print correctly?
Edit those lines: printf("%lf",pi)printf("%lf",time_spent) printf()is for formatted output that takes aconst char *as an argument.There are many format specifiers defined in C. Take a look at the following list: %ior%dforint%cforchar%fforfloat%sforstring%lfforlong float (double)
Is it possible to declare a variable when initializing an array? For example: ``` #include <stdio.h> main() { int x; int arr[x]; scanf("%i", &x); } ``` Or perhaps something similar? Any help would be appreciated.
In general you may write ``` int x; scanf("%i", &x); int arr[x]; ``` In this case the arrayarrwill be a variable size array. The value ofxshall be greater than 0. Otherwise in this case ``` int x; int arr[x]; ``` the variablexis uninitialized (because it is a variable with automatic storage duration) and as a result the array declaration invokes undefined behavior.
``` #include<stdio.h> int main(){ int y=15; if(y++>19 && y++!=21 && y++>21) printf("%d",y); else printf("%d",y); return 0; } ``` I expected output to be 15 or even 18 but it gives out 16 and I don't know why.
Here y++>19 ==> y is compared against 19 and then incremented due to postfix ++. So, y++>19 is actually evaluated as 15>19 and then y gets incremented and becomes 16. Since 15>19 is false, the rest of the condition y++!=21 && y++>21 is not evaluated and control goes to else condition and prints y. Since y already became 16 above, it prints 16. Note that in short-circuit evaluation, A && B && C, if A gets evaluated to true then only B gets evaluated. If both A and B gets evaluated to true then only C gets evaluated. Thus, in your case, since A is false, there was no further evaluation of B and C and the control just enters else part of it and prints y.
I have aC++UWP app that calls aCfunction which writes to a file .e.g. ``` FILE * fp = fopen ("file.txt", "w+"); fprintf(fp, "Hello"); fclose(fp); ``` fopen()failes with error13which means that there are insufficient permission on the directory. How can I ensure that theCfunction can write to a file?
SinceUWPruns in a sandbox, I solved it by getting a writable file path inC++: ``` StorageFolder^ localFolder = ApplicationData::Current->LocalFolder; String^ path = localFolder->Path; ``` Then I passed the path to theCprogram.
This question already has answers here:How can I call a function using a function pointer?(17 answers)Closed2 years ago. I have a struct with a function pointer, that is intended for pointing to the bar() function, but i have no clue how to call the function that's being pointed on: ``` #include <stdlib.h> typedef struct Foo { int (*func_ptr)(const char *, const char *); } Foo; int bar(const char *a, const char *b) { return 3; } int main(void) { Foo *foo = (Foo *)malloc(sizeof(Foo)); foo->func_ptr = &bar; //how do i call the function? return 0; } ```
Imagine yourconst char *ais "hello" andconst char *bis "there", then you can use any of the following forms to call the function by its pointer: ``` (foo->func_ptr)("hello", "there"); (*foo->func_ptr)("hello", "there"); foo->func_ptr("hello", "there"); ```
Just for personal study and better understanding of C code preprocessor 😳: I am wondering if it is possible to implementFibonaccifunction bypreprocessor directivesin C language. Normal definition of Fibonacci function could be: ``` int f(int i) { // i should be non-negative integer if (i <= 1) { return 1; } return f(i - 1) + f(i - 2); } ``` The approach of using the template metaprogramming technique in C++ is not what I need. It seems that it is not possible to perform recursive calculations by using the code preprocessor?
I do not think macro in C can support recursive macro. But Fibonacci is possible macro. By using the fomular of nth number #define Fibonacci(n) (POW(1+POW(5,1/2),n) - POW(1-POW(5,1/2),n))/POW(5,1/2)
How can I find the element closest to average in c array. This passes most tests however when I type in the sequence 4-1-5-7-2 it prints out 2, instead of 5. ``` #include <stdio.h> #include <math.h> int main() { int A[50], n, k = 0, i = 0; double avg = 0; scanf_s("%d", &n); do { scanf_s("%d", &A[i]); avg += (double)A[i] / n; } while (++i < n); printf("\n%f\n", avg); for (i = 1; i < n; i++) { if (fabs(A[k] - avg) > fabs(A[i]) - avg) { k = i; } } printf("%d", A[k]); return 0; } ```
In your if statement, replacefabs(A[i]) - avgwithfabs(A[i] - avg)to get the absolute difference.
This question already has answers here:Why does C++ require a cast for malloc() but C doesn't?(4 answers)Closed2 years ago. ``` int *pi = malloc(sizeof(int)); ``` It can do in C language but in C++ language, it has compile error. In C++ language, it should use this way. ``` int *pi = (int*) malloc(sizeof(int)); ``` what difference is malloc function in C and C++ language?
C and C++ are two different languages each with their own set of rules. In both C and C++mallocreturns avoid*. In C avoid*is compatible with any pointer so it can (and should) be assigned directly. In C++ it is not compatible with anything else so it cannot be assigned directly to a nonvoid*. So if you want to usemallocin C++ (you should not) you have to cast thevoid*return value to the appropriate pointer type,int*in your example.
From the mysql terminal: ``` SELECT 1, (SELECT user_id FROM users); ``` ERROR 1242 (21000): Subquery returns more than 1 row In C code: ``` ret = mysql_query("SELECT 1, (SELECT user_id FROM users)"); printf("Ret is %d\n", ret); // --> "Ret is 0" ``` Is this a bug in the mysql C api? I cannot get any error information from this query. Bothmysql_errno()andmysql_error()return nothing. As far as the API is concerned the query ran successfully.
This error isn't reported until you callmysql_store_result. ``` ret = mysql_query(con, "SELECT 1, (SELECT user_id FROM users)"); printf("Ret is %d\n", ret); // --> "Ret is 0" MYSQL_RES *result = mysql_store_result(con); if (result == NULL) { printf("Error is %s", mysql_error(con); // prints "Subquery returns more than 1 row" } ```
I am wondering is it possible to write in a string some content and put another string in there at the same time ``` char str[50], *test; scanf("%s", str); test = "123 %s 123", str; printf("%s\n", test); ``` consider i write in the scanf "abc" Is the a way for it to output: 123 abc 123
You can usesnprintf()to doprintf-like formatting and put the result into character array. ``` char str[50], test[128]; scanf("%s", str); snprintf(test, sizeof(test), "123 %s 123", str); printf("%s\n", test); ```
I"m trying to fix my function so that if the input is NULL, I can re ask for file input as opposed to exiting the program. Here is what I have so far: ``` void inputGrades(float *arr[MAX_ROWS]) { char fileName[20]; printf("Please enter file name: "); scanf("%s", fileName);//Input file name FILE *f = fopen(fileName, "r");//Open file if(f == NULL) { printf("File not found"); printf("Please enter file name: "); exit(0); ``` I'm trying to not have to use an exit statement.
I assume you want something like this? ``` FILE *f = NULL; while (NULL == f) { printf("Please enter file name: "); scanf("%s", fileName); //Input file name f = fopen(fileName, "r");//Open file } ```
I copied this code from geeks for geeks. ``` #include<stdio.h> int main() { int c; printf("geeks for %ngeeks ", &c); printf("%d", c); getchar(); return 0; } ``` It should print the characters from start to%nfollowed by the number of printed characters: But when I execute it, it's printing this:
It seems that the problem lies in the fact that older versions of MingW do not set__USE_MINGW_ANSI_STDIOby default, which is not the case for newer versions, what you can do is to manually define it in your program: ``` # define __USE_MINGW_ANSI_STDIO #include <stdio.h> int main() { //... } ``` Or use it directly on the compilation command: ``` gcc main.c -o main.exe -D __USE_MINGW_ANSI_STDIO ```
Here's the code: ``` typedef char FlagType; int main() { } int myproc( int ) { int FlagType; } ``` copied fromhttps://learn.microsoft.com/en-us/cpp/c-language/typedef-declarations?view=msvc-160 In my understanding, 'typedef char FlagType' makes 'char a' and 'FlagType a' no difference. But I can't understand the 'int FlagType'.
The code demonstrates a pathological example. Not a standard or recommended use case. It is shown to explain what happens when a local variable has the same name as a typedef name. Typedef names share the name space with ordinary identifiers (see Name Spaces for more information). Therefore, a program can have a typedef name and a local-scope identifier by the same name.
Let's take the following example: ``` // hash.h #ifndef _HASH_H_ #define _HASH_H_ /* A few prime number helpers */ bool is_prime(int x); #endif ``` Because this header file uses theboolobject, do I need to add#include <stdbool.h>, or is it enough for thehash.cfile to import it. Why or why not?
Your header file shouldincludeit if it needs it. Otherwise you'd be relying on theincludeorder of the fileincludeing your header: ``` // works #include <stdbool.h> #include "hash.h" ``` ``` // doesn't work -- bool not defined yet when hash.h is processed #include "hash.h" #include <stdbool.h> ```
javascript regex: ``` reg = /\/\*[\s\S]*?\*\// ``` I use it to remove code comments like "/* xxxx */", which work fine. Now I want to convert to posix extended regex use c language, ``` // use regex.h // regcomp const char *patten = "TODO"; // need convert from javascript regex regcomp(&re, patten,REG_EXTENDED); ``` I try as follow: ``` const char *patten = "\\/\\*[[:space:]^[:space:]]*?\\*\\/"; /* * javascript regex white space \s convert to posix [:space:] */ ``` but it not work. where is wrong?
You can write it as ``` const char *patten = "/\\*[^*]*\\*+([^/*][^*]*\\*+)*/"; ``` Details: /\*- starting/*char sequence[^*]*- zero or more characters other than*\*+- one or more literal*([^/*][^*]*\*+)*- zero or more sequences of:[^/*]- a char other than a/and*[^*]*- zero or more chars other than asterisk\*+- one or more asterisks/- a closing/char. See theregex demo.
I need to modify some element of two-dimensional char array using pointer. I have tried this: ``` char arr[5][5]; char** ptr = arr; ptr[2][3] = 'a'; ``` This is not the correct way to do so. It gives me access violation. What should I do?
It will depend on what you actually want to do. Here are some candidates of ways: Way 1: allocate an array with pointers to each row and use that. ``` char arr[5][5]; char* arr_rows[5]; char** ptr; for (int i = 0; i < 5; i++) arr_rows[i] = arr[i]; ptr = arr_rows; ptr[2][3] = 'a'; ``` Way 2: use a pointer to an array ``` char arr[5][5]; char (*ptr)[5] = arr; ptr[2][3] = 'a'; ```
I have been given a task to simulate heap space and implementmalloc,freeandreallocon this piece of memory. The size of this piece of memory is not fixed, but I am not allowed to use any standard library allocator,brk,sbrk,mmap,alloca, and variable-length array. Can anybody give me even a piece of hint on this? Thanks for you guys but static variables are also forbidden.
My interpretation is that you are supposed to write an implementation on asimulatedheap. That is, you should write code that allows the user to allocate and deallocate address space. The memory does not physically have to be available, but your code should actas ifit manages heap space of some arbitrary size.
This question already has answers here:Undefined, unspecified and implementation-defined behavior(9 answers)Closed2 years ago. in this example ``` for(int i = 0; i < 4; i++) { char c = 's'; printf("%d\n", strcmp(&c, "s")); } ``` output : 0, 1, 2, 3 why the return values of function strcmp() in for(){} are different and increasing?
The code snippet has undefined behavior because the functionstrcmpis designed to compare strings. But the pointer expression&cin this statement ``` printf("%d\n", strcmp(&c, "s")); ``` does not point to a string. It points to a single object of the type char after which the memory can contain anything. So it seems the memory after the objectcis somehow being overwritten in each iteration of the for loop after the statement above. Instead you should write ``` const char *c = "s"; printf("%d\n", strcmp(c, "s")); ```
I am trying to write image rotation code in C. ``` int width, height, channels; unsigned char *img = stbi_load("butterfly.jpg", &width, &height, &channels, 0); ``` I am reading the image as seen. I want to convert these image data to 3D (row, column, channel) array format to be able to do this line: ``` if (Xprime >= 1 && Yprime >= 1 && Xprime <= height && Yprime <= width) { pixel = img[Xprime][Yprime]; } returnedOutImage[i][j] = pixel; } ```
You could cast it to VLA. I assume that pixels are ordered by y, next by x, finally by the channel. ``` unsigned char (*img3d)[width][channels] = (void*)img; ``` Now you can access it byimg3[y][x][c]. There is a question if such a cast violates strict aliasing rules.
How we use a string name in C to print a string without dereferencing it? Like here: ``` char str[]; printf("%s",str); ``` But in case of arrays we use dereferencing by square brackets[] to print an array: ``` int a[10]; for(i=0;i<10;i++); printf("%d",a[i]); ``` What's the difference between printing a string and an array? We need dereferencing an array by using square brackets [] but in case of stringwithout using any dereferencingprintf(); is just printing the value of the string and not the address.
Because that is what the interface toprintfdictates. In case of a"%s"it expects apointerto a NUL terminated string.In case of a"%d"it expects anint.
This is the code that I have: ``` while(1) { if (fmod(get_elapsed_time(), 3.0) == 0.0) { printf("Hello World\n"); } } ``` Theget_elapsed_timefunction returns adoublewhich is the time elapsed since the program started in seconds with the milliseconds after the decimal place. So this code should be printing hello world every 3 seconds but it doesn't and I can't figure out why.
Floating point inaccuracy. Keep track of when you last printed a thing, and when the current time is >= 3 seconds of that, it's time to print more. Something like ``` float last_print_time = get_elapsed_time(); for(;;) { float current_time = get_elapsed_time(); if (current_time - last_print_time >= 3.0) { printf("Beep!\n"); last_print_time = current_time; } } ```
I'm trying to build a C program with Windows gcc using Mingw-w64 installation (gcc.exe (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0). I getundefined reference to `memmem'error. Isn't memmem() a standard glibc function that should be available in all gcc versions?
Asthis postexplains "MinGW does not build against glibc, it builds against msvcrt. As such, it uses libmsvcrtXX.a instead." "gcc and glibc are two separate products." So, yep, no memmem on Windows andhere's the implementation.
I am learning C Programming currently on VS Code. I run program a lot of time repeatedly which mess up terminal. Mostly I useclsbefore running program to clear previous output of terminal. My default terminal is PowerShell in VS Code. Is there any way to clean terminal before each run. What I have tried after google search:-I have tried addingclsto powershell profile but it does not work on every code run.-Checkingclear previous outputincoderunnersettings didn't work either.
The easiest way is to add cls to the beginning of your code, but that's not always best: You can also set a keyboard shortcut forclearing the console(Used to bectrl+k, but was removed) You don't want to replace the existing behavior when running code, but a pretty simple one-button solution could be setting up a vs code macro to doTerminal: Clear, and alsorunyour open file in the terminal.
I'm trying to send a time_t value over a UDP socket. I think that I need to convert it into a string, save int the buffe and send. After a research in internet, I tried with the snprintf() function, but I don't know why does not work. ``` snprintf(buffer, BUF_SIZE, "%s", puntatore_list->date); ``` puntatore_list->date is the time_t value. Is the correct way to do?
If both sides of the communication have the same definition oftime_t(and the sameendianness), you can just send it:send(sock, &(puntatore_list->date), sizeof(time_t), NULL). If not, just agree on a common definition (for example "number of second since some agreed-upon point in time stored as a 64 bit integer") and convert fromtime_tto that before sending.
If I declare two max integers in C: ``` int a = INT_MAX; int b = INT_MAX; ``` and sum them into the another int: ``` int c = a+b; ``` I know there is a buffer overflow but I am not sure how to handle it.
This causes undefined behavior since you are using signed integers (which cause undefined behavior if they overflow). You will need to find a way to avoid the overflow, or if possible, switch to unsigned integers (which use wrapping overflow). One possible solution is to switch to long integers such that no overflow occurs. Another possibility is checking for the overflow first: ``` if( (INT_MAX - a) > b) { // Will overflow, do something else } ``` Note: I'm assume here you don't actually know the exact value ofaandb.
I currently have a queue struct defined as ``` typedef struct { int size; char** data; unsigned count; unsigned head; } queue; ``` It is initialized with ``` Q->size = DEFAULTSIZE; Q->data = malloc(sizeof(char*) * QSIZE); Q->count = 0; Q->head = 0; ``` Whenever I enqueue something, ``` //item is a char* Q->data[i] = malloc(sizeof(char) * item_length); Q->data[i] = item; //If I was to do free(Q->data[i]); at this point, I would get an error as stated below ``` The issue is that whenever I dequeue, and want to freeQ->data[i]I get a WRITE error on the line that I am freeing on. Although usingprintf("%s", Q->data[i]);seems to work fine telling me that I have access to that item. Any advice?
What you probably mean is this: ``` Q->data[i] = malloc(strlen(item) + 1); strcpy(Q->data[i], item); ```
I'm trying to send a time_t value over a UDP socket. I think that I need to convert it into a string, save int the buffe and send. After a research in internet, I tried with the snprintf() function, but I don't know why does not work. ``` snprintf(buffer, BUF_SIZE, "%s", puntatore_list->date); ``` puntatore_list->date is the time_t value. Is the correct way to do?
If both sides of the communication have the same definition oftime_t(and the sameendianness), you can just send it:send(sock, &(puntatore_list->date), sizeof(time_t), NULL). If not, just agree on a common definition (for example "number of second since some agreed-upon point in time stored as a 64 bit integer") and convert fromtime_tto that before sending.
If I declare two max integers in C: ``` int a = INT_MAX; int b = INT_MAX; ``` and sum them into the another int: ``` int c = a+b; ``` I know there is a buffer overflow but I am not sure how to handle it.
This causes undefined behavior since you are using signed integers (which cause undefined behavior if they overflow). You will need to find a way to avoid the overflow, or if possible, switch to unsigned integers (which use wrapping overflow). One possible solution is to switch to long integers such that no overflow occurs. Another possibility is checking for the overflow first: ``` if( (INT_MAX - a) > b) { // Will overflow, do something else } ``` Note: I'm assume here you don't actually know the exact value ofaandb.