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 y...
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 ``` in...
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 Pro...
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 usingpr...
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, &mpista...
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 l...
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...
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 */ ...
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...
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)...
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)...
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 identif...
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; ptrVec...
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)); ...
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 eas...
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...
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 i...
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...
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 i...
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~/.gdbinita...
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:...
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...
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...
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_...
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]; }...
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-precis...
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 representation01000101101010101000001...
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);...
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 obj...
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, bu...
"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: Depend...
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: Depend...
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])...
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 ...
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...
``` 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_C...
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%...
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 sa...
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); ...
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 suggesti...
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/g...
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 co...
``` #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 th...
*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. Ho...
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/g...
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 co...
``` #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 th...
*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. Ho...
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 determine...
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 ...
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 foun...
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; ...
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...
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; ...
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...
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 poi...
``` *(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 yo...
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) == ...
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 raise...
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: Modifyi...
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 anythi...
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 raise...
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: Modifyi...
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 anythi...
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 nothi...
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, be...
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 i...
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 dem...
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 hap...
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 ...
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.re...
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 cou...
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; wh...
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/su...
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 ...
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...
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...
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 he...
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]==...
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 stor...
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...
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 free...
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 ...
``` { 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 w...
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++) num...
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 s...
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 n...
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++) num...
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 s...
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 n...
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 ...
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 ma...
``` #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 functi...
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)...
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 thi...
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 exec...
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 d...
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; } ...
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? Wh...
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 ...
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; } ...
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.