question
stringlengths
25
894
answer
stringlengths
4
863
I want to do basic statistics withVlang. Can I use C libraries? For example, Apophenia:http://apophenia.info/ Or IMSL C stat library:https://docs.roguewave.com/en/imsl/c/8.6/pdf/C_Stat_library.pdf Thanks for your help.
Yes, you cancall C librariesfrom V. You need to make the C library's structs, typedefs and functions known to V by defining them in V first - before calling/using them. For structs you conveniently only need to define the fields you need to use. Here's some examples: via2D game framework wrapping several C libssokolin vlibv-miniaudiowrapper (disclaimer: my own module) Generally you can find a lot of C wrapper code invlibitself. (We're working on replacing C with pure V)
I literally have no idea how to do this for the data types char, float or double. The extent of my knowledge in this is putting a variable next to [10] and that's it. Another question on the worksheet: For the declaration float data[12]; with the compiler assigning a starting address of 0005 in decimal. What would be the address of the last byte?
sizeof arrayNamewill return the size of the entire array.sizeof arrayName[0]will return the size of a single element of the array. You can use any index in the second expression, it doesn't have to be a valid element of the array. The size is determined at compile time from the type, the contents are not relevant. Note that you can only get the size of the array using an actual array variable,nota pointer.
The problem is that if x=2, y=2, z=4, I see 2<2<4 on console.Why?It is wrong actually.Why I see 2<2<4? ``` int main(void) { int x, y, z; printf("Please enter 3 numbers: \n"); scanf("%d%d%d", &x, &y, &z); int max=x; if (y > max) max = y; if (z > max) max = z; if (max == z) if (x < y) printf("%d < %d < %d\n", x, y, z); else printf("%d < %d < %d\n", y, x, z); ```
You are testing forx < y, the negation of that isy <= xand noty < x, so your print statement is giving the wrong text.
I'm trying to send binary data to the client, what I'm trying to do is:write(client_fd,"0xf",size,flag). I don't know how to make the string binary and not sure what type of flag should I use.
A string literal "0xf" is similar to ``` char str[] = { '0', 'x', 'f', '\0' }; ``` If you want to write actual 0x0 and 0xf data, hex values can be expressed within a string literal, each with a leading\xlike this: ``` size = 2; nwritten = write(sock_fd, "\x0\xf", size); ```
Question 3 onCareer Ridesuggests that*(x+i)is the same as&x[i]. Can someone please explain whether this is correct?
That answer is incorrect. Given a pointer variablexand an integer variablei,*(x + i)is the same asx[i]andx + iis the same as&x[i]. It looks like they took half from each side of that for their answer, but they didn't provide any explanation, so we'll never know.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed3 years ago.Improve this question This is what I code for program which do case conversion of string : https://i.stack.imgur.com/uXp9w.png I'm confused why I can't use Logical OR (||) operator instead of Logical AND(&&)operator in lineif(str[i]>='a'&& str[i]<='z')
There are other possible characters after'z'and below'a'(ascii table), so it's necessary to do both upper and lower bounds checks with&&. If you used the||operator then the statement could execute if the character wereanyvalue, because ALL characters are greater than'a'or less than'z'.
Can anyone explain why I get a memory leak (+1.55 kB) with code below and what am I supposed to do to avoid it ? ``` void TestGuid() { UUID id; ZeroMemory(&id, sizeof(UUID)); UuidCreate(&id); } int _tmain(int argc, _TCHAR* argv[]) { TestGuid(); // Memory Snapshot 1 here return 0; // Memory Snapshot 2 here } ```
The very first call ofUuidCreatemakes some allocations. The first snapshot shows what was allocated, it seems it's related to initialization of random numbers generator: But if you callUuidCreateonce again, no new allocations are made. The second screenshot shows that no leaks found. So formally there are leaks but you can't fix it, and it's not a big deal - very few memory allocated.
When I try to compile my code, I am getting a c statement with no effect warning: I am trying to use the bitwise operation to shift a value to the left. This is the code I am trying to do: ``` *bits << 5 ``` bits is a unsigned pointer.
You are calculating a value, but not assigning it to anything. You probably want to do this instead: ``` *bits <<= 5; // or equivalent *bits = *bits << 5; ```
Below archive file(shuffler.a) is created with below command: ``` $ go install github.com/myhub/cs61a $ $ $ file pkg/linux_amd64/github.com/myhub/cs61a/shuffler.a pkg/linux_amd64/github.com/myhub/cs61a/shuffler.a: current ar archive $ $ ``` But there is more than one than file(relocatable) integrated in archive file: ``` $ ar -t pkg/linux_amd64/github.com/myhub/cs61a/shuffler.a __.PKGDEF _go_.o $ $ ``` _go_.ois a relocatable binary form ofsrc/github.com/myhub/cs61a/shuffler/shuffle.gosource code What does__.PKGDEFsignify?ar –rcs libourown.c one.o two.oin C world does not add this file
Since go code is organized by package, while C code is not, and since go libraries/binaries are compiled package by package, I would take the wild guess that PKGDEF has information about the go language package from which the code was compiled.
I'm trying to convert a tm struct to a string using strftime() in a Kinetis KL25Z using codewarrior ide. When calling strftime i get an error saying "undefined reference to 'strftime'". Test code used below: ``` #include "derivative.h" /* include peripheral declarations */ #include <stdlib.h> #include <stdio.h> #include <time.h> struct tm dateinfo; struct tm *dateinfoPointer=&dateinfo; int main(void) { int counter = 0; char buffer[8]; strftime(buffer,sizeof(buffer),"%H:%M:%S",dateinfoPointer); for(;;) { counter++; } return 0; } ``` What I'm missing?
I would be surprised if this function is implemented for your Cortex M0 uC. Usuallytime.hfunctions are not implemented or the functions are on;y the stubs. Programming such a small micros you need to forget your Windows/Linux programming habits. So how to deal with time? Write it yourself :)
Question 3 onCareer Ridesuggests that*(x+i)is the same as&x[i]. Can someone please explain whether this is correct?
That answer is incorrect. Given a pointer variablexand an integer variablei,*(x + i)is the same asx[i]andx + iis the same as&x[i]. It looks like they took half from each side of that for their answer, but they didn't provide any explanation, so we'll never know.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed3 years ago.Improve this question This is what I code for program which do case conversion of string : https://i.stack.imgur.com/uXp9w.png I'm confused why I can't use Logical OR (||) operator instead of Logical AND(&&)operator in lineif(str[i]>='a'&& str[i]<='z')
There are other possible characters after'z'and below'a'(ascii table), so it's necessary to do both upper and lower bounds checks with&&. If you used the||operator then the statement could execute if the character wereanyvalue, because ALL characters are greater than'a'or less than'z'.
Can anyone explain why I get a memory leak (+1.55 kB) with code below and what am I supposed to do to avoid it ? ``` void TestGuid() { UUID id; ZeroMemory(&id, sizeof(UUID)); UuidCreate(&id); } int _tmain(int argc, _TCHAR* argv[]) { TestGuid(); // Memory Snapshot 1 here return 0; // Memory Snapshot 2 here } ```
The very first call ofUuidCreatemakes some allocations. The first snapshot shows what was allocated, it seems it's related to initialization of random numbers generator: But if you callUuidCreateonce again, no new allocations are made. The second screenshot shows that no leaks found. So formally there are leaks but you can't fix it, and it's not a big deal - very few memory allocated.
When I try to compile my code, I am getting a c statement with no effect warning: I am trying to use the bitwise operation to shift a value to the left. This is the code I am trying to do: ``` *bits << 5 ``` bits is a unsigned pointer.
You are calculating a value, but not assigning it to anything. You probably want to do this instead: ``` *bits <<= 5; // or equivalent *bits = *bits << 5; ```
Below archive file(shuffler.a) is created with below command: ``` $ go install github.com/myhub/cs61a $ $ $ file pkg/linux_amd64/github.com/myhub/cs61a/shuffler.a pkg/linux_amd64/github.com/myhub/cs61a/shuffler.a: current ar archive $ $ ``` But there is more than one than file(relocatable) integrated in archive file: ``` $ ar -t pkg/linux_amd64/github.com/myhub/cs61a/shuffler.a __.PKGDEF _go_.o $ $ ``` _go_.ois a relocatable binary form ofsrc/github.com/myhub/cs61a/shuffler/shuffle.gosource code What does__.PKGDEFsignify?ar –rcs libourown.c one.o two.oin C world does not add this file
Since go code is organized by package, while C code is not, and since go libraries/binaries are compiled package by package, I would take the wild guess that PKGDEF has information about the go language package from which the code was compiled.
I'm trying to convert a tm struct to a string using strftime() in a Kinetis KL25Z using codewarrior ide. When calling strftime i get an error saying "undefined reference to 'strftime'". Test code used below: ``` #include "derivative.h" /* include peripheral declarations */ #include <stdlib.h> #include <stdio.h> #include <time.h> struct tm dateinfo; struct tm *dateinfoPointer=&dateinfo; int main(void) { int counter = 0; char buffer[8]; strftime(buffer,sizeof(buffer),"%H:%M:%S",dateinfoPointer); for(;;) { counter++; } return 0; } ``` What I'm missing?
I would be surprised if this function is implemented for your Cortex M0 uC. Usuallytime.hfunctions are not implemented or the functions are on;y the stubs. Programming such a small micros you need to forget your Windows/Linux programming habits. So how to deal with time? Write it yourself :)
``` #include <string.h> #include <stdio.h> int main() { char str[255] = "Hello;thisnewwolrd"; int i =0; while(str[i] != ';') { i++; } i++; char *name = NULL; while(str[i] != NULL) { name[i] = str[i]; i++; printf("%c \r\n",name[i]); } } ``` the expected output isthisnewwolrdbut i am getting error of core dumped canany one have reason why and how to over come this
This should work: ``` int main() { char str[255] = "Hello;thisnewwolrd"; char *ptr = strchr(str, ';') + 1; char name[255]; strcpy( name, ptr); printf("%s \r\n", name); } ``` You don't have to reinvent the wheel, and are much better off using standard library functions for string manipulation.
I need to take an argument (argv[2]) and convert it to uint16_t type. How I can get this? I put a PORT in argument so I need to convert in uint16_t, I tried this: ``` uint16_t PORT; PORT = argv[2]; ``` but when I do ``` servaddr.sin_port = htons(PORT) ``` I get ``` warning: assignment makes integer from pointer without a cast ```
You can convert achar *to anint(and therefore, to auint16_t) via theatoi()function: ``` #include <stdlib.h> [...] uint16_t PORT = atoi(argv[2]); ```
c code : ``` int main(void) { int i = 0, j = 0; double avg = 0; int *pi, *pj; double *pavg; ``` .. ``` pi = &i; pj = &j; pavg = &avg; ``` .. ``` *pi = 5; *pj = 10; *pavg = (*pi + *pj) / 2; ``` here where it prints : ``` printf("%lf\n\n", avg); ``` it prints7.000000000 ``` return 0; } ```
When you do(*pi + *pj) / 2, you are doing integer arithmetic. The numbers after the decimal have already been discarded before you assign to thedoublevariable. One way is to do(*pi + *pj) / 2.0. One of the operands of the expression being a double, the otherints will be promoted todoubles before the expression is evaluated. Another option is totypecastone of the variables to a double((double)*pi + *pj) / 2. Here, the de-referencing operator being of higher precedence will be evaluated before the typecast.
For example: Code snippet 1: ``` int func() { int x=5; return x; } ``` This function wouldn't produce a runtime error. Code snippet 2: ``` char* func() { char str1[]="HELLO"; return str1; } ``` This would produce a runtime error -"Address of local variable is being returned".
``` int func() { int x=5; return x; } ``` Function returns an int, thevalueof x is being returned. ``` char* func() { char str1[]="HELLO"; return str1; } ``` Function returnschar*, theaddressofstr1is being returned. The storage duration of a local variable is limited to it's scope. Oncefunc()returns, that address ofstr1is not valid hereafter. Shall you dereference that returned pointer, you will trigger undefined behavior.
I came across the code and it was kind of strange to me I am unable to understand what it means. ``` typedef struct alpha *Abc; ``` this is where Abc is defined; ``` struct alpha{ Abc s;//what does this mean } ``` also some where in function it is used like this ``` Abc iAmFunc(Abc beta,int a){ some thing is performed return variable of type Abc } ``` I dont understand the purpose of doing this can anyone explain me!!
The typedef defines a pointer type tostruct alphawith type nameAbc. Because of this,Abc s;translates tostruct alpha *s;
when I try to call the function as flip(flip(num,no),no). I am getting an answer of flip(num, no) and I can't find the solution of this code. ``` #include <stdio.h> #include <math.h> int flip(int number, int n); main() { int num = 12345; int no = 3; int result = flip(flip(num,no), no); printf("%d", result); } int flip(int number, int n) { int x = number % 10; int s = n + x * pow(10, n - 1); int temp = n * pow(10, n - 1) + x; int sum = number + s - temp; int* ptr = &sum; return *ptr; } ``` Required Answer = 12345;Output = 12543;
With loop, you can handle digit by digit: ``` int flip(int number, int n) { int rev = 0; for (int i = 0; i != n; ++i) { rev *= 10; rev += number % 10; number /= 10; } for (int i = 0; i != n; ++i) { number *= 10; } return number + rev; } ``` Demo
A void function does not return any value as output and can take input values. The function below seems a void function, but there is the operator *, why? ``` void *function(){ printf("hello") } ```
That is not avoidfunction. That is a function that returns avoid*(pointer). But it seems incomplete, because theprintf()has no semicolon;and the function does not actually return avoid*.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed3 years ago.Improve this question Where can I find the official manuals of the Linux libraries for C? For instance the manual of the pthread library? I found onlythis big file.
on the terminal type: ``` man function_name ``` For example: ``` man pthread_create ``` For showing all functions of pthread library: ``` man pthreads ``` For seeing the options of man command line type: ``` man man ```
when I try to call the function as flip(flip(num,no),no). I am getting an answer of flip(num, no) and I can't find the solution of this code. ``` #include <stdio.h> #include <math.h> int flip(int number, int n); main() { int num = 12345; int no = 3; int result = flip(flip(num,no), no); printf("%d", result); } int flip(int number, int n) { int x = number % 10; int s = n + x * pow(10, n - 1); int temp = n * pow(10, n - 1) + x; int sum = number + s - temp; int* ptr = &sum; return *ptr; } ``` Required Answer = 12345;Output = 12543;
With loop, you can handle digit by digit: ``` int flip(int number, int n) { int rev = 0; for (int i = 0; i != n; ++i) { rev *= 10; rev += number % 10; number /= 10; } for (int i = 0; i != n; ++i) { number *= 10; } return number + rev; } ``` Demo
A void function does not return any value as output and can take input values. The function below seems a void function, but there is the operator *, why? ``` void *function(){ printf("hello") } ```
That is not avoidfunction. That is a function that returns avoid*(pointer). But it seems incomplete, because theprintf()has no semicolon;and the function does not actually return avoid*.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed3 years ago.Improve this question Where can I find the official manuals of the Linux libraries for C? For instance the manual of the pthread library? I found onlythis big file.
on the terminal type: ``` man function_name ``` For example: ``` man pthread_create ``` For showing all functions of pthread library: ``` man pthreads ``` For seeing the options of man command line type: ``` man man ```
I am currently working on a simulation using OpenMP. Whenever I try to execute with --trace to get the trace of the execution I get the following error ``` src/trace_graphics.c:5:10: fatal error: fut.h: No such file or directory 5 | #include <fut.h> ``` I redownloaded easypap but the file doesn't seem to come with it.
I friend of mine found the solution so I'm posting it ``` sudo apt-get install libfxt-dev ``` This will do the trick
I have quite an unusual problem, that is probably just bad code from a newbie C-learner. I am struggling with the following piece of code. ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv) { float a = 1587128832.000000; int d = 1587128898.000000; float f = a + d ; printf("%f\n", f); return 0; } ``` The following code outputs3174257664.000000while googlesays that the result should be 3174257730. I am trying to add afloat/doublewith anintand it is giving me a strange result. So what the heck am I doing wrong? I don't think that the error is in fact a problem with mixed datatypes, as C should convertints tofloats.
float is not capable of holding exactly such numbers. viz.https://www.h-schmidt.net/FloatConverter/IEEE754.html if you want exact result, you need more memory -> usedouble.
Say I do this: const char *myvar = NULL; Then later *myval = “hello”; And then again: *myval = “world”; I’d like to understand what happens to the memory where “hello” was stored? I understand it is in the read only stack space, but does that memory space stays there forever while running and no other process can use that memory space? Thanks
Assuming you meant ``` myval = "world"; ``` instead, then I’d like to understand what happens to the memory where “hello” was stored? Nothing. You just modify the pointer itself to point to some other string literal. And string literals in C programs are static fixed (non-modifiable) arrays of characters, with a life-time of the full programs. The assignment really makes the pointer point to the first element of such an array.
I am keen on someone else's code and want to understand what is happening here. What is stored in this structure? Is this some kind of pattern in C? ``` typedef struct _P_NEXT P_NEXT; struct _P_NEXT {P_NEXT *p_el;}; ```
The structure contains a pointer, not the structure itself. Pointer is essentially an address in memory. The pointer type (P_NEXT, in this case) just tell what is the interpretation of the memory block should be. This struct looks like a list: a node which points to the next node in list (I guess there is an extra "data" attribute)
Say I do this: const char *myvar = NULL; Then later *myval = “hello”; And then again: *myval = “world”; I’d like to understand what happens to the memory where “hello” was stored? I understand it is in the read only stack space, but does that memory space stays there forever while running and no other process can use that memory space? Thanks
Assuming you meant ``` myval = "world"; ``` instead, then I’d like to understand what happens to the memory where “hello” was stored? Nothing. You just modify the pointer itself to point to some other string literal. And string literals in C programs are static fixed (non-modifiable) arrays of characters, with a life-time of the full programs. The assignment really makes the pointer point to the first element of such an array.
I am keen on someone else's code and want to understand what is happening here. What is stored in this structure? Is this some kind of pattern in C? ``` typedef struct _P_NEXT P_NEXT; struct _P_NEXT {P_NEXT *p_el;}; ```
The structure contains a pointer, not the structure itself. Pointer is essentially an address in memory. The pointer type (P_NEXT, in this case) just tell what is the interpretation of the memory block should be. This struct looks like a list: a node which points to the next node in list (I guess there is an extra "data" attribute)
``` (a > b) ? c = 10 : (a < b) ? c = 20 : c = 30; ``` why this code make a error that called "expression is not acceptable" ?? Error messages said "c = 30" this part made the error.
Because ternary operator?:has precedence over=, the expression is parsed as: ``` ((a > b) ? c = 10 : (a < b) ? c = 20 : c) = 30; ``` Because you can't "assign" to(a > b) ? c = 10 : (a < b) ? c = 20 : c, your compiler errors. You want: ``` (a > b) ? c = 10 : (a < b) ? c = 20 : (c = 30); ``` But it's really better to write: ``` c = (a > b) ? 10 : (a < b) ? 20 : 30; ```
I would expect this code to print 0 1 2 3 4 5 6 7 8 9 but it only prints the first two elements of the array: 0 1 I realize I could just change the condition in my for loop to i < 10 to get the desired output, but I want to understand how/whether I can use the value of an element of the array to set the condition. Thank you! code: ``` #include <stdio.h> int main() { int array[10]; for(int i = 0; array[i] < 10; i++) { array[i] = i; printf("%d ", array[i]); } } ```
What you really want for yourforloop is ``` for(int i = 0; i < 10; i++) ``` The way you've got it now, you're checking the value ofarray[i]before it is given a value, meaning its value is whatever junk memory was on the stack when your function began.
So let's say: ``` int n = 50; int *p = &n; ``` Why do we use*and not&in C? What's the key difference between*and&?
Using*to declare pointers is mostly a matter of convention, but there is a reason of consistency: the*in the declarationint *pmeansintis the type of*p. It might seem more consistent to writeint &p = &naspis initialized to the address ofnbut this convention would not hold for double pointers:int **ppdefinesppas a pointer to a pointer to anint, yetppcannot be initialized with&(&n). Note thatint& p = n;is a valid definition in C++ for a reference to anint, which is a pointer in disguise. Modifyingpwould then modifyn. References are implemented as pointers without the indirection notation.
Is there any way to detect if a tree view control (and specifically a TVITEM) is double clicked using Common Controls & WINAPI? I mean in my wndproc function of a form. If so, what are the msg, wParam & lParam in that case?
A treeview control sends anNM_DBLCLKnotification when you double-click it, withuMsg=WM_NOTIFYandlParampointing to anNMHDRstructure as per the documentation. You can then send the treeview control aTVM_HITTESTmessage to determine the item under the cursor, something like: ``` TVHITTESTINFO tvhti = {}; GetCursorPos (&tvhti.pt); ScreenToClient (hTreeView, &tvhti.pt); SendMessage (hTreeView, TVM_HITTEST, 0, (LPARAM) &tvhti); ``` See thedocumentationfor the values returned byTVM_HITTEST.
my code (in the C language) is this: ``` avg = round((r + g + b) / 3); r = avg; g = avg; b = avg; ``` It should do the grayscale image effect. There are no syntax errors, but apparently avg, when calculated as shown above with valuesras 27, and bothgandbas 28, avg finds it to be 27. I know it is 27.66666... and when rounded that is 28. if you can either-or/both explain to me why this happens withround(), and/or give me a solution, it is really appreciated.
Assuming thatr,g, andbhave integer types, the expression(r + g + b) / 3performs integer division because all operands have integer type. This means that any fractional part of the division gets truncated. Change the expression to this: ``` (r + g + b) / 3.0 ``` The constant3.0has typedouble, so this will perform floating point division. Then rounding the result of this expression will give you the desired result.
These are example of incrementing each element of an array by 10. ``` for (i = 0; i< 100; i++){ arr[i] += 10; } ``` or ``` for (i = 0; i< 100; i+=2){ arr[i] += 10; arr[i+1] += 10; } ``` which is the efficient way to solve this problem out of these these two in C language?
Don't worry about it. Your compiler will make this optimization if necessary. For example,clang 10 unrolls this completely and uses vector instructions to do multiple at once.
The example: ``` ++structure.field; ``` incrementsfieldinstead of giving "wrong type argument to increment" compiler error, although ++ and . operators are equaly hierarchized ergo: should've been executed from left to right. Am I missing something here?
Prefix and postfix++have different precedence..has the higher precedence than theprefixincrement operator, as seen oncppreference.com. .andpostfixincrement have the same precedence. If you wrotestructure.field++then they'd have the same precedence and associativity would kick in to resolve the ambiguity as(structure.field)++rather thanstructure.(field++).
Isn'tiinscanfand insumuseless? It doesn't change anything, even when I print&ptrit doesn't show me any difference in memory values. ``` #include <stdio.h> #include <stdlib.h> int main() { int n, *ptr, sum = 0; printf("Enter number of elements: "); scanf("%d", &n); ptr = (int *)malloc(n * sizeof(int)); // if memory cannot be allocated if (ptr == NULL) { printf("Error! memory not allocated."); exit(0); } printf("Enter elements: "); for (int i = 0; i < n; ++i) { scanf("%d", ptr + i); sum = sum + *(ptr + i); } printf("Sum = %d", sum); // deallocating the memory free(ptr); return 0; } ```
The 'i' isn't supposed to change the pointer. It is used to access the i'th element of the array that PTR points to. Without the I it would scan for the same element in this array, the first element
I have a data type ofdouble, I want toprintfthe double in the following form: Ifdouble x=2orx=2.0print2to the screen, which means if I get an integer I print an integer.Ifdouble x=2.3orx=2.30or any other non-whole number I print2.3to the screen. Is there any way to do it shortly? or do I need to use if statements or something like that? ``` double x = 2; printf("%d", x); double x = 2.3; printf("%.1f", x); ``` This is an illustration only. I want toprintfan integer or a double based on the value I get.
IfOP wants one decimal place after the.when the value of not a whole number: Use".*"andtrunc()to control number of precision digits. trunc()returns thedoublewith the fractional part truncated. ``` double f = 2.3; printf("%.*f\n", f != trunc(f), f); // 1 digit f = 2.0; printf("%.*f\n", f != trunc(f), f); // 0 digits, no . ``` Output ``` 2.3 2 ```
I don't know what is causing this error, I try dividing 2/12 using double but it gives me a completely wrong number. ``` #include <stdio.h> #include <stdlib.h> int main() { double a; a = 2/12; printf("\n a = %lf \n", a); return 0; } ``` This returns -272632568 and makes no sense. Thanks for your help.
First of all, you should consider the declaration: ``` double a = 2 / 12; // (integer) ``` It'll just give you zero and then assign to double since they're integers. If you use rather: ``` double a = 2.0 / 12.0; // explicitly defining ``` Then you'll get right precision output by using this statement: ``` printf("\n a = %f\n", a); ``` Or, ``` printf("\n a = %lf\n", a); ```
``` size_t my_strspn(const char *string, const char *chars) { size_t n; const char *p; for (n = 0; *string; string++, n++) { for (p = chars; *p && *p != *string; p++); if (!*p) break; } return n; } ``` Is there a simple way to remove "break"? I tried to modify for loops, but they make one extra iteration more that needed.
I'm too new to this forum to add a comment and I'm too busy (i.e. lazy) to test this, so... What about adding the *p check in the first for loop?: ``` for (n = 0; *string && *p; string++, n++) ```
The C standard provides two functions,putsandfputs, withputs(s)behaving asfputs(s, stdout)except that it additionally appends a newline: Theputs()function shall write the string pointed to bys, followed by a<newline>, to the standard output streamstdout. What is the rationale for this difference in behavior betweenputsandfputs?
Theputsfunction specifically writes tostdoutwhich is commonly a console. Because console output is typically line bufered, it's convenient to not have to explicitly add a newline to a string to print. Thefputsfunction can write to any givenFILEobject, not juststdout, so by not automatically adding a newline it makes the function more flexible in the general case.
Is there a more concise way to write the second line of this function without repeatingareduntantly? ``` void myfunc() { bool a = false; // Assume that this won't alway be hardcoded to false. a = !a; } ```
Is there a more concise way to write the second line of this function without repeating a reduntantly? !is an unary operator, you cannot associate it with=if this is what you expected. But you can do something likea ^= true;, this is not amore concise waybut this iswithout repeating a redundantly. Anyway this is not a good way to do contrarily toa = !a;which is much more readable
I checked on the net it shows size of long to be 4 bytes . But when I print sizeof(long) in my laptop it prints 8 . Why is there a conflict in the values ? I am using this print statement ``` printf("%zu",sizeof(long)); ```
The "conflict" you mean to see comes from the standard, which does not specify specific widths of the integer types. Different compilers use different widths. But therealquestion you have is: "What should I do?" The answer is to use the types provided by the standard for such purpose. Include "stdint.h" and useint32_t(oruint32_tfor unsigned integers) for 4-byte integers. Please get yourself a standard, and take the time to look in it. You don't need to read every line, though, just enough to know what to expect therein.
``` #include<stdio.h> int areaOfRectangle(int,int); int perimeter(int,int); int main() { int l,b; scanf(" %d %d",&l,&b); printf("%d %d %d %d",l,b,areaOfRectangle(l,b),perimeter(l,b)); return 0; } int areaOfRectangle(int a,int b) { int area; area=a*b; return area; } int perimeter(int c,int d) { int meter; meter=2(c+d); return meter; } ``` why this error:called object is not a function or function pointerat line:meter=2(c+d)? Also, can I use the same variablea,bto pass in perimeter function?
Your codemeter=2(c+d);should be changes asmeter=2*(c+d);You can use the same variable a,b to pass in perimeter function, A parameter is just a local variable.
I send messages usingZMQ_PUSHsocket withZMQ_DONTWAITflag. Each message separated by 300ms (so I seriously doubt, that my thread scheduling is so off). However from time to time several (up to 7 so far) messages are packed to the same TCP frame yet I don't see any retransmissions or reconnections in tcpdump. Why is it happening? And how can I determine when my message would be sent?
Q:"And how can I determine when my message would be sent?" You have zero-chance to know when a message, dispatched to be sent, would finally get down to the wire-level. This is a property of the concept, not a bug. It was explicitly explained in the documentation, since the API v2.0+ ( and will most probably remain so forever ). It is fair to add that some insight into thezmq_context-instance's internalities might be derived from asocket_monitoravailable in the more recent API versions.
Usingsignal()or, preferably,sigaction(), we can choose to ignore or explicitly handle most of thePOSIX signals. For example, in order to ignoreSIGCHLDwe could do the following: ``` struct sigaction sa_chld = { .sa_handler = SIG_IGN }; sigaction(SIGCHLD, &sa_chld, NULL); ``` Is there also a way to figure out if a given signal is being ignored and/or caught by the program? Ideally, I'd like to distinguish if a signal... is being handled as per thedefault actionsis being ignored explicitlyis being caught explicitly
For a running process, you can check out/proc/PID/statusand check the fieldsSigBlk,SigIgn, andSigCgtfor blocked, ignored, and caught signals respectively. Someone wrote autility scripthandy to "decode" it which I personally find very useful and been using it. Seeprocdocumentation for details and more relevant fields.
How is the second scanf working in the below code ``` #include <stdio.h> #include <string.h> #include <unistd.h> int main() { char buf[256]; int i; write(1, "Hello World\n", strlen("Hello World\n")); dup(0); close(0); scanf("%s", buf); printf("Buffer:%s\n", buf); dup(3); scanf("%s", buf); printf("Buffer:%s\n", buf); return 0; } ``` We are closing the stdin (fd:0), Then how does dup(3) have the effect of reopening the stdin?
I think when you check the return value of these two call of dup, you will find the first is 3, and the second is 0. So before the second scanf function is called, file descriptor 0 is related with terminal again.
Ok so I have a function to print a queue. I use a temp Node to iterate through the linked list. When I try to free the temporary node, it also frees the rear of my queue (the last node inside the queue) ``` struct QNode *temp = q->front; printf("Queue: %d", temp->value); while (temp->next != NULL) { temp = temp->next; printf(" -> %d", temp->value); } printf("\n"); free(temp); ``` I have a very long algorithm and If i dont free the temp I will have hundreds of thousands of trash memory. And I cant afford it
The rule is onefreepermalloc, since you are not allocating space for your temporary node (is just a pointer to the front), you dont have to callfree, just ignore it.
``` #include <stdio.h> int main(int argc, char **argv){ int c; char str[10]; while ((c=getchar()) != '\n') { scanf("%s",str); } printf("%s\n", str); } ``` If the input is "Data", the output is "ata" where the "D" is missing. Can't figure out why. Any explanation?
In your program, ``` while ((c=getchar()) != '\n') { scanf("%s",str); } ``` thegetcharwill absorb the first character, then thescanfwill take all but the last'\n', which will end the while loop. Thusstrmisses the first char. Change to ``` do { scanf("%s",str); } while ((c=getchar()) != '\n'); ``` to get the whole string. Or simply remove the loop andgetchar()...
I have the following big endian in C: ``` int32_t num = 0x01234567; ``` I'd like to convert it to mid little endian like this :0x45670123 How do I use the bitwise operator to do that in C.
A very simple approach would be: Read a byte fromnumwith the AND operator.Shift the read byte to the position you want in the output number.OR the shifted byte with your output number.Repeat until done. Example: ``` uint32_t num = 0x01234567; uint32_t output = 0; uint32_t firstByte = num & 0xff000000; // firstByte is now 0x01000000 // Where do we want to have 0x01 in the output number? // 0x45670123 // ^^ here // Where is 0x01 currently? // 0x01000000 // ^^ here // So to go from 0x01000000 to 0x00000100 we need to right shift the byte by 16 (4 positions * 4 bits) uint32_t adjByte = firstByte >> 16; // adjByte is now 0x0100 // OR with output output |= adjByte; ``` AND, Shift & OR operator on wikipedia.
I try to make pgbouncer in windows They haveusuallibrary (libusual) for work with ip-sokets. When pgbouncer tune socket, it callssocket_setupfrom usual library socket_setupcallres = fcntl(sock, F_SETFD, FD_CLOEXEC);andresis -1 now. How can I fix one? My build system is mingw64 from msys.
Just for someone who find this page. Problem occurred because theusuallibrary in some (not in all) places useintinsteadSOCKETwhich isint*and has a size more than size ofinton a 64-bit platform.
If I had a for loop that looks like this: ``` for (i = 0; i < size; i++){ printf("you entered %d", number); //store number in int arr[][] } ``` Would the resulting arr need to be initialized in that for loop? Or can I access arr after the for loop finishes?
To access the array outside of the loop, define it outside the loop: ``` int arr[size][size]; // or whatever number you want to use here for (i = 0; i < size; i++){ printf("you entered %d", number); //store number in int arr[][] } // access values of arr here ``` You don't need toinitializethe array outside of the loop (fill it with some values) if you're just planning on overwriting those values with the values produced in the array.
This question already has answers here:Single quotes vs. double quotes in C or C++(15 answers)Closed3 years ago. Why does this generate errors? ``` char variable = "\n"; printf ("%c",variable); ``` But changing the double quotes to single fixes it? ``` char variable = '\n'; printf ("%c",variable); ```
Because"\n"is an array of chars. Specifically achar[2]array, as it is the same as{'\n',0}. And you cannot assign achar[2]to achar. Even without the null termination you would still not be able to assign it because of the type mismatch. Nochar[N](for a fixedN) can be assigned to achar.
I want to allocate memory for a string using calloc, I know that calloc fills the whole allocated memory with 0, but I also found out that they are different from \0 in some contexts. This whole discussion it's kind of confusing for a newbie (like myself), so I was wondering if anyone could give me the final answer, if I use alloc to initialize a string do I have to manually set the last character to "\0" or not?
There is no difference between integral value0, with whichcallocfills up the allocated memory, and literal character'\0', which is identical to integral value0. So if you write up ton-1characters to a memory block ofncharacters allocated withcalloc, you will always have a valid 0-terminated string.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed3 years ago.Improve this question I am trying to call to function ``` int function(int argc, const char *argv[]) {} ``` from my main function with: ``` function(int argc, const char *argv[]); ``` But I am geting errors saying I needed an expression before int.
The small program below maybe helps you: ``` #include <stdio.h> int function(int argc, const char *argv[]) { printf("argc = %d\n", argc); for (int i = 0; i < argc; i++) { printf("argv[%d] = %s\n", i, argv[i]); } return 0; } int main(int argc, const char *argv[]) { function(argc, argv); return 0; } ``` The output of test: ``` ./test argv1 argv2 argc = 3 argv[0] = ./test argv[1] = argv1 argv[2] = argv2 ```
The functionRtlInitUnicodeString()used to initialize theUNICODE_STRINGstructure cannot be used as a linker error stating that anunresolved external symbol RtlInitUnicodeString referenced in function ***func_name*** (LNK2019)is thrown during compilation. I tried using the statement#pragma comment(lib, "NtosKrnl.lib")to solve the issue at hand (as I assumed that linking the library mentionedherewould resolve it) but a linker error stating the messagecannot open file 'ntoskrnl.lib' (LNK1104)is thrown. Thanks in advance.
The function cannot be called directly as they belong to the internal API and their mere prototype header is exposed via thewinternl.hheader file (at least in this case). In order to use the functions that are part of the internal API, one can either use run-time dynamic linking to link theNtdll.dlllibrary as statedhereor link the library filentdll.lib, which is a provided as a part of theWDK.
I am trying to write code that copy and print the word in text file on the screen with getline() and strchr() functions. so this is my code: ``` void read_teams(char* text) { FILE *fp=fopen(text,"r"); char* tname=NULL; size_t tname_size=0; while(getline(&tname,&tname_size,fp)!=EOF) { tname[strchr(tname,'\n')-tname]='\0'; printf("%s\n",tname); } fclose(fp); } ``` when it is read strchr function it's show: ``` Segmentation fault (core dumped) ``` so why? i have to use this function with getline ,so don't tell me to write my code in other way please.
If the buffer does not contain a\ncharacter, thenstrchr()-tnamewill be way beforetname. That will cause a seg fault. So use: ``` while(getline(&tname,&tname_size,fp)!=EOF) { char *p= strchr(tname,'\n'); if (p) tname[p-tname]='\0'; printf("%s\n",tname); } ```
I am trying to preserve a variable so I can see its value while debugging optimized code. Why is the following an illegal constant expression? ``` void foo(uint_32 x) { static uint_32 y = x; ... } ```
For your purpose you probably want this: ``` void foo(uint_32 x) { static uint_32 y; y = x; ... } ``` What you tried to do is an initialisation. What is done above is an assignment. Maybe for your purpose this would be even more interesting: ``` static uint_32 y; void foo(uint_32 x) { y = x; ... } ``` Now the variableycan easily be accessed by the debugger once thefoofunction is finished.
I want to allocate memory for a string using calloc, I know that calloc fills the whole allocated memory with 0, but I also found out that they are different from \0 in some contexts. This whole discussion it's kind of confusing for a newbie (like myself), so I was wondering if anyone could give me the final answer, if I use alloc to initialize a string do I have to manually set the last character to "\0" or not?
There is no difference between integral value0, with whichcallocfills up the allocated memory, and literal character'\0', which is identical to integral value0. So if you write up ton-1characters to a memory block ofncharacters allocated withcalloc, you will always have a valid 0-terminated string.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed3 years ago.Improve this question I am trying to call to function ``` int function(int argc, const char *argv[]) {} ``` from my main function with: ``` function(int argc, const char *argv[]); ``` But I am geting errors saying I needed an expression before int.
The small program below maybe helps you: ``` #include <stdio.h> int function(int argc, const char *argv[]) { printf("argc = %d\n", argc); for (int i = 0; i < argc; i++) { printf("argv[%d] = %s\n", i, argv[i]); } return 0; } int main(int argc, const char *argv[]) { function(argc, argv); return 0; } ``` The output of test: ``` ./test argv1 argv2 argc = 3 argv[0] = ./test argv[1] = argv1 argv[2] = argv2 ```
The functionRtlInitUnicodeString()used to initialize theUNICODE_STRINGstructure cannot be used as a linker error stating that anunresolved external symbol RtlInitUnicodeString referenced in function ***func_name*** (LNK2019)is thrown during compilation. I tried using the statement#pragma comment(lib, "NtosKrnl.lib")to solve the issue at hand (as I assumed that linking the library mentionedherewould resolve it) but a linker error stating the messagecannot open file 'ntoskrnl.lib' (LNK1104)is thrown. Thanks in advance.
The function cannot be called directly as they belong to the internal API and their mere prototype header is exposed via thewinternl.hheader file (at least in this case). In order to use the functions that are part of the internal API, one can either use run-time dynamic linking to link theNtdll.dlllibrary as statedhereor link the library filentdll.lib, which is a provided as a part of theWDK.
I am trying to write code that copy and print the word in text file on the screen with getline() and strchr() functions. so this is my code: ``` void read_teams(char* text) { FILE *fp=fopen(text,"r"); char* tname=NULL; size_t tname_size=0; while(getline(&tname,&tname_size,fp)!=EOF) { tname[strchr(tname,'\n')-tname]='\0'; printf("%s\n",tname); } fclose(fp); } ``` when it is read strchr function it's show: ``` Segmentation fault (core dumped) ``` so why? i have to use this function with getline ,so don't tell me to write my code in other way please.
If the buffer does not contain a\ncharacter, thenstrchr()-tnamewill be way beforetname. That will cause a seg fault. So use: ``` while(getline(&tname,&tname_size,fp)!=EOF) { char *p= strchr(tname,'\n'); if (p) tname[p-tname]='\0'; printf("%s\n",tname); } ```
I am trying to preserve a variable so I can see its value while debugging optimized code. Why is the following an illegal constant expression? ``` void foo(uint_32 x) { static uint_32 y = x; ... } ```
For your purpose you probably want this: ``` void foo(uint_32 x) { static uint_32 y; y = x; ... } ``` What you tried to do is an initialisation. What is done above is an assignment. Maybe for your purpose this would be even more interesting: ``` static uint_32 y; void foo(uint_32 x) { y = x; ... } ``` Now the variableycan easily be accessed by the debugger once thefoofunction is finished.
I've a make file which runs several of targets , now I want to add new target that will run after some timeout, how can I do it ? e.g. execbin: build start run This is running ok, however I want to add new targetcalled testwhich will run after two seconds (some timeout) , how can I do that ? execbin: build start run test testshould execute after the run has finished and also wait 2 seconds before it start , is it possible ?
The lazy solution would be to add a new target called 'sleep-2', and a pattern rule do: ``` execbin: build start run sleep-2 test sleep-%: sleep $(@:sleep-%=%) ``` This creates apattern rulethat takes the value after the hyphen in a sleep-<> target, and uses it as the amount of time to sleep. I will echo @MadScientists's answer that this probably will not work if you domake -j, which really does require changing the targets to depend on each other.
Why the output of the below program is 125 and not 5? ``` #include<stdio.h> #define square(x) x*x int main() { int var; var = 125/square(5); printf("%d",var); return 0; } ```
This line: ``` var = 125/square(5); ``` is expanded into: ``` var = 125/5*5; ``` which evaluates from left to right to25*5and then to125; To fix it, parenthesize the argument in the definition ofsquare, like this: ``` #define square(x) ((x)*(x)) ``` Note also the extra parenthesis aroundxin order to achieve expected behavior when e.g.1+2is passed intosquare.
I'm using strace to investigate the select system call of a process and I'm trying to figure out what doesleftmean. Find below the debug line extracted from the strace log. ``` select(13, [6 7 8 11 12], [], NULL, {0, 10000}) = 1 (in [11], **left** {0, 9994}) ``` So far, I didn't find anything in the available documentation.
Note thatselectupdates thetimeoutparameter to indicate the amount of time that was left before the timeout. This indicates that updated value, in usualstruct timevalformat (seconds and microseconds).See the strace source code to confirm this. So in this case, fd 11 became ready for reading when only 6 microseconds had elapsed.
I've a make file which runs several of targets , now I want to add new target that will run after some timeout, how can I do it ? e.g. execbin: build start run This is running ok, however I want to add new targetcalled testwhich will run after two seconds (some timeout) , how can I do that ? execbin: build start run test testshould execute after the run has finished and also wait 2 seconds before it start , is it possible ?
The lazy solution would be to add a new target called 'sleep-2', and a pattern rule do: ``` execbin: build start run sleep-2 test sleep-%: sleep $(@:sleep-%=%) ``` This creates apattern rulethat takes the value after the hyphen in a sleep-<> target, and uses it as the amount of time to sleep. I will echo @MadScientists's answer that this probably will not work if you domake -j, which really does require changing the targets to depend on each other.
Why the output of the below program is 125 and not 5? ``` #include<stdio.h> #define square(x) x*x int main() { int var; var = 125/square(5); printf("%d",var); return 0; } ```
This line: ``` var = 125/square(5); ``` is expanded into: ``` var = 125/5*5; ``` which evaluates from left to right to25*5and then to125; To fix it, parenthesize the argument in the definition ofsquare, like this: ``` #define square(x) ((x)*(x)) ``` Note also the extra parenthesis aroundxin order to achieve expected behavior when e.g.1+2is passed intosquare.
I'm using strace to investigate the select system call of a process and I'm trying to figure out what doesleftmean. Find below the debug line extracted from the strace log. ``` select(13, [6 7 8 11 12], [], NULL, {0, 10000}) = 1 (in [11], **left** {0, 9994}) ``` So far, I didn't find anything in the available documentation.
Note thatselectupdates thetimeoutparameter to indicate the amount of time that was left before the timeout. This indicates that updated value, in usualstruct timevalformat (seconds and microseconds).See the strace source code to confirm this. So in this case, fd 11 became ready for reading when only 6 microseconds had elapsed.
i have an problem, i am writing a header file, which depending on the Sizes of the c standard datatypes, defines different Structs and Unions. I would need something like this: ``` #if sizeof(int) == 4 typedef struct { int i; } test; #else typedef struct { long i; } test; #endif ``` sadly this doesnt work. Does somebody know, how i can do this? Thanks for your help.
You cant do it this way as preprocessor does not know anything about the C language, but for this purpose you have fixed size integer types which are standard and portable ``` typedef struct { int32_t i; } test; ```
what is the meaning of "D type qualifier is meaningless on cast type at this line of code" ``` (*((volatile RCC_t * const)0x400FE060)).USESYSDIV = 1; ``` and how to solve it?
volatile RCC_t * constsays the pointer (not the thing it points to) isconst. But this is for avalue, which is just a result used in an expression. Qualifiers likeconstare properties ofobjectsin memory. So it serves no purpose in this cast.
This question already has answers here:Comparison operation on unsigned and signed integers(7 answers)sizeof() operator in if-statement(5 answers)Closed3 years ago. ``` unsigned int array[5],length = 5; for(int i = -1; i < length; ++i) { array[i] = i; printf("%d\n", array[i]); } ``` Output: No Output // nothing is printing I am expecting It should print the array. Why no output of this c code ? What is the reason ?
The types ofiandlengthare different (int and unsigned int respectively). So in the comparisoni < length,igets converted to anunsigned intbecauseunsigned inthas higher rank as perusual arithmetic conversions. The value of-1converted tounsigned intisUINT_MAX. Thus the comparison is equivalent toUINT_MAX < 5in the first iteration. Which is false and the loop is never entered.
``` #include <stdio.h> #include <stdlib.h> int main() { int a[3][4]; for (int i=0;i<3;i++){ for(int j=0;j<4;j++){ printf("a[%d][%d]:",i+1,j+1); scanf("%d",a[i][j]); } } return 0; } ``` The program stops in the third line and doesn't execute the next lines
Did you see the compiler warning in yourscanffunction: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ So, using ``` scanf("%d",&a[i][j]); ``` instead of ``` scanf("%d",a[i][j]); ``` This happens becausescanfreceives an address (pointer) to variable, and not the variable itself. adding&before variable name will refer to it's address
``` #include <stdio.h> #include <stdlib.h> #include <time.h> int rnd = list[modo]; } return 1; } ``` This code compiles fine, I just have a question as to why the for loop isn't iterating tillsize < iWhere i is the same size as the integer argument that gets passed int. It's supposed to keep printing%duntil it reaches sizeibut it only prints one random number. I'm trying to get it to print the amount of random numbers that are passed as an argument. So if you enter./main 3to run the program for example it prints:0 4 5or./main 4it prints:2 1 5 6
There is areturn 0inside the for statement block, this exits themainfunction and ends the program, remove this line. (And change the last linereturn 1toreturn 0.)
I need to get the size of a C/C++ executable at runtime in code. Unfortunately I cannot use /proc/self/exe as it's restricted on the target system.
Actually, it's a lot simpler than my attempt in the comments. The executable is simply: ``` (const char *)getauxval(AT_EXECFN) ``` That said, you should always try to open/proc/self/exefirst since the executable may have been deleted/moved/replaced while running.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed3 years ago.Improve this question My homework is this piece of code and I need the explanation and output. I can't understand what this code does and what is the output can anyone help me to understand thanks. ``` for (int i = 0; i < 10; i++) int x = 10; ```
This code iterates 10 times over the variableifromi=0toi=9with aforloop. For every iteration, it declares the variablexas an integer and assign it the value of10. This code has no output. Edit after the comment:if you do not use{}the code has no problem in this case, because in theforloop there is only one instruction. This: ``` for (i = 0; i < 10; i++) int x = 10; ``` and this: ``` for (i = 0; i < 10; i++) { int x = 10; } ``` are the same because there's only one instruction
I tried to read a text file into an array using following code, but each and every value of the array gets the final line read from the text file. ``` #include <stdio.h> int main() { char line[255]; char *kernal[3]; FILE *fpointer_1 = fopen("sample.txt", "r"); for (int i = 0; i <= 2; i++) { fgets(line, 255, fpointer_1); kernal[i] = line; }; fclose(fpointer_1); printf("1st value : %s\n", kernal[0]); printf("2nd value : %s\n", kernal[1]); printf("3rd value : %s\n", kernal[2]); return 0; } ``` Can anyone tell me why that happens and how to solve the issue ?
The problem lies in thekernal[i] = lineline.You alwayspoint to the same line. You need to allocate it a memory, then usestrcpyto copy the contents from thelinearray to the new allocated memory. ``` kernal[i] = malloc(strlen(line) + 1); strcpy(kernal[i], line]; ```
This question already has an answer here:how to printf long double in C? [duplicate](1 answer)Closed3 years ago. i have written the below code in C language. ``` #include <stdio.h> #include <limits.h> #include <float.h> int main(void) { printf("Long Double range: %lf, %lf\n", LDBL_MIN, LDBL_MAX); } ``` when I compile it (with gcc (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008), it shows the below warning!!! ``` warning: format ‘%lf’ expects argument of type ‘double’, but argument 2 has type ‘long double’ ``` how can i resolve this warning? i have used also%leand%lg, but warning resists!
If you want to print a long double value, you must use the placeholder%Lf.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed3 years ago.Improve this question I recently came across this piece of code online,here, I was unable to read it due to the strange if statement. ``` //Send some data if( send(sock , message , strlen(message) , 0) &lt; 0) { puts(&quot;Send failed&quot;); return 1; } ``` I am specifically referring to the&lt; 0following thesend()function. I have never seen this use and am having trouble describing it to google. Can anyone explain this use or link to any resources that may contain more information on it?
The code went through HTML encoding. Replace&lt;with<and&quot;with", and it will immediately make sense.
I am given a N x M matrix and I have a certain amount of sources and sinks and I need to find the maximum paths between them that do not intersect, basically two paths can't use the same vertex. To ensure that, I've set all the maximum capacities of all vertexes to 1. I've already tried to combine the BFS algorithm with the Ford-Fulkerson algorithm using a supersource that it's connected to all sources and a supersink that is connected by all sinks but it doesn't always return the right amount of maximum paths.
Seems like you could just do a simple modification to BFS, where the first source -> sink pass removes the matrix connections for each visited vertex. And then the second pass for second soruce -> sink works on this modified matrix, and so on.
I have a pointer to an array of bytes (u8). I now have a function that takes a pointer of type int (unsigned int). What is an elegant way to accomplish this without creating a new array and converting each element? I need to convert each byte to a single int. (i.e. {0x12, 0x34, 0x56} --> {0x00000012, 0x00000034, 0x00000056}) ``` void external_function(unsigned int *val, int length) { //Write values to ... } void my_function(u8 *array) { int length = 10; //Need to convert *array to (unsigned int *) external_function(array, length); } ```
What is an elegant way to accomplish this without creating a new array and converting each element? There's not one. That's how you have to do it. The problem is that the00bytes between the elements you need just aren't there while it's abytearray.
``` #include <stdio.h> main() { int a[10]; //array declaration printf("Enter 10 numbers: "); for(int i=0;i<10;i++) //loop to take input { scanf("%d", (a[i])); } } ``` Trying to make a program in C that takes 10 integers in an array "a". But it closes after taking the first input. What can be the error?
Use &a[i] to take input. As we need to pass variable address to take input value from user. ``` #include <stdio.h> int main() { int a[10]; printf("Enter 10 numbers: "); for(int i=0;i<10;i++) { scanf("%d", &a[i]); } return 0; } ```
I have a Sample.exe project that depends on Common.dll . I need to use libcurl.dll in both Sample.exe and Common.dll . Do I need to import libcurl.lib into both Sample.exe and Common.dll , or will the .EXE module be able to use libcurl.dll if it's imported by Common.dll . So far in my experiments I'm getting "unresolved external" error in Sample.exe project build, even though it references Common.dll that references libcurl.dll .
No, it cannot. The linker doesn't search through the dlls you import for symbols from other dlls it itself imports, nor does it resolve this kind of indirect importing. You'll have to link with libcurl.dll as well.
For example: ``` bit [1:10] v1 [1:5]; //1 to 10 varies most rapidly; compatible with memory arrays bit v2 [1:5][1:10]; //1 to 10 varies most rapidly, compatible with C; ```
If you line up all the elements by their order in memory(or as a bit-stream), the dimension whose index whose index that would change between each element is the one thatvaries most rapidly. The memory layout does not matter so much since SystemVerilog has no pointers. But is does matter when you try to select parts of an array, the index selecting goes from least to most varying. v1[2][3]is 2 of 5 followed by 3 of 10.
``` printf("\e[2J\e[0;0H"); ``` What does this line mean? Can I know what to learn and from where to understand this statement?
"\e"as an escape sequence is not part of the C standard. A number of compilers treat the otherwiseundefined behavioras a character with the value of 27 - the ASCIIescapecharacter. Alternative well defined code: ``` //printf("\e[2J\e[0;0H"); printf("\x1B[2J\x1b[0;0H"); printf("\033[2J\033[0;0H"); #define ESC "\033" printf(ESC "[2J" ESC "[0;0H"); ``` The escape character introduces ANSI escape sequences as well answered in@Mickael B.. Select terminals implement some of these sequences.
I am given a N x M matrix and I have a certain amount of sources and sinks and I need to find the maximum paths between them that do not intersect, basically two paths can't use the same vertex. To ensure that, I've set all the maximum capacities of all vertexes to 1. I've already tried to combine the BFS algorithm with the Ford-Fulkerson algorithm using a supersource that it's connected to all sources and a supersink that is connected by all sinks but it doesn't always return the right amount of maximum paths.
Seems like you could just do a simple modification to BFS, where the first source -> sink pass removes the matrix connections for each visited vertex. And then the second pass for second soruce -> sink works on this modified matrix, and so on.
I have a pointer to an array of bytes (u8). I now have a function that takes a pointer of type int (unsigned int). What is an elegant way to accomplish this without creating a new array and converting each element? I need to convert each byte to a single int. (i.e. {0x12, 0x34, 0x56} --> {0x00000012, 0x00000034, 0x00000056}) ``` void external_function(unsigned int *val, int length) { //Write values to ... } void my_function(u8 *array) { int length = 10; //Need to convert *array to (unsigned int *) external_function(array, length); } ```
What is an elegant way to accomplish this without creating a new array and converting each element? There's not one. That's how you have to do it. The problem is that the00bytes between the elements you need just aren't there while it's abytearray.
``` #include <stdio.h> main() { int a[10]; //array declaration printf("Enter 10 numbers: "); for(int i=0;i<10;i++) //loop to take input { scanf("%d", (a[i])); } } ``` Trying to make a program in C that takes 10 integers in an array "a". But it closes after taking the first input. What can be the error?
Use &a[i] to take input. As we need to pass variable address to take input value from user. ``` #include <stdio.h> int main() { int a[10]; printf("Enter 10 numbers: "); for(int i=0;i<10;i++) { scanf("%d", &a[i]); } return 0; } ```
I have a Sample.exe project that depends on Common.dll . I need to use libcurl.dll in both Sample.exe and Common.dll . Do I need to import libcurl.lib into both Sample.exe and Common.dll , or will the .EXE module be able to use libcurl.dll if it's imported by Common.dll . So far in my experiments I'm getting "unresolved external" error in Sample.exe project build, even though it references Common.dll that references libcurl.dll .
No, it cannot. The linker doesn't search through the dlls you import for symbols from other dlls it itself imports, nor does it resolve this kind of indirect importing. You'll have to link with libcurl.dll as well.
For example: ``` bit [1:10] v1 [1:5]; //1 to 10 varies most rapidly; compatible with memory arrays bit v2 [1:5][1:10]; //1 to 10 varies most rapidly, compatible with C; ```
If you line up all the elements by their order in memory(or as a bit-stream), the dimension whose index whose index that would change between each element is the one thatvaries most rapidly. The memory layout does not matter so much since SystemVerilog has no pointers. But is does matter when you try to select parts of an array, the index selecting goes from least to most varying. v1[2][3]is 2 of 5 followed by 3 of 10.
``` printf("\e[2J\e[0;0H"); ``` What does this line mean? Can I know what to learn and from where to understand this statement?
"\e"as an escape sequence is not part of the C standard. A number of compilers treat the otherwiseundefined behavioras a character with the value of 27 - the ASCIIescapecharacter. Alternative well defined code: ``` //printf("\e[2J\e[0;0H"); printf("\x1B[2J\x1b[0;0H"); printf("\033[2J\033[0;0H"); #define ESC "\033" printf(ESC "[2J" ESC "[0;0H"); ``` The escape character introduces ANSI escape sequences as well answered in@Mickael B.. Select terminals implement some of these sequences.
This piece of code return an error. ``` #include<stdio.h> #include<stdlib.h> int* a; a = NULL; int main(){ printf("works"); return 0; } ``` whereas this one does not... ``` #include<stdio.h> #include<stdlib.h> int* a= NULL; int main(){ printf("works"); return 0; } ``` What's the difference and why does this show the re-declaration error? If I do the same thing inside main function it works. But not outside.
a = NULL;is a statement you can put only in the body of function int* a= NULL;is the definition with initialization of the global variablea
I have noticed that both work, what is the correct way to use inline here? ``` static inline int getAreaIndex() ``` OR ``` inline static int getAreaIndex() ``` Plus, getAreaIndex contains a large loop. sometimes I call it only one and sometimes I call it through a loop, should I inline it? (it's 10 line tall)
What is the correct way to use inline here Bothstatic inlineandinline staticare allowed and they mean the same thing.static inlineis preferred, because "storage class specifiers" likestaticare always supposed to come first in a declaration (seeC11 §6.11.5). should I inline this function To answer this question you will need to benchmark your program both ways and find out which is faster.
Probably, I don't know something about ifstream. I have binary file : 0604 0204 0a02. ``` std::ifstream input(input_filename, std::ios::binary); unsigned char cmd; unsigned char type; while (!input.eof()) { input >> cmd; input >> type; std::cout << static_cast<int>(cmd) << " " << (int)type << "\n"; } ``` And result of this code: ``` 6 4 2 4 2 0 ``` What is going wrong?
operator >>is skipping white space. You need to call ``` while(input.read(&cmd, 1) && input.read(&type, 1)) {} ``` or ``` while(input >> std::noskipws >> cmd >> std::noskipws >> type) {} ``` Also please note the changed error checking (just casting the stream to bool).
While readinguname.c(in order to recreate it) I found a variable calledHOST_OPERATING_SYSTEM(line 371). It's never mentioned in the same file (as Strg+f told me) and not in the dependencies ofuname.c, as far as I could see. Where is the variable initialized and how to access it?
HOST_OPERATING_SYSTEMis defined at build time using autoconf modules defined ingnulib.
This question already has answers here:Variable Scope in C programming(4 answers)Closed3 years ago. What is difference between defining a var inside a loop or outside? for example: ``` int a; for(int i=1; i<11; i++){ a = rand()%10; printf("%d\n",a); } ``` theais defined first and then is used in loop. but in : ``` for(int i=1; i<11; i++){ int a = rand()%10; printf("%d\n",a); } ``` hereais defined in the loop. What is difference and which one is slower?
the difference is the scope of the variable. a exists after the loop ends in the 1st case, but does not in the 2nd case.