question
stringlengths
25
894
answer
stringlengths
4
863
``` void kmmil() { int x, y; printf("a.KM TO MILS\n"); printf("b.MILS TO KM\n"); char c; scanf("%c", &c); printf("this is the value %c", c); } ``` output: ``` this is the value (blank) ``` end;
If the scanf "doesn't work" it usually does but not in a way we intended to. If you have another scanf in your code, that for example scans a number. You type in your terminal something like 123 and hit enter to confirm. That enter however stays in the input and waits to be scanned by something. This is probably why your scanf "doesn't work". Onto the solution to that:I suggest you clear your input. You can do this in at least ``` scanf("%*[^\n]"); // scan and delete everything until newline character scanf("%*c"); // scan and delete one more character (newline) ``` or ``` while(getchar() != '\n'); // get characters until newline (note that newline is deleted this way too!) ```
I was looking at one of the first compilers of c, written by dmr himself. It was written in the early 1970's, so obviously the syntax is very different. Inthisfile, what doesossizmean? ``` ossiz 250; ``` By the way, is there any helpful article or manual on this sort of thing (older c syntax)?
Just like in B, it's a global variable definition with initialization. In modern C it would be: ``` int ossiz = 250; ``` Also:https://github.com/mortdeus/legacy-cc/blob/2b4aaa34d3229616c65114bb1c9d6efdc2a6898e/last1120c/c10.c#L462
Is there any built-in for this operation (in C) ? ``` lock or QWORD [...], ... ``` In fact, I'm searching forlock orin C. If there isn't any built-in, how can I write it in C inline-asm ? I'm using GCC (C version 11).
The standard C11 way of doing this is with <stdatomic.h> andatomic_fetch_or. You can do things like: ``` #include <stdatomic.h> atomic_int var; int res = atomic_fetch_or(&var, 0x100); ```
So I try to take a user input of unknown max length from the command line. The program to be able to do something like that needs to take a dynamic input of a string (char array maybe?). The outcome should be something like ./a.out st1 your str is ... the only code I was able to come up with is the following ``` int main (int argc, char* argv[]){ ... char str1[]; str1 = argv[1]; printf("your...); ... } ```
This declaration of a block scope array with an empty number of elements: ``` char str1[]; ``` is incorrect. Moreover arrays do not have the assignment operator: ``` str1 = argv[1]; ``` You could declare a pointer: ``` char *str1; str1 = argv[1]; printf("your...); ```
What is the use of thestat.hheader incat.c? Here you have thecat.c https://github.com/mit-pdos/xv6-riscv/blob/riscv/user/cat.c Here you have thestat.h https://github.com/mit-pdos/xv6-riscv/blob/riscv/kernel/stat.h I do not see any direct use of thestatstruct in thecat.cso I wonder if there is an indirect one.
It was added inthis commitprobably becauseuser.huses thestruct stat *datatype
When i compile and run it tons of random letters appear in it closes ``` #include <stdio.h> int main(int argc, int* argv[]) { int x; for(x = 0; x < argc; x++) { while(*argv[x]) { putchar(*argv[x]); *argv[x]++; } putchar('\n'); } return 0; } ``` This Programm should take the input from the comand line and print it(i wanted it in this format to test why and how *argv[] works)
You may consider checking for errors. ``` #include <stdio.h> int main(int argc, char *argv[]) { // Exit status if the argument count is incorrect if (argc != 2) { printf("Usage: ./program string\n"); return 1; } ``` Also you may want to print the string without writing a loop usingprintf()fucntion. ``` // Print the whole string in one step printf("%s\n", argv[1]); return 0; } ```
In c in "mpi.h", i think it will be something like ``` MPI_Request mpireq[2]; MPI_Status mpistat; int temp, index, flag; MPI_Irecv(temp, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &mpireq[0]); MPI_Irecv(temp, 1, MPI_INT, MPI_ANY_SOURCE, 1, MPI_COMM_WORLD, &mpireq[1]); MPI_Testany(2, mpireq, &index, &flag, &mpistat); ``` but i think Testany is a non-blocking so i don't know how to use flag and index i propose something like but i don't if this is going to work. ``` if(flag){ printf("someone came\n"); if (index == 0){do something} else{do something else} } else printf("No one is here yet"); ```
I tried something like this and it seems to work ``` MPI_Irecv MPI_Irecv MPI_Testany while(!flag) MPI_Testany(); if(flag) capture Irecv that comes first; ```
How can I replace strdup() with strcpy() and malloc() in linked list in c?
You're confusing the pointer with the value it points at. If you remove thestrdupfrom your code, all the pointers in your linked list end up pointing at the same char array, so if/when you change the string in that char array, all the pointers will see it. So to have distinct strings for each element of the linked list, each element's pointer must point at a different char array. Usingstrdupdoes exactly that, creating a new char array of the correct size withmallocand copying the string into that char array. So each pointer ends up pointing to a different char array with (potentially) a different string in each. To (safely) get rid of strdup you need to do the same thing some other way -- create a new array for each string, so you can have the pointer point at it.
I have to find arecursivefunction in C to compute big Binomial Coefficients. e.g. 59C10 I've written the below code but takes too much time. Is there a better way to do it ? ``` long long nCk(long long n, long long k) { if(n == k || k == 0) { return 1; } else if(k == 1) { return n; } else { return nCk(n-1,k-1) + nCk(n-1,k); } } ```
Consider: That can be directly implemented as: ``` /* The helper assumes all sanity checks have been made */ static long long nCk_helper(int n, int k) { if (k == 0) return 1; return nCk_helper(n - 1, k - 1) * n / k; } long long nCk(int n, int k) { if (n < k || k < 0) return 0; /* Or some error value */ /* Take the shorter of the possible computations */ if (k <= n - k) return nCk_helper(n, k); else return nCk_helper(n, n - k); } ```
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed1 year ago.Improve this question There are 2 ways of struct init in C, and I wonder if there is significant difference in code culture. ``` struct myStruct { int a; int b; }; struct myStruct myVar = {4,5}; ``` or ``` typedef struct { int a; int b; }myStruct; myStruct myVar = {4,5}; ``` Which one is more common used in practice?
The first one is more common. There is no significant difference in real life.
What is a C equivalent tothis C++ answerfortemporarilysilencing output to cout/cerrand thenrestoringit? How to silence and restorestderr/stdout? (Need this to silence noise from 3rd party library that I am calling, and to restore after the call.)
This is a terrible hack, but should work: ``` #include <stdio.h> #include <unistd.h> int suppress_stdout(void) { fflush(stdout); int fd = dup(STDOUT_FILENO); freopen("/dev/null", "w", stdout); return fd; } void restore_stdout(int fd) { fflush(stdout); dup2(fd, fileno(stdout)); close(fd); } int main(void) { puts("visible"); int fd = suppress_stdout(); puts("this is hidden"); restore_stdout(fd); puts("visible"); } ```
What is a C equivalent tothis C++ answerfortemporarilysilencing output to cout/cerrand thenrestoringit? How to silence and restorestderr/stdout? (Need this to silence noise from 3rd party library that I am calling, and to restore after the call.)
This is a terrible hack, but should work: ``` #include <stdio.h> #include <unistd.h> int suppress_stdout(void) { fflush(stdout); int fd = dup(STDOUT_FILENO); freopen("/dev/null", "w", stdout); return fd; } void restore_stdout(int fd) { fflush(stdout); dup2(fd, fileno(stdout)); close(fd); } int main(void) { puts("visible"); int fd = suppress_stdout(); puts("this is hidden"); restore_stdout(fd); puts("visible"); } ```
I usually useprintf("%-8d",a);for example for 8 spaces after (and including) an integer. My code: ``` #include <stdio.h> #include <string.h> int main() { int a = 10; char b = "Hello"; } ``` How can I print:'#10-Hello 'with 16 spaces (8 is the integer and the string, and 8 spaces after)?
Do it in two steps. First combine the number and string withsprintf(), then print that resulting string in a 16-character field. ``` int a = 10; char *b = "Hello"; char temp[20]; sprintf(temp, "#%d-%s", a, b); printf("%-16s", temp); ```
This might seem a very stupid question but how is the member access operation in struct performed? When you writestruct_name.member_namehow does the machine know which member to be accessed? Structs are stored in a contiguous block of memory with some padding(depends) and there is no sort of mapping of member identifiers to memory locations afaik. Unlike arrays, structs cant be accessed using base address offset and size (am I right?) so how does it happen ? Does the access take O(1) or not and what is the reason for it?
I don't know why you assume there is no mapping between identifiers and memory locations? Access to members of structs/classes is just: address of instance (struct) + offset of member. So yes, access to any member is constant time O(1) You can seehttps://en.cppreference.com/w/c/types/offsetof:)
I'm trying to create dynamic memory allocation usingmallocbut always I got 0 as output instead of 5.My code ``` typedef struct{ int nl; double *vect; }vect_t; void creerVecteur(vect_t *ptrVect){ double *p; ptrVect->vect=(double *)malloc(ptrVect->nl*sizeof(double)); ptrVect->vect[0] = 5; ptrVect->vect[1] = 7; ptrVect->vect[2] = 2; printf("%d\n",ptrVect->vect[0]); } int main(){ vect_t v1; v1.nl = 3; creerVecteur(&v1); } ```
You're using the wrong format specifier toprintf. The%dformat specifier is for printing anintin decimal format. To print adouble, use%f.
Here I have tried to create a linked list and create a function which adds any given number to the staring of the linked list. ``` #include <stdio.h> #include <stdlib.h> struct Node{ int data; struct Node* next; }; struct Node* head=NULL; void Add(int n){ head=(struct Node*)malloc(sizeof(struct Node)); head->data=n; head->next=NULL; return; } ``` Now my doubt is, here we have definedheadto be a pointer variable of datatypestruct Node. InAddfunction, we have assigned the address of new memory allocated toheadpointer variable. But when we are writinghead->data=n, why are we not dereferencingheadfirst, sinceheadwas a pointer variable, so it stores address, and to store variables like data, why shouldn't it be*head->data? Similar for*head->next=NULL.
The operator->is already a dereferencing operator.head->datais equivalent to(*head).data.
I am working on an STM32F401 MC for audio acquisition and I am trying to send the audio data(384 bytes exactly) from ISR to a task using queues. The frequency of the ISR is too high and hence I believe some data is dropped due to the queue being full. The audio recorded from running the code is noisy. Is there any easier way to send large amounts of data from an ISR to a task? The RTOS used is FreeRTOS and the ISR is the DMA callback from the I2S mic peripheral.
The general approach in these cases is: Down-sample the raw data received in the ISR (e.g., save only 1 out of 4 samples)Accumulate a certain number of samples before sending them in a message to the task
The right hand operand of a logical operator || has persistent side effects because of calling functiondetectError(). ``` if ( ( detect() == VALID ) || ( detectError() == INVALID ) ) { up( a,b ); } ``` ``` typedef enum { C; }E_name; ``` ``` typedef struct { E_name be:4; }S_name; S_name name; ``` persistent_side_effect: Expression name.be = C has persistent side effect: modifying non-local object okay.be = C. ``` sint16 detectError(void) { name.be = C; } ``` I was able to solve logical operator &&, is there a solution for || operator?
Surely the simplest work around for this is: ``` whateverType detectFlag1 = detect(); whateverType detectFlag2 = detectError(); if ( ( detectFlag1 == VALID ) || ( detectFlag2 == INVALID ) ) { up( a,b ); } ``` Simple, clear code, with no potential side effects?
In c, c++ when we say ``` For i=0 ;i<10 ;i++ Printf(i) ``` It prints the order used in the iretation 0,1,2... but in python I have this example : ``` friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends: print('Happy New Year:', friend) ``` I want to print the oder of the elements, Joseph is 0, Glenn is 1.. Etc, i know i can use a count=count+1 to print it, but I see print order knows already the order of elements, so is there a way similar to c to print the order of elements directly?
You can use theenumeratefunction to get the index of items in a list: ``` for idx, friend in enumerate(friends): print('Happy New Year:', idx, friend) ```
The right hand operand of a logical operator || has persistent side effects because of calling functiondetectError(). ``` if ( ( detect() == VALID ) || ( detectError() == INVALID ) ) { up( a,b ); } ``` ``` typedef enum { C; }E_name; ``` ``` typedef struct { E_name be:4; }S_name; S_name name; ``` persistent_side_effect: Expression name.be = C has persistent side effect: modifying non-local object okay.be = C. ``` sint16 detectError(void) { name.be = C; } ``` I was able to solve logical operator &&, is there a solution for || operator?
Surely the simplest work around for this is: ``` whateverType detectFlag1 = detect(); whateverType detectFlag2 = detectError(); if ( ( detectFlag1 == VALID ) || ( detectFlag2 == INVALID ) ) { up( a,b ); } ``` Simple, clear code, with no potential side effects?
In c, c++ when we say ``` For i=0 ;i<10 ;i++ Printf(i) ``` It prints the order used in the iretation 0,1,2... but in python I have this example : ``` friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends: print('Happy New Year:', friend) ``` I want to print the oder of the elements, Joseph is 0, Glenn is 1.. Etc, i know i can use a count=count+1 to print it, but I see print order knows already the order of elements, so is there a way similar to c to print the order of elements directly?
You can use theenumeratefunction to get the index of items in a list: ``` for idx, friend in enumerate(friends): print('Happy New Year:', idx, friend) ```
After i quit GDB every user-defined function disappear. Im sure there should be some way to make it available between sessions.
GDB reads the followingfilesbefore starting:~/.config/gdb/gdbinit,~/.gdbinit. It is a common practice to edit e.g.~/.gdbinitto define the user-defined function using an external editor and usesource ~/.gdbinitin a GDB session to reload that file. Once the function works as you expect, just leave it in your~/.gdbinitand it will be available in all future GDB sessions.
This question already has answers here:What is an undefined reference/unresolved external symbol error and how do I fix it?(39 answers)Closed1 year ago. I want to compile a C code in the latest version of ubuntu. when I do this, I get the following error: ``` gcc <fileName>.c ``` ``` /usr/bin/ld: /tmp/ccY8CJ10.o: in function `main': sudoku.c:(.text+0xb8): undefined reference to `stdscr' /usr/bin/ld: sudoku.c:(.text+0xc0): undefined reference to `wgetch' collect2: error: ld returned 1 exit status ``` Do you have any idea what causes this?I know the problem is<curses.h>header in my code, but I don't know how to fix it.
You could use-lcurses. Ex:gcc main.c -o demo -lcurses
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.Closed1 year ago.Improve this question I have a set of C code files named as: hmc.c hopping.c phi4.c and I have an 'infile' which contains value of parameters and a 'Makefile'. How do I run these set of files in Ubuntu? Previously in Windows I used gcc compiler with command 'gcc hmc.c hopping.c phi4.c' and then press Enter and then 'a infile' and that did the expected job but on Ubunut it isn't working..
Running the makefile should compile and give you an executable. You can do so by enteringmakein the command line. Make sure you have it installed first.
I'm trying to make a program in C that reads my matrix and calculates the sum of elements, but it gives me an error at scanf("%d",&a[i]). This is the error : ``` warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int (*)[10]’ [-Wformat=] ``` and this is my code: ``` #include <stdio.h> int main() { int m,n,a[10][10],s=0; scanf("%d",&n); scanf("%d",&m); for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) scanf("%d",&a[i]); for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) s=s+a[i][j]; printf("%d",s); return 0; } ``` Anyone know why?
changescanf("%d",&a[i]);toscanf("%d",&a[i][j]);as you need to give him the address to write on but you give the address of array of ten int
I have this struct: ``` typedef struct { int id; node_t * otherNodes; } node_t; ``` where I need an array of nodes in my node.... but in the header file is not recognized: it tell me `unknown type name 'node_t' how can I solve this? thanks
In this typedef declaration ``` typedef struct { int id; node_t * otherNodes; } node_t; ``` the namenode_twithin the structure definition is an undeclared name. So the compiler will issue an error. You need to write for example ``` typedef struct node_t { int id; struct node_t * otherNodes; } node_t; ``` Or you could write ``` typedef struct node_t node_t; struct node_t { int id; node_t * otherNodes; }; ``` Or even like ``` struct node_t typedef node_t; struct node_t { int id; node_t * otherNodes; }; ```
So, I'm basically trying to assign my structure with strings as 0, so then I could change some values later, but I'm getting the warning of "strcpy makes pointer from integer without a cast" and the code is not working how can I fix it? my structure is this ``` struct node{ char ID[3]; char Name[40]; char Code[3]; }; ``` and here is my function ``` void initialiseArray(struct node* arr){ int i; for(i = 0; i < capacity; i++){ strcpy(arr[i].ID[3], "0"); strcpy(arr[i].Name[40], "0"); strcpy(arr[i].Code[3], "0"); } } ```
arr[i].ID[3]in the function definition must bearr[i].ID. Same for the other two fields.arr[i].ID[3]is a [nonexistant] character of a string, not the string.
I have a program in C like this: ``` #include <stdio.h> int main() { float number = 0; scanf("%f", &number); printf("%f\n", number); } ``` And the output is: ``` ururay@note:~/workspace/c/float-precision$ gcc float-precision.c -o float-precision ururay@note:~/workspace/c/float-precision$ ./float-precision 5456.367 5456.367188 ``` I have executed this program several times and the output is the same. Is the '188' "appended" to the end of the number because float precision? If so, how could I identify this in binary representation?
The number5456.367cannot be represented exactly in theIEEE-754single-precision floating point format. The closest number is5456.3671875, which has the binary representation01000101101010101000001011110000. The next smaller representable number is5456.3666992, which has the binary representation01000101101010101000001011101111.
Suppose that in the main function an int type varaible x has a value 20. IF the function is called 2 times as foo(&x) , whats the value of x? ``` #include<stdio.h> void foo(int *n) { int *m; m = (int *)malloc(sizeof(int)); *m = 10; *m = (*m)*5; n = m; } int main() { int x = 20; foo(&x); printf("%d",x); } ``` Shouldn't the value of x be 50 since we are initializing the address of n with m which has the value 50 but its coming out to be 20?
Theaddressof thenpointer is local tofoo. So modifying thepointerinsidefoohas no effect outside of the function. But when dereferencingn, thepointed-tovalue can be changed. Forxto become 50, the last line of thefoofunction should have been: ``` *n = *m; ```
Given a meson-based project wheremeson.buildcontains the following line: ``` cc = meson.get_compiler('c') ``` How doesmeson.get_compiler('c')pick a compiler on a system with multiple C compilers? At the time of writing this question, the reference manual does not provide much detail, only... Returns a compiler object describing a compiler. Please note I am not trying to force meson to use a specific compiler. Rather, I am trying to understand how this line inmeson.build,as it is currently written, will function.
On Windows it tries icl, cl, cc, gcc, clang, clang-cl, pgcc; on Linux it tries cc, gcc, clang, nvc, pgc, icc. That's after it looks for the value of $CC and whatever is in your cross or native file.See the code here.
I have some old code files in my C++ project, that need to be compiled as C code - the entire codebase is set to compile as C++. I am using Visual Studio, but I'd rather avoid setting this per-file from the project properties, and would rather use some kind of#pragmadirective (if possible). I have searched around, but found nothing, the closes I could think of is to add an#ifdef, that checks for__cplusplusand fails if does so. Basically I am looking for a way to inject the/Tc, /Tp, /TC, /TP (Specify Source File Type)commands from the source.
"By default, CL assumes that files with the .c extension are C source files and files with the .cpp or the .cxx extension are C++ source files." So rename the files if nessesary and put the new c files to your projekt. If neded set the compiler options:Set compiler
I am trying to split binary (for example0100 0101 0100 0001) into binaries with 6 bit size (get0100,010101,000001, ) and also add to them two binaries (add10to000001=>10000001). How can I do this in C?
You are looking forbitwise operators A few examples, with the mandatory0bat the beginning of binary literals: ``` 0b0100010101000001 & 0b111111;// = 0b000001 0b0100010101000001 & (0b111111 << 6);// = 0b010101 0b0100010101000001 & (0b111111 << 12);// = 0b010001 0b101010 | (0b10 << 6);// = 0b10101010 ``` Note: Depending on the compiler you are using, writing binary literals as0bxxxxmay not be valid, as it is not standard. You may have to convert to decimal or hex (0xAF). Seethis post.
I am trying to split binary (for example0100 0101 0100 0001) into binaries with 6 bit size (get0100,010101,000001, ) and also add to them two binaries (add10to000001=>10000001). How can I do this in C?
You are looking forbitwise operators A few examples, with the mandatory0bat the beginning of binary literals: ``` 0b0100010101000001 & 0b111111;// = 0b000001 0b0100010101000001 & (0b111111 << 6);// = 0b010101 0b0100010101000001 & (0b111111 << 12);// = 0b010001 0b101010 | (0b10 << 6);// = 0b10101010 ``` Note: Depending on the compiler you are using, writing binary literals as0bxxxxmay not be valid, as it is not standard. You may have to convert to decimal or hex (0xAF). Seethis post.
I've tried different types of string input(scanf, getchar, gets), but none of them can finish input with Enter. Do you guys have any ideas?
As Cheatah said, the function you looking for isfgets(). Always try to avoidgets()as it offers no protections against a buffer overflow vulnerability and can cause big problems in your program. You can read some of the answers to this question to clarify the utility of each functionScanf() vs gets() vs fgets()
I've tried different types of string input(scanf, getchar, gets), but none of them can finish input with Enter. Do you guys have any ideas?
As Cheatah said, the function you looking for isfgets(). Always try to avoidgets()as it offers no protections against a buffer overflow vulnerability and can cause big problems in your program. You can read some of the answers to this question to clarify the utility of each functionScanf() vs gets() vs fgets()
So i wanna to make a program that if I : Input : 1 & 2 & 3 Output : & 1 ``` #include <stdio.h> int main() { char array[5]; int arr[5]; for (int i = 0; i < 5; i++){ if (i%2 == 0){ scanf("%d",arr[i]); } else { scanf(" %s ",array[i]); } } printf("%s",array[1]); printf(" %d",arr[0]); } ```
You are using scanf incorrectly. Write ``` if (i%2 == 0){ scanf( "%d", &arr[i]); } else { scanf( " %c", &array[i]); } ``` or ``` if (i%2 == 0){ scanf( "%d", arr + i ); } else { scanf( " %c", array + i ); } ``` Also in the call of printf write ``` printf("%c",array[1]); ```
When Iprintffollowing code, I gethex escape sequence out of range.\x1bisnumeric escapeforESC. If my string is literally the1ESC1, how to represent it? ``` #include <stdlib.h> #include <stdio.h> int main(void){ printf("1\x1b1\n"); return EXIT_SUCCESS; } ```
"\x1b is numeric escape for ESC" is true, but thehex escape sequencehere is\x1b1, not\x1b. Avoidprintf(st)to print astringst. The first argument toprintf()is for a format. OK in OP's case, but better to avoid that maybe some escape sequence was used that was the same as%. Tryputs("1" "\x1b" "1");.
I just want to know if a line break (i.e. '\n') can only be written to the stdout if 1 byte is used for such, I mean, does a line break have to be called like this? ``` write(1, "\n", 1); ``` or can it be called like this? ``` write(1, "\n", 0); ```
Bytes are bytes. There's nothing magical about\nthat makes it not count. It has to be the former.
I need help with a function that finds the line with the largest number of numbers in a two-dimensional array and prints index this row. I don't know how to start for help thank you. main.c ``` int array[2][2]= { {1,0}, {0,-3} }; printf("%d\n", largest_line(2, array)); ``` ``` int largest_line(const int size, int array[][size]){ for(int col= 0; col < size; col++){ for(int row = 0; row <size; row++){ // and on this place I stop } } } ```
Something like this should work for you: ``` int largest_line(const int size, int array[][size]){ int largest_number = 0; int largest_row = 0; for(int col= 0; col < size; col++){ for(int row = 0; row <size; row++){ if(largest_number > array[col][row]) { largest_number = array[col][row]); largest_row = row; } } } return largest_row; } ```
``` int (*EVP_MD_meth_get_cleanup(const EVP_MD *md))(EVP_MD_CTX *ctx) ``` I find this code piece, not sure how to understand it. I thinkEVP_MD_meth_get_cleanupis the name of the function pointer type, returnint, but not understand the argument part.
EVP_MD_meth_get_cleanupis a function, that takesconst EVP_MD *mdas an argument, andreturns a function pointer. That function pointer takesEVP_MD_CTX *ctxand returns anint. Nothing better than an example: ``` int somefunction(EVP_MD_CTX *ctx) { stuff(); } int (*EVP_MD_meth_get_cleanup(const EVP_MD *md))(EVP_MD_CTX *ctx) { return somefunction; } ```
I hope not to sound very foolish here, but does the NULL module actually require memory allocation or not when doing this: ``` TheNull = malloc(sizeof(NULL)); ``` If true, how can something that has no memory allocated actually exist in the ram?
If you use NULL as parameter ofmalloc(sizeof()), does it returnNULL? No, unless out-of-memory, like any other allocation. NULL, thenull pointer constant, does not have a particular type. It may bevoid *,int,long, or some integer type. Avoidsizeof(NULL)as its size/type may differ from system to system.
What is wrong with this code? I don't get why this isn't working. ``` struct point { int x; int y; } eh; void main() { eh = {1, 2}; printf("%i", eh.x); } ``` but this works fine ``` struct point { int x; int y; } eh; void main() { eh.x = 2; printf("%i", eh.x); } ```
That kind of syntax might work in some other languages, but in C you should write: ``` eh = (struct point){1, 2}; ``` The expression on the right hand side is called acompound literal.
im facing an problem in this program, may anyone tell me, what im doing wrong, the program won't display anything after i give it input. (Code is about sum of digits enter #example 12345 = 15) ``` #include<stdio.h> int sum(int num); int sum(int num){ int total=0; if(sum==0){ return total; } else{ total+=num%10; num/=10; return sum(num); } } int main() { int num,k; printf("Enter 5 positive number: "); scanf("%d",&num); printf("Sum is: %d",sum(num)); } ```
Here is a rule of thumb, whenever you have a non-stopping recursion program try to verify your base cases. Here you are verifyingsumthe function instead ofnumthe parameter. The C compiler let's you do that because functions in C are pointers, and pointers hold the addresses as numeric value.
How to change the signs in the number field? ``` void swap_sign(const int size, int array[]) { if (array[] != NULL) { for (int i = 0; i < size; i++) { if (array[i] == /* - */ ) { //turn the sign to + and save to the field } else if (array[i] == /* + */ ) { //turn the sign to - and save to the field } } } } ```
Not sure why you have commented things out in the for loop, but switching signs is achieved with just multiplying the minus sign. array[i] = -array[i]; ``` for(int i=0; i < size; i++){ array[i] = -array[i]; } ```
If you run the following code you will get the ASCII characters, even though we useint iwithin%cinside the for loop. ``` #include <stdio.h> int main() { int i; for (i = 0; i <= 255; i++) /*ASCII values ranges from 0-255*/ { printf("ASCII value of character %c = %d\n", i, i); } return 0; } ``` Could you please advise how is this possible since there are characters inside ASCII?
Every variable in the computer is stored as binary and its value will depend on the type you define. For example, in memory store the value1010. If you cast it asint, it will print -6, if you cast it asunsigned int, it will print 10. Same for int and char. It depends on you
I need to use VirtualAlloc() on a C code application in order to run a piece of assembly code using memory pointer. I'm trying to build the code on Windows XP 32 bit for a testing purpose but I can't find a way to use VirtualAlloc(). I installed the last available Visual C++ Redistributable package using the suggestion of Microsoft from here:https://learn.microsoft.com/en-US/cpp/windows/latest-supported-vc-redist?view=msvc-170 Any tip? Thank you
When I coded for Windows XP, VirtualAlloc was found in windows.h. If you can't locate it, copy/paste the declaration. ``` LPVOID WINAPI VirtualAlloc(LPVOID lpaddress, SIZE_T size, DWORD flAllocationType, DWORD flProtect); ```
"undefined reference to 'func~'" error.. I'm new to that program, so I can't figure out the reason for the error. enter image description here
You need to add#include <stdlib.h>
I am trying to use gui with gkt-2.0 in Linux mint 32bit. When I try to compile gui.c I encountered following error message: ``` #include<gtk-2.0/gtk/gtk.h> void main(){ } ``` ``` In file included from gui.c:1:0: /usr/include/gtk-2.0/gtk/gtk.h:32:10: fatal error: gdk/gdk.h: No such file or directory #include <gdk/gdk.h> ^~~~~~~~~~~ ```
When the appropriate packages are installed, you can add the needed include search directories with option-I, and the libraries of course-l, e.g. ``` gcc -I/usr/include/gtk-2.0 gui.c -o gui -lgtk-2.0 ``` The source should be changed to ``` #include <gtk/gtk.h> ``` To avoid hard-coding any paths and names, you could usepkg-config (Compiling GTK Applications on UNIX) ``` gcc $(pkg-config --cflags gtk+-3.0) gui.c -o gui $(pkg-config --libs gtk+-3.0) ``` Better yet, usemakeor some other build tool.
``` #include<stdio.h> void main() { int a[]= {10,20,30,40,50,60}; int *p[]= {a,a+1,a+2,a+3,a+4,a+5}; int **pp=p; pp++; printf("%d,%d,%d", pp-p,*pp-a, **pp); *pp++; printf("%d,%d,%d", pp-p, *pp-p, *pp-p); ++*pp; printf("%d,%d,%d", pp-p, *pp-a, **pp); ++**pp; printf("%d,%d,%d", pp-p, *pp-a, **pp); } ``` it's showing this error: ``` invalid operands to binary - (have 'int *' and 'int **') printf("%d,%d,%d", pp-p, *pp-p, *pp-p); invalid operands to binary - (have 'int *' and 'int **') printf("%d,%d,%d", pp-p, *pp-p, *pp-p); ```
*pp-p, you cannot subtract aint**from anint*since they are not compatible types. It should bepp-p. Also please note that in order to print addresses with printf, you should cast the pointers tovoid*and print using%p.
I'm doing a C program to solve a system of linear equations by fixed point iteration method. And I have to check if the main matrix is diagonally dominant. But when I enter abs and element of the matrix, it says Error (active) E0308 more than one instance of overloaded function "abs" matches the argument list. How can I fix this? ``` //for every row for (i = 0; i < size; i++) { //for every column finds the sum of the row double sum = 0; for (j = 0; j < size; j++) sum += abs(k[i][j]); sum -= abs(k[i][i]); //check if (abs(k[i][i]) < sum) { printf("The matrix is not diagonally dominant."); } } ```
int abs(int)is forint. Usedouble fabs(double)withdoubles.
I am trying to use gui with gkt-2.0 in Linux mint 32bit. When I try to compile gui.c I encountered following error message: ``` #include<gtk-2.0/gtk/gtk.h> void main(){ } ``` ``` In file included from gui.c:1:0: /usr/include/gtk-2.0/gtk/gtk.h:32:10: fatal error: gdk/gdk.h: No such file or directory #include <gdk/gdk.h> ^~~~~~~~~~~ ```
When the appropriate packages are installed, you can add the needed include search directories with option-I, and the libraries of course-l, e.g. ``` gcc -I/usr/include/gtk-2.0 gui.c -o gui -lgtk-2.0 ``` The source should be changed to ``` #include <gtk/gtk.h> ``` To avoid hard-coding any paths and names, you could usepkg-config (Compiling GTK Applications on UNIX) ``` gcc $(pkg-config --cflags gtk+-3.0) gui.c -o gui $(pkg-config --libs gtk+-3.0) ``` Better yet, usemakeor some other build tool.
``` #include<stdio.h> void main() { int a[]= {10,20,30,40,50,60}; int *p[]= {a,a+1,a+2,a+3,a+4,a+5}; int **pp=p; pp++; printf("%d,%d,%d", pp-p,*pp-a, **pp); *pp++; printf("%d,%d,%d", pp-p, *pp-p, *pp-p); ++*pp; printf("%d,%d,%d", pp-p, *pp-a, **pp); ++**pp; printf("%d,%d,%d", pp-p, *pp-a, **pp); } ``` it's showing this error: ``` invalid operands to binary - (have 'int *' and 'int **') printf("%d,%d,%d", pp-p, *pp-p, *pp-p); invalid operands to binary - (have 'int *' and 'int **') printf("%d,%d,%d", pp-p, *pp-p, *pp-p); ```
*pp-p, you cannot subtract aint**from anint*since they are not compatible types. It should bepp-p. Also please note that in order to print addresses with printf, you should cast the pointers tovoid*and print using%p.
I'm doing a C program to solve a system of linear equations by fixed point iteration method. And I have to check if the main matrix is diagonally dominant. But when I enter abs and element of the matrix, it says Error (active) E0308 more than one instance of overloaded function "abs" matches the argument list. How can I fix this? ``` //for every row for (i = 0; i < size; i++) { //for every column finds the sum of the row double sum = 0; for (j = 0; j < size; j++) sum += abs(k[i][j]); sum -= abs(k[i][i]); //check if (abs(k[i][i]) < sum) { printf("The matrix is not diagonally dominant."); } } ```
int abs(int)is forint. Usedouble fabs(double)withdoubles.
Given the fact that local variables inside a function in C get pushed to the stack once the function is called (After pushing the variables being passed to the function), is there any limit to the quantity of said variables before the stack buffer overflows? Or that limit is just given by the amount of RAM a determined host has? I've tried to test this by creating a 4,6gb .C file with a single function having 25000*13 variables declared and initialized to 0. Said function is called insidemain()but it compiled just fine (With -O0) and it didn't crash.
For example according to the C Standard (5.2.4.1 Translation limits) 1 The implementation shall be able to translate and execute at least one program that contains at least one instance of every one of the following limits:— 4095 external identifiers in one translation unit— 511 identifiers with block scope declared in one block
When using the inputhello worldto this program it outputshellwhich is less than 5 why does this happen ``` void grab_user_input() { char user_input[10]; if ( fgets(user_input, 5 , stdin ) != NULL ) { printf("%s\n",user_input); } } int main() { grab_user_input(); return 0; } ```
The last byte is the null byte\0. Read thefgetsmanual for more info. Here's an excerpt: char *fgets( char *restrict str, int count, FILE *restrict stream );Reads at mostcount - 1characters from the given file stream and stores them in the character array pointed to bystr. Parsing stops if a newline character is found, in which casestrwill contain that newline character, or if end-of-file occurs. If bytes are read and no errors occur, writes a null character at the position immediately after the last character written tostr.
I can only use POSIX standard library functions. I want to usesplicefunction. Is it POSIX or not? How can I find out?
You can check man-pages: ``` $ man splice ``` Itsays: ``` CONFORMING TO This system call is Linux-specific. ``` So it is not in POSIX.
I am new to c coding, my program is running well when useintdata type, but when I usecharit starts skipping line. ``` #include <stdio.h> int main() { int i; char k[10]; for (i = 0; i < 10; i++) { printf("enter your character for line %d: \n", i); scanf("%c", &k[i]); } for (i = 0; i < 10; i++) { printf("your character for line %d are %c \n", i, k[i]); } return 0; } ```
Well, when you press Enter you are writting 'new line' character to program's input.And because it's character,%cis reading it. Specifier%cdoesn't consume spaces like other specifiers, so you have to explicitly tellscanfto skip whitespaces, by adding space before%c, so you will have" %c"as format. More details might be here:https://stackoverflow.com/a/5240807/2416941 EDIT:Be aware that this way you can't read space or tabs from user's input.
I can only use POSIX standard library functions. I want to usesplicefunction. Is it POSIX or not? How can I find out?
You can check man-pages: ``` $ man splice ``` Itsays: ``` CONFORMING TO This system call is Linux-specific. ``` So it is not in POSIX.
I am new to c coding, my program is running well when useintdata type, but when I usecharit starts skipping line. ``` #include <stdio.h> int main() { int i; char k[10]; for (i = 0; i < 10; i++) { printf("enter your character for line %d: \n", i); scanf("%c", &k[i]); } for (i = 0; i < 10; i++) { printf("your character for line %d are %c \n", i, k[i]); } return 0; } ```
Well, when you press Enter you are writting 'new line' character to program's input.And because it's character,%cis reading it. Specifier%cdoesn't consume spaces like other specifiers, so you have to explicitly tellscanfto skip whitespaces, by adding space before%c, so you will have" %c"as format. More details might be here:https://stackoverflow.com/a/5240807/2416941 EDIT:Be aware that this way you can't read space or tabs from user's input.
I have a pointer to poinetr that I am getting in function as parameterchar **image now I want to assign it to char pointer such that if I allocatediskthen the calling function oftestcan free it image and disk will be freed too. Is it possible in C? This is my function that calling function is calling and image is pointer to pointer parameter. I calling this function aschar *image="hello";test("hello",&image) ``` int32_t test(const char *path,char **image){ *(char *)(&disk) =*image; 34 printf("ya %s\n",*disk); ```
``` *(char *)(&disk) ^^^^^ take the address of disk (with type "pointer to type of disk") ^^^^^^^^^ ^ convert that to a pointer to char ^ and finally get the single char pointed to by that mess *(char *)(&disk) = *image; // nope, you cannot assign a pointer to char to a char. ```
When I am printing the error message of the execution of a non-existent command like "asdf": ``` execl("/bin/asdf", "asdf", NULL); printf("%s\n", strerror(errno)); ``` I get the messageNo such file or directory. On the other hand, if I run the same command in the terminal, I get ``` Command 'asdf' not found, did you mean: command 'sdf' from deb sdf (2.001+1-7) command 'asdfg' from deb aoeui (1.7+20160302.git4e5dee9-2) command 'adsf' from deb ruby-adsf (1.4.3+dfsg1-1) command 'sadf' from deb sysstat (12.2.0-2ubuntu0.1) Try: sudo apt install <deb name> ``` As I am building a pseudo terminal, is there a way to recreate the message send by the actual terminal in Unix? Thank you in advance!
As suggested by @Gerhardh, run your command via the shell: ``` execl("/bin/bash", "bash", "-c", "asdf", "/bin/asdf"); ```
I have a problem with my code these 2 conditions aren't True. In fact, I have a Python background and they seem right for me. I hope anyone could help me solving this problem. Thanks for your Time ! ``` char cArray[12] = "Hello World"; char* pcVal = &cArray[2]; if (cArray[2] == "l"){} if ((*pcVal) == "l"){} ```
You are comparing a char with a string literal. You need to use 'l' char cArray[12] = "Hello World"; ``` char* pcVal = &cArray[2]; if (cArray[2] == 'l'){} if ((*pcVal) == 'l'){} ```
Sample code (t0.c): ``` #include <stdio.h> #include <fenv.h> int main(void) { printf("%e\n", 1.0f); { #pragma STDC FENV_ACCESS ON return fetestexcept(FE_INEXACT) ? 1 : 0; } } ``` If1is returned, then is it an error?
Yes. Even more: not just "allowed", but "required". IEEE 754-2019, 5.12.2: If rounding is necessary, they shall use correct rounding and shall correctly signal the inexact and other exceptions. ISO/IEC 9899:202x (E) working draft— December 11, 2020 N2596, Annex F.5: The "inexact" floating-point exception is raised (once) if either conversion is inexact.392) (The second conversion may raise the "overflow" or "underflow" floating-point exception.) The specification in this subclause assures conversion between IEC 60559 binary format and decimal character sequence follows all pertinent recommended practice.
MISRA C-2012 Control Flow Expressions (MISRA C-2012 Rule 14.2) misra_c_2012_rule_14_2_violation: The expression i used in the for loop clauses is modified in the loop body. ``` for( i = 0; i < FLASH; i++ ) { if( name.see[i] == 0xFF ) { name.see[ i ] = faultId | mnemonicType; ``` modify_expr: Modifying the expression i. ``` i = FLASH-1; /* terminate loop */ } } ```
You aren't allowed to modify the loop iteratoriinside the loop body, doing so is senseless and very bad practice. Replace the obfuscated codei = FLASH-1;withbreak;.
I've been having some problems trying to figure out with header is useful to manage to get a screen, and draw shapes in it, using C. Tried to use 'graphics.h' but is not working for me, I think maybe 'graphics.h' is meant to be used in C++ and not C? I really don't know and would appreciate it if someone knows anything.
On Linux, you can't build a graphical app using only stdlib. You have to add something like OpenGL, Xlib, maybe Qt or even SFML. Good luck to make an app)
Sample code (t0.c): ``` #include <stdio.h> #include <fenv.h> int main(void) { printf("%e\n", 1.0f); { #pragma STDC FENV_ACCESS ON return fetestexcept(FE_INEXACT) ? 1 : 0; } } ``` If1is returned, then is it an error?
Yes. Even more: not just "allowed", but "required". IEEE 754-2019, 5.12.2: If rounding is necessary, they shall use correct rounding and shall correctly signal the inexact and other exceptions. ISO/IEC 9899:202x (E) working draft— December 11, 2020 N2596, Annex F.5: The "inexact" floating-point exception is raised (once) if either conversion is inexact.392) (The second conversion may raise the "overflow" or "underflow" floating-point exception.) The specification in this subclause assures conversion between IEC 60559 binary format and decimal character sequence follows all pertinent recommended practice.
MISRA C-2012 Control Flow Expressions (MISRA C-2012 Rule 14.2) misra_c_2012_rule_14_2_violation: The expression i used in the for loop clauses is modified in the loop body. ``` for( i = 0; i < FLASH; i++ ) { if( name.see[i] == 0xFF ) { name.see[ i ] = faultId | mnemonicType; ``` modify_expr: Modifying the expression i. ``` i = FLASH-1; /* terminate loop */ } } ```
You aren't allowed to modify the loop iteratoriinside the loop body, doing so is senseless and very bad practice. Replace the obfuscated codei = FLASH-1;withbreak;.
I've been having some problems trying to figure out with header is useful to manage to get a screen, and draw shapes in it, using C. Tried to use 'graphics.h' but is not working for me, I think maybe 'graphics.h' is meant to be used in C++ and not C? I really don't know and would appreciate it if someone knows anything.
On Linux, you can't build a graphical app using only stdlib. You have to add something like OpenGL, Xlib, maybe Qt or even SFML. Good luck to make an app)
the given code is: ``` int main() { char *str = "hello world"; str[0] = 0; printf("%s\n", str); //prints nothing } ``` I know that I can't edit the part of the string like 'str[5] = 'w;', so I thought that line 4 'str[i] = 0;' would work like this. But it seems to clear the string and thus prints nothing. Can someone please explain why line 4 works like that?
0or'\0'is a null character. In the C language, a string is a null-terminated array ofchars. So, if you put0at the very first element of thechararray, it will represent anemptystring (having length zero) when interpreted as a null-terminated string, such as by the%sspecifier ofprintf(). But, your code is invalid, because you can't modify astring literal. It has to be more like this instead: ``` int main() { char str[] = "hello world"; str[0] = 0; printf("%s\n", str); //prints nothing } ```
I have coded a program that reads an integers & tells if it's greater or not. I have done it with an array & initialized it with some numbers(As a test if the program works). Now I have to read it from a File with a lot of integers, but I don't know the length of the File. How can I determinate the size of the Array if I don't know the length?
Either you do it on the fly (read and process one line at a time -> one number at a time), or you need to allocate memory dynamically as you read the file as described here:Dynamically expanding array using realloc
I am looking at some code and came across this line: ``` fscanf(file, "%*[: ]%16s", dest); ``` What does the%*[: ]%16sformat string specifier do?
This format string ``` "%*[: ]%16s" ``` means that all symbols':'and' '(the symbols placed in the square brackets in the format string) must be skipped in the input stream and then at most 16 characters be read in a character array. In the format string the symbol*is assignment-suppressing character. Here is a demonstration program. For visibility I am usingsscanfinstead offscanf. ``` #include <stdio.h> int main( void ) { const char *stream = "::: : : : :::Hello"; char s[17]; sscanf( stream, "%*[: ]%16s", s ); printf( "\"%s\"\n", s ); return 0; } ``` The program output is ``` "Hello" ```
In this C program, if I enter b as the input, the program prints Enter correct input. If I enter b45 as the input, the program again prints Enter correct input. But, if I enter 45b, the program takes 45 as the input and proceeds normally. If I enter 45b, the program should print Enter correct input, but it is not happening. ``` #include <stdio.h> int main() { double i; printf ("Enter a number. \n"); while (scanf("%lf", &i) == 0) { printf("Enter correct input. \n"); fflush (stdin); } printf ("%lf\n", i); return 0; } ```
Instead of reading viascanf(), read alineof user input withfgets(buf, ...), then usestrtof(buf, &endptr))to assess if the the input was numeric andendptrto assess what is after the numeric text.
I have seenthis questionabout getting the quotient and remainder in a single operation in C. However the Cdivandldivfunctions takeintandlongarguments. But how can I performunsigneddivision and save both the remainder and quotient in C? There is to my knowledge nounsignedversions ofdivorldiv. Will I have to use inline assembly?
Just use%and/close enough to each other, and let any reasonable modern optimizing compiler translate them to a single instruction. Godbolt Example ``` struct res { unsigned long long quo; unsigned long long rem; } f(unsigned long long x, unsigned long long y) { struct res r; r.quo = x / y; r.rem = x % y; return r; } ``` Compiled by GCC 11.2-O2to: ``` f: mov rax, rdi xor edx, edx div rsi ret ```
i've been trying some stuff with the realloc function and ran into a problem with strings: ``` char *s="hello"; s=realloc(s,size); // this return null char *p; p=malloc(5); strcpy(p,"hello"); p=realloc(p,size) // this works fine ``` why does the first declaration fail?
This line declaressand reserves some static storage space for"hello", then assigns a pointer to it tos. ``` char *s="hello"; ``` This second line is trying toreallocmemory that was never dynamically allocated. In fact, it's static. ``` s=realloc(s,size); // this return null ``` No wonder it fails. Actually, it could very well crash your program, it's undefined behavior! You can only usereallocorfreeon memory that was previously returned by a call tomalloc(or variants). Nothing else. See also: String literals: Where do they go?C: do all string literals have static storage duration?
I made a code of is_coprime function and euler function. but the results come out 0. what is the problem?you don't need to touch the main function part.you don't need to add anything else. only the is_coprime, euler function part can be modified. ``` #include <stdio.h> int is_prime(int m, int n) { int r; while (n > 0) { r = m % n; m = n; n = r; if (m == 1) break; } } int euler(int n) { int i; int sum = 0; for (i = 0; i <= n; i++) { if (is_prime(i, n) == 1) sum += 1; } return sum; } main() { int i; for (i = 2; i <= 10; i++) { printf("euler(%d) = %d\n", i, euler(i)); } } ```
I guess your <is_prime> function is not returning anything. put a suitable "return" part for it.
I want the following idea: I haveshort a = -4;and I have anunsigned short b = (unsigned short)a;When Iprintf("%hu", b), why doesn't it print4? How can I convert a negative integer to a positive integer using casting?
shortandunsigned shortare normally 16 bit integers. So limits are -32768 to 32767 for the signed version (short) and 0 to 65535 forunsigned short. Casting from signed to unsigned justwrapsvalues, so -4 will be casted to 65532. This is the way casting to unsigned works in C language. If you accept to use additions/substractions, you can do: ``` 65536l - (unsigned short) a ``` The operation will use thelongtype (because of thelsuffix) which is required to be at least a 32 bits integer type. That should successfully convert any negative short integer to its absolute value.
I want to follow up on this question:What is the difference between a definition and a declaration?, there is answer about definition and a declaration, but nothing about implementation. I want also know what is the difference between implementation and definition.
Function definition etc is a formal term, but "implementation" is a fuzzy informal term. In plain English, it could refer to your application's implementation of something, like for example a function. The implementation phase of a project is typically the phase where you write all the code. And so on - it depends on context. In formal/technical C programming terms,implementationmeans the implementation of the C language. That is:formallyimplementationmeans the C compiler and standard library.And the formal termimplementation-defined behaviormeans compiler-specific behavior.
I am trying to open a file and write to it. Whenever I run the program, it creates thetextfile.txtbut it's empty. How do I deal with this? ``` #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <string.h> int main() { char buf[1024]; int file = open("testfile.txt", O_CREAT | O_WRONLY, 0644); strcpy(buf, "My message"); write(file, buf, sizeof(buf)); close(file); } ```
Change your code to: ``` #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <string.h> int main() { char buf[1024]; int file = open("testfile.txt", O_CREAT | O_WRONLY, 0644); strcpy(buf, "My message"); write(file, buf, strlen(buf)); close(file); } ```
write the post order of the above BST I,m confusing it starts with 50 or 60
"Post order" means that a parent is always visitedafter("post") its children are visited.. So if you would start with 50, you cannot visit 60 anymore, as that would violate that rule. The post order thus starts like this: 60, 50, 80, ... As this is an assignment, please figure out the rest yourself, just making sure you always abide to the above rule.
I usedffigento generate bindings from a C header file. One of the methods in C isopen(const char *path), and ffigen generated a binding methodopen(ffi.Pointer<ffi.Int8> path). If I want to have a dart methodopen(String path)that access this binding method how can I convert the String parameter to ffi.Pointer<ffi.Int8>?
Try ``` "Your message".toNativeUtf8().cast<Int8>() ``` Also see erjo's comment inhttps://github.com/dart-lang/ffigen/issues/72
I want to find where the leading zero ends in a string? but a unexpected problems happened... ``` for(i=2980;(bin[i]==0)&&(i>=0);i--);//this failed to past for(i=2980;i>=0&&bin[i]==0;i--);//this is accepted by testing-web ``` but I think this two expressions have the same meaning..I can't find the reason ,please help me, thank you.
I think this two expressions have the same meaning They do not. They differ. a && bis a "short-circuit" evaluation.Ifaisfalse,bis not evaluated.Ifaistrue, thenbis evaluated. Consider what happens wheni == -1: ``` // Only (-1 >= 0) evaluated // Since it was false bin[-1]==0 was not attempted. (i >= 0) && (bin[i]==0) // Code first tries bin[-1], which is outside the array bin[] // Result: undefined behavior (UB). // In OP's case, program failed. (bin[i]==0) && (i>=0) ```
How can I find the length of a string from an array of pointers to a string? For example, if I want to find the length of the string "apple" then how can I calculate length of it? I tried many ways, but I couldn’t. If I do sizeof(str[0]), it returns the size of the pointer (4 bytes in my 32-bit device). Are they stored in the memory location next to each other or not? ``` const char *str[] = { "apple", "ball", "cat", "dog", "mep", "helsdf" }; ```
Use strlen() from string.h ``` #include <stdio.h> #include <string.h> int main() { const char *str[] = { "apple", "ball", "cat", "dog", "mep", "helsdf" }; printf("Length of \"%s\": %zu\n", str[0], strlen(str[0])); return 0; } ```
If I compile a C program on Windows 10, can that program run on Windows 7? If I compile a C program on Windows 10 Home, can that program run on Windows 10 Pro?
yes , you can run your program in any windows.I think knowing aboutcompile processcan help you.
Hi guys i'm kind of new to c programming so sorry if my question seems evident. When i use scanf("%c",c) it counts space as a character so what should i do to ignore the spaces between input characters? Any help would be much appreciated.
The only thing you should do is to consider spaces as characters and scanning them like other characters. for example if you want to scan "a b" in characters, you should write ``` scanf("%c %c %c", &c1, &c2, &c3); ``` so that the space will be c2.
Hi I am beginner in programming and in C. I am trying to scan a character array but when I hit enter instead of submitting my input it go to the next line and then typing any character and hitting enter it submit, What is wrong with my code? by the way I am using a CodeBlocks IDE. Thanks, sorry for noob question I can't find any answer. EDITED: I Answered my own question lol I realize I add\ninscanffunction ``` #include <stdio.h> #include <conio.h> int main() { char name[21]; printf("what is your name\n"); scanf("%s\n", name); printf("%s\n", name); getch(); return 0; } ```
the answer is in the comment by @some programmer dude. I forget that I add\nintoscanf("%s", name)like thisscanf("%s\n", name)
Say I have some code snippet ``` char *str = malloc(sizeof(char)*10) // some code to add content to the string in some way ``` To create a string of 10 chars. If I then copystrwithstrcpyfrom the standard string library into a new variable like so ``` char *copy; strcpy(copy, str); ``` I'm aware I then need to freestrusingfree(str), but is that enough? Or doesstrcpyalso dynamically allocate memory forcopyif used on a string created from malloc?
Or does strcpy also dynamically allocate memory for copy No,strcpyknows nothing about memory, so your code copies a string into an uninitialized pointer pointing at la-la land. If you want allocation + copy in the same call, there is non-standardstrdupfor that (which looks like it will be added to the C standard in the next version of the language). Alternatively just dochar *copy = malloc(strlen(str)+1);and thenstrcpy. Keep in mind to always leave room for the null terminator.
``` { unsigned long long two16, two48 ; two16 = 65536; two48 = two16 * two16 * two16 ; printf("2^48=%llX \n",two48 ); two48 = 1<<48 ; printf("Shifted 1<<48=%llX \n",two48); return 0 ; } ``` When compiled on a 64 bit machine, with a word size of 8, the above gives a warning the two=1<<48 will overflow left shift count >= width of type. The output of the program is: ``` 2^48=1000000000000 Shifted 1<<48=0 ``` What is going on? Why can I not shift a 64bit quantity 48 bits?
why can I not shift a 64bit quantity 48 bits? You arenotshifting a 64-bit integer by 48. You are shifting a 32-bit integer (1) by 48, and assigning the (overflown) result to a 64-bit integer. Try this instead: ``` two48 = 1ULL << 48; ``` or this: ``` two48 = 1; two48 = two48 << 48; ```
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.Closed1 year ago.Improve this question If we have two integers numbers, 5 and 6, for example, we can just do ``` for(int i = 0; i < 5; i++) number += 6; ``` That is the same thing as ``` number = 5*6; ``` But, how does it works for float numbers? I searched in a lot of forums and couldn't find the answer. Does anybody know how C makes two floats be multiplied?
Nowadays, floating-point operations are performed as single instructions in theALU's repertoire, and no software implementation is necessary. Anyway, you can easily imagine that a floating-point multiply is performed by multiplying the mantissas, viewed as integers with proper scaling;add the exponents;combine the signs. Extra housekeeping needs to be done for special numbers, such as zero.
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.Closed1 year ago.This post was edited and submitted for review1 year agoand failed to reopen the post:DuplicateThis question has been answered, is not unique, and doesn’t differentiate itself from another question.Improve this question How we could get three numbers without ordering and then check if they form a Pythagorean triple or not? So,pythagorean(3, 4, 5)orpythagorean(5, 3, 4)will print/return true, whilepythagorean(4, 3, 6)will print/return false.
You can use this algotrithm : ``` #include<stdio.h> int main(){ long long int a, b, c ; scanf("%llu %llu %llu", &a, &b, &c); if (a*a==b*b+c*c || b*b==a*a+c*c || c*c==a*a+b*b) { printf("YES"); } else printf("NO"); return 0; } ```
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.Closed1 year ago.Improve this question If we have two integers numbers, 5 and 6, for example, we can just do ``` for(int i = 0; i < 5; i++) number += 6; ``` That is the same thing as ``` number = 5*6; ``` But, how does it works for float numbers? I searched in a lot of forums and couldn't find the answer. Does anybody know how C makes two floats be multiplied?
Nowadays, floating-point operations are performed as single instructions in theALU's repertoire, and no software implementation is necessary. Anyway, you can easily imagine that a floating-point multiply is performed by multiplying the mantissas, viewed as integers with proper scaling;add the exponents;combine the signs. Extra housekeeping needs to be done for special numbers, such as zero.
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.Closed1 year ago.This post was edited and submitted for review1 year agoand failed to reopen the post:DuplicateThis question has been answered, is not unique, and doesn’t differentiate itself from another question.Improve this question How we could get three numbers without ordering and then check if they form a Pythagorean triple or not? So,pythagorean(3, 4, 5)orpythagorean(5, 3, 4)will print/return true, whilepythagorean(4, 3, 6)will print/return false.
You can use this algotrithm : ``` #include<stdio.h> int main(){ long long int a, b, c ; scanf("%llu %llu %llu", &a, &b, &c); if (a*a==b*b+c*c || b*b==a*a+c*c || c*c==a*a+b*b) { printf("YES"); } else printf("NO"); return 0; } ```
This question already has answers here:Chaining multiple greater than/less than operators(6 answers)if(x==y==z) works, if(x!=y!=z) does not(4 answers)Closed1 year ago. Anyone can enlighten me on why-5<-2<-1returns0in C when I would expect it to return1(True)? ``` printf("%d", -5<-2<-1); ```
This expression ``` -5<-2<-1 ``` is equivalent to ``` ( -5<-2 ) < -1 ``` because the operator < evaluates left to right. As-5is less than-2then the value of the sub-exoression ``` ( -5 < -2 ) ``` is integer value1. So you have ``` 1 < -1 ``` and the result of this expression is 0 that is logical false. From the C Standard (6.5.8 Relational operators) 6 Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to)shall yield 1 if the specified relation is true and 0 if it is false. The result has type int. It seems you mean- 5 < -2 && -2 < -1
I have a function that prints 'Hello' and an integer.I would like to use a callback function that passes the integer into the first functionA. ``` //FUnction Pointers in C/C++ #include<stdio.h> void A(int ree) { printf("Hello %s", ree); } void B(void (*ptr)()) // function pointer as argument { ptr(); } int main() { void (*p)(int) = A(int); B(p(3)); } ``` Desired result would be 'Hello 3'. This doesn't compile.
``` #include<stdio.h> void A(int ree) { printf("Hello %d", ree); // format specifier for int is %d } void B(void (*ptr)(int), int number) // function pointer and the number as argument { ptr(number); //call function pointer with number } int main() { void (*p)(int) = A; // A is the identifer for the function, not A(int) B(p, 3); // call B with the function pointer and the number // B(A, 3); directly would also be possible, no need for the variable p } ```
I know how can I convert decimals to any other kind of bases less than 10 but could we do this without using any arrays or strings in the C language? getnas a input numbergetbas a base that we want to convert to that.print the number inbbase
solve in this way: get n as an input number.get b as a base that we want to convert to that.print the number in b base here is a sum. ``` #include <stdio.h> int main() { long long int n; int b; long long int sum=0; int i=1; scanf("%lld %d",&n,&b); while(n>0) { sum+=(n%b)*i; i*=10; n/=b; } printf("%lld",sum); return 0; } ```
This question already has answers here:How to escape the % (percent) sign in C's printf(13 answers)Closed1 year ago. I was wondering if I could print % in c but when I useprintf("%")It just shows this syntax in output. ``` #include<stdio.h> int main() { printf("%"); } ``` but the result is like this: main.c:13:13: warning: spurious trailing ‘%’ in format [-Wformat=] Does anybody know how I can literally print % as a character in c.
To print a%character you need to follow this structure: ``` int main() { printf("%%"); return 0; } ``` you have to use the character twice.
This question already has answers here:'do...while' vs. 'while'(31 answers)Closed1 year ago. I am new to programming language. Anyone please help me with this. It helps to improve my skills. what is the difference between while and do-while loop in c Thank You,
while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. do-while loop: do while loop is similar to while loop with the only difference that it checks for the condition after executing the statements, and therefore is an example of Exit Control Loop. for more info click here.
I'm working on a C++ program that needs to use the hostname of the computer it is running on. My current method of retrieving this is by mangling a C API like this: ``` char *host = new char[1024]; gethostname(host,1024); auto hostname = std::string(host); delete host; ``` Is there a portable modern C++ method for doing this, without including a large external library (e.g., boost)?
No, there is no standard C++ support for this. You'll either have to make your own function, or get a library that has this functionality.
I've started to learn C and just learned that strings are just arrays of chars. I wanted to see values are in the strings at every given moment so I set a breakpoint in vscode, stepped through the execution, and looked at all the values. ``` int main() { char a[4] = "foo"; char b[4] = "bar"; return 0; } ``` I saw that before initializing thea[]array, there are already values in memory.. My question is, what are those values? Why are they there? What do they represent?
When defining a value, it takes a part of memory that could have contained other numbers. It's basically those numbers being shown in your debug tab.
This question already has answers here:Multiple printf in the For-loop as part of the initialization, condition and update(2 answers)Closed1 year ago. ``` #include <stdio.h> int main(){ for (printf ("3"); printf("2"); printf("1")) break; return 0; } ``` Can anyone explain how this works? Why does it print 32? When I remove brake it's infinite loop and it prints 12?
First,printf ("3")is executed, so it prints3. Thenprintf("2")is executed, print2. Becauseprintf()'s return value is the number of character it prints, which in this case, is1, and because1is a nonzero value, the loop continues in the body. The first statement in the body isbreak, meaning to exit out the loop. So the loop terminates. So the result on the screen is32
I've started to learn C and just learned that strings are just arrays of chars. I wanted to see values are in the strings at every given moment so I set a breakpoint in vscode, stepped through the execution, and looked at all the values. ``` int main() { char a[4] = "foo"; char b[4] = "bar"; return 0; } ``` I saw that before initializing thea[]array, there are already values in memory.. My question is, what are those values? Why are they there? What do they represent?
When defining a value, it takes a part of memory that could have contained other numbers. It's basically those numbers being shown in your debug tab.