question
stringlengths
25
894
answer
stringlengths
4
863
The user writes a number to the input, it is stored in a string. How can I check if this number is included in size in thefloattype or does it need adouble?
Unless your floating point numbers are huge or extremely small, i.e. out of the range spanning -3.4E38 to 3.4E38, a float 32 will store anything you throw at it in terms of size but not accuracy. As such, the real issue is how many significant digits you need in order to minimize rounding errors. I recommend you to readhttps://www.itu.dk/~sestoft/bachelor/IEEE754_article.pdf If you are not limited by disk space or memory, then just go for float 64.
I have never been good at reading and understanding C & C++ Library documentation, for some reason. It's drives me insane. If I see a working sample then I'm good for most other things. I have installed libsmbios-dev and libsmbios-doc on my ubuntu based machine. The Library docs are located at /usr/share/doc/libsmbios-doc/doxygen/libsmbios_c Can anyone provide a working example of pulling the service tag number on a dell machine using libsmbios? I've search and I can't seem to find what i'm looking for. Thank you
Could this function be the one you're looking for? ``` char *sysinfo_get_service_tag(); ``` Defined inservice_tag.c, declared insystem_info.h. I am unable to test this, but you would presumably include this file in your code. ``` #include <smbios_c/system_info.h> ```
I know that here are some explanations about the difference between p++, ++p and p+1 but I couldn't understand it clearly yet, especially when it's not working with that function: ``` void replace(char * str, char c1, char c2){ if (*str == '\0') { return; }else if (*str == c1) { printf("%c", c2); } else { printf("%c", *str); } replace(++str, c1, c2); } ``` When I doreplace(++str, c1, c2);orreplace(str+1, c1, c2);it works, butreplace(str++, c1, c2);doesn't. Why?
replace(str++, c1, c2);means: ``` replace(str, c1, c2); str+=1; ``` whilereplace(++str, c1, c2);means: ``` str+=1; replace(str, c1, c2); ```
If you wanted a random number generator to use ints 2,5,7,4 and you seed your generator with ``` srand(2,5,7,4) printf("%d \n",rand()) ``` Is this flawed in accomplishing that?
That is not how it works. An PRNG uses an algorithm to generate a sequence of numbers with random like behaviour. For a given seed, a given sequence of numbers will be generated, what those number are is entirely up to the algorithm used. to get a random number for a list, you will need something like: ``` n = list[rand() % (sizeof(list) / sizeof(list[0])]; ```
I'm using VScode as my IDE, IN my college we require to write our codes using TopDown Design. like this example: ``` void sum(int a, int b); int main() { int a=2, int b=3; sum(a,b); return 0; } void sum(int a, int b) { printf("%d", a+b); } ``` My problem is that a lot of time while editing my function at the "Down LVL" I also need to edit the signature for adding or removing arguments, is there add-in or some key bind in VScode that can edit both signatures at the same time while I only edit one of them?
If you place the cursor over the signature and pressCTRL + Dyou can select all the signatures, one at a time, then you can change them all in one go.
I have this code: ``` #include <stdio.h> int main(){ char a[] = "ciao"; char *aPtr = a; printf("%s\n", *aPtr); } ``` It gives me this warning: ``` 8:17: warning: format specifies type 'char *' but the argument has type 'char' [-Wformat] printf("%s\n", *aPtr); ~~ ^~~~~ %c 1 warning generated. ``` If I run it I got segmentation fault ``` Segmentation fault: 11 ``` Why?
Remove the '*' you have in the printf. You need to provide a memory adress in order to the function to be able to seek for the rest of the string. ``` printf("%s\n", aPtr); ``` You're just sending printf a 'c' (the first character of "ciao"). Hope this helps.
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 have an existing Excel with Sheet Sheet1 which has 3 Columns:e.g. FeatureName FeatureLabel FeatureDesc I have 5 rows with the respective data. I want to open the Excel and add a new row in the Excel usingCcode. Can anyone suggest me a solution for the same?
You can uselibxlsxwriterto write text, numbers, formulas and hyperlinks to multiple worksheets in an Excel 2007+ XLSX file. Thistutorialcan help you to add new row by usingworksheet_writefamily function (for example,worksheet_write_number,worksheet_write_string,worksheet_write_formula).
How can I determine the maximum file path length allowed in the system my program is running on? Is it inlimits.h? because I didn't find it there.
It should be NAME_MAX defined in<limits.h> https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html
This is my code: ``` #include<stdlib.h> int main() { system("getent passwd {1000..60000}"); return 1; } ``` I believe the ".." present in the command is causing the problem cause the program runs properly for other commands.
systemdoes not run yournormalshell. It insteadalwaysruns/bin/sh. Fromsystem(3): DESCRIPTIONThesystem() library function usesfork(2) to create a child process that executes the shell command specified in command usingexecl(3) as follows:execl("/bin/sh", "sh", "-c", command, (char *) NULL);system()returns after the command has been completed. Usually/bin/shis a shell that does not understand{1000..60000}. To run bash or zsh you need to do something like ``` system("/bin/bash -c 'getent passwd {1000..60000}'"); ```
I have the stringchar str [8]. It says a number in the HEX format. It is float and with a sign. How can I write it to a variable of type float? For example: ``` char str[9] = "41700000\0"; ``` I need get val from this:15.0
You can pun the data: Using memcpy ``` unsigned int u = 0x41700000; float f; memcpy(&f, &u, sizeof(f)); printf("%f\n", f); ``` Using union (IMO legal, many people have opposite opinion) ``` union un { float f; unsigned u; }; void foo(unsigned x) { union un a = {.u = x}; printf("%f\n", a.f); } ``` I assume floats && integers have the same size. Of course you will have to convert string from your question to the unsigned value - but it is relatively easy (scanf, atoi ....) PS BTW many compilers will generate exactly the same code for both (without thememcpycall)https://godbolt.org/z/VaCcxS
See the following code: ``` #include<stdio.h> #include<string.h> int main(void) { printf("%lu",strlen("\\n")); } ``` I know that the output would be2but confused whether\\would be the first character taken into account and thennor\would be the first count and\nwould be the second?
From the C Standard (6.4.4.4 Character constants) simple-escape-sequence: one of ``` \' \" \? \\ \a \b \f \n \r \t \v ``` and 3 The single-quote ', the double-quote ", the question-mark ?, **the backslash **, and arbitrary integer values are representable according to the following table of escape sequences: ``` single quote ' \' double quote " \" question mark ? \? backslash \ \\ octal character \octal digits hexadecimal character \x hexadecimal digits ``` Thus this string literal"\\n"containsbackslashand the charactern.
How can I determine the maximum file path length allowed in the system my program is running on? Is it inlimits.h? because I didn't find it there.
It should be NAME_MAX defined in<limits.h> https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html
This is my code: ``` #include<stdlib.h> int main() { system("getent passwd {1000..60000}"); return 1; } ``` I believe the ".." present in the command is causing the problem cause the program runs properly for other commands.
systemdoes not run yournormalshell. It insteadalwaysruns/bin/sh. Fromsystem(3): DESCRIPTIONThesystem() library function usesfork(2) to create a child process that executes the shell command specified in command usingexecl(3) as follows:execl("/bin/sh", "sh", "-c", command, (char *) NULL);system()returns after the command has been completed. Usually/bin/shis a shell that does not understand{1000..60000}. To run bash or zsh you need to do something like ``` system("/bin/bash -c 'getent passwd {1000..60000}'"); ```
I'm doing thischallengeand I am using this for loop for the code. ``` for (y >= i; y--;) { printf(" "); } ``` But I keep getting this error back ``` mario.c:57:20: error: relational comparison result unused [-Werror,-Wunused-comparison] for (y > i; y--;) ~~^~~ ``` The only trick that worked was making a useless variable inside the for() condition, but that would be useless and just take up space. Only other fixes?
The first part of aforis the initialization part, not the condition. The condition is the second part. You instead want: ``` for (; y >= i; y--) ```
I'm debugging using GDB. I know while debugging we can: ifchar arr[4] = {'a', 'b', 'c', '\0'}then usedisplay /s arrin GDB to display{a, b, c}for every stop in the debugger. But how to display an array of ints using display? so that I get the entire array contents in every stop? For example ifint arr[4] = {4, 3, 2, 1}. How do I display the entire arr using the GDB display function so that the whole arr appears each stop? So that every stop I see: {4, 3, 2, 1}
In GDB you can type indisplay /d *arr@4This will display{4,3,2,1}where@4displays 4 addresses in arr whiledisplay /d arr[0]will just display the first index of arr
My question is that in the last statement I want to show the gc variable in the lastprintf. I mean: if you introduced 4 celsius, I want to show that 4 in the as well, but I dont know how to show an variable in aprintf. ``` //celsius a radianes #include<stdio.h> int main(){ float gc, gf = ( gc * 9 / 5) + 32; printf("\n Programa para convertir de Grados celsius a grados Fahrenheit\nIntroduzca un numero en grados celsius:\n"); scanf("%f", &gc); gf = ( gc * 9 / 5) + 32; printf( "gc en Grados en fahrenheit = %.4f\n", gf); } ```
Question edited heavily (sorry OP) How to printgcandgfin print?printf( "gc en Grados en fahrenheit = %.4f\n", gf); Just add another %specifier and the corresponding variable ``` printf( "%.4f en Grados en fahrenheit = %.4f\n", gc, gf); // ^^^^ specifier1 ^^^^ specifier2 ```
Consider the following piece of code: ``` void fun (string &str1, string &str2) { const char* cstr; .... if(strlen(cstr = (str1+str2).c_str()) < 15) { // here cstr used } } ``` The condition itself works fine, but in the if-condition bodycstrcontains garbage. Why?
In this expression: ``` cstr = (str1+str2).c_str() ``` you are taking a pointer to thetemporarystringstr1 + str2. This temporary dies at the end of the expression, and so you have undefined behaviour when you try to read fromcstrinside the if-body.
``` #include <stdio.h> int main(void) { char b[5]; scanf("%4s%4s", b, b); printf("%s", b); } ``` What is the exact definition of a scalar object? Isba scalar object in this case?
According to thec11 standard, "Arithmetic types and pointer types are collectively called scalar types. Array and structure types are collectively called aggregate types" So no,bisn't a scalar because it is an array. If it were a number or a pointer (likechar* b), it would be a scalar type.
I'm trying to split a number in C into two at the decimal point. For example, let's say the number is1.5, then I want to split it into1and0.5. How can I do this?
You can usemodf()frommath.hlibrary: ``` #include <stdio.h> #include <math.h> int main () { double value, fractional, integer; value = 8.123456; fractional = modf(value, &integer); printf("Integral part = %lf\n", integer); printf("Fraction Part = %lf \n", fractional); return(0); } ``` Sample fromtutorialspoint.com
Why I am getting error here: ``` #include <stdio.h> #include <stdlib.h> struct abc{ char a;char b; }; int main (void) { struct abc def; __typeof__(def)* g; g->a = 'a'; //error line return 0; } ``` That above is only a warning, but true error iscommand terminated. Do know why
You've definedgas a pointer to typestruct abc, but you didn't set that pointer to point anywhere. So when you attempt to dereference it by writing tog->ayou invokeundefined behavior. You need to makegpoint somewhere, probably todef. ``` __typeof__(def)* g = &def; ```
This question already has answers here:Forward an invocation of a variadic function in C(13 answers)Closed5 months ago. I want to call a variadic function in a variadic function. The code does not give an error, but the resulting values are incorrect. What is the correct way to do this? ``` #include <stdarg.h> void SecondFunction (int count, ...) { va_list args; va_start(args, count); AddValues(count, args); va_end(args); }; void AddValues(int count, ...) { va_list args; va_start(args, count); for(int i=count; i--; ) processItem(va_arg(args, void*)); va_end(args); } ```
This will not work, but you can create a similar function that uses ava_listargument. That is exactly why functions such asvsyslogandvprintfexists. In its simplest form: ``` void vAddValues(int count, va_list args) { int i; for (i = count; i--; ) processItem(va_arg(args, void *)); } ```
I know for sure there is a command for CUP that prints out the produced parse tree. Is there a similar command for Bison?
No, there isn't. If you want an AST or parse tree, you are responsible for building it, and the AST node objects should be able to print themselves out, as it were.
``` int main (){ int i, total; printf("Loop to one hundred.\n"); for(i=1; i<=100; i+=2){ printf("%d ",i); total += i; } printf("\nTotal: %d", total); return 0; } ``` So I have a C programming code up on it, and I have the result as well. But what I found is the result isn't what the answer that I want. I was expecting the result is 2500 but it gave 2516. Can someone point it out what's wrong on my code? If someone suggest using while loop, yes while loop can gave me the correct answer which is 2500 but I want to know why I use for loop it gave me 2516.
You forgot to initialize the variabletotalbefore starting additions. ``` int i, total; ``` should be ``` int i, total = 0; ```
This question already has answers here:C++ literal integer type(2 answers)Closed3 years ago. Why doesn't this code print same number? : ``` long long a, b; a = 2147483647 + 1; b = 2147483648; printf("%lld\n", a); printf("%lld\n", b); ``` I know that int variable's maximum number is 2147483647 because int variable is 4 byte. But as I know, long long variable is 8 byte, but why does that code act like that?
2147483647 + 1is evaluated as the sum of twointsand therefore overflows. 2147483648is too big to fit in anintand is therefore assumed by the compiler to be along(or along longin MSVC). It therefore does not overflow. To perform the summation as along longuse the appropriate constant suffix, i.e. ``` a = 2147483647LL + 1; ```
We all know that Port numbers in IPv4 and IPv6 are 16 bits wide so the range should be 0 to 65535, But I have heard that 0 is excluded and reserved for something else, This range is now 1 to 65535. I want to know for what purpose it is reserved and for what purpose?
Port 0 is used as a "wildcard" port, meaning that when an application tries to create a socket andbind()it to an IP address, and supplies 0 as the port, the OS automatically binds the socket to a random available ephemeral port. This is useful when applications need to send data and do not care which port it is sent from. This ensures that applications do not need to constantly try to find a suitable port manually. The OS is powerful, so let it do (some of) the work for you.
Why does the C/++ scanf function need referenced variables as arguments? I was wondering why scanf can't just take in the variable itself, since it gave me a weird warning whenever I didn't put in a referenced variable. It thought I had put in a pointer. Why is that? Thanks.
I don't see how they could modify the value Here is an example ``` #include <stdio.h> void changeNumber(int *n) { *n = 12; } int main() { int x = 5; printf("X: %i\n", x); changeNumber(&x); printf("X: %i", x); return 0; } ``` Output ``` X: 5 X: 12 ```
This question already has answers here:Forward an invocation of a variadic function in C(13 answers)Closed5 months ago. I want to call a variadic function in a variadic function. The code does not give an error, but the resulting values are incorrect. What is the correct way to do this? ``` #include <stdarg.h> void SecondFunction (int count, ...) { va_list args; va_start(args, count); AddValues(count, args); va_end(args); }; void AddValues(int count, ...) { va_list args; va_start(args, count); for(int i=count; i--; ) processItem(va_arg(args, void*)); va_end(args); } ```
This will not work, but you can create a similar function that uses ava_listargument. That is exactly why functions such asvsyslogandvprintfexists. In its simplest form: ``` void vAddValues(int count, va_list args) { int i; for (i = count; i--; ) processItem(va_arg(args, void *)); } ```
I know for sure there is a command for CUP that prints out the produced parse tree. Is there a similar command for Bison?
No, there isn't. If you want an AST or parse tree, you are responsible for building it, and the AST node objects should be able to print themselves out, as it were.
``` int main (){ int i, total; printf("Loop to one hundred.\n"); for(i=1; i<=100; i+=2){ printf("%d ",i); total += i; } printf("\nTotal: %d", total); return 0; } ``` So I have a C programming code up on it, and I have the result as well. But what I found is the result isn't what the answer that I want. I was expecting the result is 2500 but it gave 2516. Can someone point it out what's wrong on my code? If someone suggest using while loop, yes while loop can gave me the correct answer which is 2500 but I want to know why I use for loop it gave me 2516.
You forgot to initialize the variabletotalbefore starting additions. ``` int i, total; ``` should be ``` int i, total = 0; ```
This question already has answers here:C++ literal integer type(2 answers)Closed3 years ago. Why doesn't this code print same number? : ``` long long a, b; a = 2147483647 + 1; b = 2147483648; printf("%lld\n", a); printf("%lld\n", b); ``` I know that int variable's maximum number is 2147483647 because int variable is 4 byte. But as I know, long long variable is 8 byte, but why does that code act like that?
2147483647 + 1is evaluated as the sum of twointsand therefore overflows. 2147483648is too big to fit in anintand is therefore assumed by the compiler to be along(or along longin MSVC). It therefore does not overflow. To perform the summation as along longuse the appropriate constant suffix, i.e. ``` a = 2147483647LL + 1; ```
We all know that Port numbers in IPv4 and IPv6 are 16 bits wide so the range should be 0 to 65535, But I have heard that 0 is excluded and reserved for something else, This range is now 1 to 65535. I want to know for what purpose it is reserved and for what purpose?
Port 0 is used as a "wildcard" port, meaning that when an application tries to create a socket andbind()it to an IP address, and supplies 0 as the port, the OS automatically binds the socket to a random available ephemeral port. This is useful when applications need to send data and do not care which port it is sent from. This ensures that applications do not need to constantly try to find a suitable port manually. The OS is powerful, so let it do (some of) the work for you.
Why does the C/++ scanf function need referenced variables as arguments? I was wondering why scanf can't just take in the variable itself, since it gave me a weird warning whenever I didn't put in a referenced variable. It thought I had put in a pointer. Why is that? Thanks.
I don't see how they could modify the value Here is an example ``` #include <stdio.h> void changeNumber(int *n) { *n = 12; } int main() { int x = 5; printf("X: %i\n", x); changeNumber(&x); printf("X: %i", x); return 0; } ``` Output ``` X: 5 X: 12 ```
This question already has answers here:The need for parentheses in macros in C [duplicate](8 answers)Closed3 years ago. My code: ``` #include <stdio.h> #define PRODUCT(x) (x * x) int main() { int i = 3, j, k, l; j = PRODUCT(i + 1); k = PRODUCT(i++); l = PRODUCT(++i); printf("%d %d %d %d", i, j, k, l); return 0; } ``` I am not able to comprehend why the output is: ``` 7 7 12 49. ``` Is there any error in macro or some other problem?
Your code has undefined behavior, operations ini: ``` k=PRODUCT(i++); l=PRODUCT(++i); ``` lack a sequence point. As for: ``` j=PRODUCT(i+1); ``` It expands toi+1*i+1which isi+i+1which is7. I assume it's not the expected result, in the future also include that in your question.
So I'm trying to print out a 2d array (double array[2][3]) that has decimal numbers and characters something like that ``` 3.4 E 5.6 R 7.8 T ``` Numbers in row and chrachters in the other row
I don't , this is some thing you want or not: ``` #include <stdio.h> int main() { double array[2][3] = {{2.5, 3.6, 4.2}, {'R', 'A', 'Q'}}; for(int i = 0; i < 3; i++) { printf("%lf ", array[0][i]); } printf("\n"); for(int i = 0; i < 3; i++) { printf("%c ", (char)array[1][i]); } return 0; } ``` output: ``` 2.500000 3.600000 4.200000 R A Q ``` As the comment, you should use the struct that contains two types (one forchar, one fordouble) because cast fromdoubletocharas i did is not recommended.
I have a driver which is, for some unknown reasons causing a bugcheck 0x0000003b. So I decided to set up a Hyper-V VM and use kernel debugging to see what exactly is going on. I already enable testing signing withbcdedit, and checked that the driver is indeed loaded and running withsc query. The problem is that I want WinDbg to step in ONLY when the offending driver is being called and not when the windows debugee is booting, how can I do that? How do I instruct windbg to pause at the DriverEntry function of my driver?
You can add a breakpoint at DriverEntry using command 'bm DriverName!DriverEntry'.
I read that: sizeof operator returns the size of the data type, not the amount of memory allocated to the variable. Isn't the amount ofmemory allocateddepends on the size of the data type? I mean thatsizeofwill return 4 (architecture-dependent) when I passintto it. Am I missing something here?
sizeofreturns the number of bytes that a variable or stack allocated array occupies. Examples: sizeof(char)=1(in most configurations)Butsizeof(char*)=8(depending on the platform)If you dynamically allocate memory withmalloc, you will receive a pointer to that block of memory. If use thesizeofon it, you will just get the size of the pointer.However,sizeof()a stack allocated array like when you writeint a[10]is the size of the allocated memory (so 4*10) The size of the pointer doesn't depend on the size of the datatype it represents. (On 32 bit platforms, a pointer is 32bit)
Thevarnish docssay that we can include C snippets inside a VCL file, like ``` sub vcl_hash { C{ int i = /* Some logic to get a number */ }C } ``` But now how can I use the value of the integerito set a response header, or cookie
Seevarnish.vcc And the functions: VRT_SetHdrVRT_GetHdr in varnish 4 there isctxvariabl defined for the context (as opposed tospin varnish 3 ) (source) example: ``` sub vcl_hash { C{ const char *hash = calc_hash(...); const struct gethdr_s hdr = { HDR_BERESP, "\010X-Hash:" // length prefixed string, in octal }; VRT_SetHdr(ctx, &hdr, hash, vrt_magic_string_end); }C } ``` seehere for another example
Im trying to write a function the converts kelvin to celsius of farenheit based on a user input, i want it to keep prompting the user if they enter an invalid input but no matter the input it prints "Invalid Input" and the loop repeats even though im printing the value of y to test it and it returns as 'C' or 'F' (ReadChar() just uses scanf and returns the character) ``` do { printf("Choose Celsius or Farenheit (F/C): "); y = ReadChar(); y = toupper(y); printf("%c", y); if ((y != 'C') || (y != 'F')) { printf("Invalid Input\n"); } }while ((y != 'C') || (y != 'F')); return(y); ```
You inverted your logic incorrectly. Assuming you started with((y == 'C') || (y == 'F'))which defines a valid input, and now you want to inverse condition to define an invalid input, you need to change the logic to((y != 'C') && (y != 'F'))(see DeMorgans Law).
I am currently writing a game of battleship as a project for a class. What is the best way to store coordinates for ship locations? The ocean is a 10x10 grid square with letters going horizontally and numbers vertically. I need to store the coordinates of each ship. For example, the carrier has 5 spaces so A1, B1, C1, D1, and E1. If I do this in an array, I would somehow have to break up the A1 into a char and an int. Correct? Is there a better way to do this? Thanks in advance.
you can use a structure: ``` struct point{ int m_vertical; char m_horizon; } ``` any way you need to do some effort before you ask a question. Please do some effort and try to search and dig in the webs before asking. good luck
I'm trying to review a C/C++ project which is heavily dealing with macros and function-like macros. What I would like to do is to replace thedefineand function-like macros with their replacement. For example I have this file: ``` #include <iostream> #define SUM(a,b,c,d) a+b+c+d using namespace std; int main(){ cout << SUM(1,2,3,4) << endl; } ``` And I want to reach to this file: ``` #include <iostream> using namespace std; int main(){ cout << 1+2+3+4 << endl; } ``` Please note that I'm not looking to replace the#includelines. EDIT: gcc -Eexpands the#definemacros but it will also expand the#includemacros as well. I DO NOT want the#includeto be expanded.
I've usedgcc -nostdinc -E ...(or something similar) before. Can't test this at the moment; don't really remember exactly why I used it either
I am using an ATMEGA16M1 microcontroller and the MPLAB IDE. I have following function to write to the ports. ``` void Lcd8_Write_String(char *a) { int i; for(i=0;a[i]!='\0';i++) Lcd8_Write_Char(a[i]); } void Lcd8_Write_Char(char a) { pinChange(RS,1); // => RS = 1 Lcd8_Port(a); //Data transfer pinChange(EN,1); // => E = 1 _delay_ms(1); pinChange(EN,0); // => E = 04 _delay_ms(1); } ``` I call the function withLcd8_Write_String("Hello World");. I get: error: passing argument 1 of 'Lcd8_Write_String' from pointer to non-enclosed address space. How do I resolve this error?
If you write: ``` Lcd8_Write_String("Hello World"); ``` The string"Hello World"will be in the Flash memory of your microcontroller and not in the RAM. So you had to switch your function to: ``` void Lcd8_Write_String(const char *a) ```
for example i have an array with elements0 1 2 3 4 5 6i want to add say 3 to all the elements and want this output:3 4 5 6 0 1 2after the addition the numbers should not exceed the largest element, but start from the smallest one.Hard to explain. Is there some way of doing this in c? (not c++)
What you are describing seems to be addition modulo the maximum element + 1, i.e., a sum greater than the maximum element wraps around. Find the maximum element, let's call itmax, by iterating over the array.Iterate over the array again, and for each element do the addition modulomax + 1, i.e., conceptuallyarr[i] = (arr[i] + n) % (max + 1). (If it was intended that the wrap-around is not to zero but to the minimum element, then also find the smallest value in step 1 and doarr[i] = ((arr[i] - min + n) % ((max - min) + 1)) + minin step 2.)
``` int main(int argc, string argv[ ]) { variable(x); } ``` Such as here. How can I use argv and argc here?? ``` int variable(x) { //I want to use argc and argv here.. } ```
Yes, they are just like any other function parameters: ``` int variable(int x, int argc, char *argv[]) { for(int i = 0; i < argc; ++i) printf("%s\n", argv[i]); return x; } int main(int argc, char *argv[]) { int x = 42; variable(x, argc, argv); } ```
``` char str[vector_total(&final_clause)]; for(int i = 0; i<vector_total(&final_clause); i++) { printf("%s ", (char*) vector_get(&final_clause,i)); // outputs b a -c a a -c -c strcpy(str, (char*) vector_get(&final_clause,i)); } printf("%s", str); //only prints -c (last ) remove_repeatation(str); // removes repeats. Expected: b a-c ``` Evidently its replacing 'str' everyloop. So what is the best way to fix this? Not sure if this is a easy question but I just haven't been able to crack it using different approaches.
char str[vector_total(&final_clause)];too small. ``` size_t len = vector_total(&final_clause); char str[len*2 + 1]; // might be enough ``` //only prints -c (last ) Code copiesvector_get()into the same location so this is expected. Perhaps usestrcat()andstr[0] = 0;for the firststrcat(str, ..to work.
I'm filling a lower triangular matrix like this: ``` for (i = 0; i < size; i++) { for (j = 0; j <= i; j++) l[i][j] = j + 1; } ``` And I want to calculate the order of the code in Big O notation but I'm really bad. If it was a regular matrix it would be O(n²) but in this case I'm not sure if it's O(nlog(n)) or something like that.
Typically (but not always) one loop nested in another will cause O(N²). Think about it, the inner loop is executeditimes, for each value ofj. The outer loop is executedsizetimes. This comes out to be 1/2 of N^2, which is still O(N^2)
Firstly i will show an example: ``` void main(void){ char word[12]; char input[12]; int i; printf("Input some word: "); scanf("%s",input); for(i=0;i<strlen(input);i++) word[i]=NULL; if(word[i]==NULL){ printf(" %c ",word[i]); } } ``` As you can see i give to word[i] a NULL value that makes the warning "Warning assignment makes integer from pointer without a cast", then the next warning is in the if "Warning comparison between pointer and integer". So how can i resolve this warnings, exist other options instead of giving the NULL value?
string null terminator is'\0',NULLis usually for pointers.
I am getting an error in the constructor for Node inside the sizeof(Node) saying "type name is not allowed" any thought ? Thank you ``` struct Node { int data; Node *next; }; struct LinkedList { Node *first; int size; }; typedef struct Node Node; typedef struct LinkedList LinkedList; //constructor for node Node* createNode(int data) { Node * newNode = malloc(sizeOf(Node)); if (data != NULL) { newNode->data = data; newNode->next = NULL; return newNode; } return NULL; } ```
``` malloc(sizeOf(Node)) ``` should be ``` malloc(sizeof(Node)) ``` also I suspect that there are other compiler errors; you have to do ``` struct Node * ``` rather than ``` Node * ```
I'm trying to write a parallel IO program with MPI, I'm required to write the data to the file with a format as:02 03 04in the file instead of2 3 4. ``` fprintf(fpOut,"%.2d ",var); ``` Would be the serial counterpart of what I'm trying to do. I've looked around but couldn't find any answers so far. Any idea on how I might go about this?
MPI_IOwrites binary data (vs text/formatted data). So if you really want to write in parallel, you can use an intermediate buffer, and then write it, for example ``` char buf[4]; sprintf(buf, "%.2d ", var); MPI_File_write_at(buf, 3, MPI_CHAR, ...); ``` That being said, you might want to reconsider your workflow: one option is to start using binary data everywhere (and write in parallel)an other option is to write intermediate data in binary and in parallel, and finally post process it (not in parallel) to "convert" it into plain text.
Does the expressionnode.next->prevevaluate to the same thing asnode->next->prev?
In C, at least one ofnode.next->prevandnode->next->prevwon't compile. Ifnodeis declared as a pointer to a structure (say,struct Node* node), then you can't use the.operator on it because.can only be applied to honest-to-goodnessstructs, not pointers to them. In that case,node.next->prevwon't compile, whilenode->next->prevwill. Conversely, ifnodeis defined as an actual honest-to-goodnessstruct(say,struct Node node), thennode->next->prevwon't compile because->can only be applied to pointers, whilenode.next->prevwill. That being said, theintentbehind these two pieces of code is the same. They both mean "go to some node, pick out itsnextfield, then read theprevfield of whatever node that is."
I'm trying to write a parallel IO program with MPI, I'm required to write the data to the file with a format as:02 03 04in the file instead of2 3 4. ``` fprintf(fpOut,"%.2d ",var); ``` Would be the serial counterpart of what I'm trying to do. I've looked around but couldn't find any answers so far. Any idea on how I might go about this?
MPI_IOwrites binary data (vs text/formatted data). So if you really want to write in parallel, you can use an intermediate buffer, and then write it, for example ``` char buf[4]; sprintf(buf, "%.2d ", var); MPI_File_write_at(buf, 3, MPI_CHAR, ...); ``` That being said, you might want to reconsider your workflow: one option is to start using binary data everywhere (and write in parallel)an other option is to write intermediate data in binary and in parallel, and finally post process it (not in parallel) to "convert" it into plain text.
Does the expressionnode.next->prevevaluate to the same thing asnode->next->prev?
In C, at least one ofnode.next->prevandnode->next->prevwon't compile. Ifnodeis declared as a pointer to a structure (say,struct Node* node), then you can't use the.operator on it because.can only be applied to honest-to-goodnessstructs, not pointers to them. In that case,node.next->prevwon't compile, whilenode->next->prevwill. Conversely, ifnodeis defined as an actual honest-to-goodnessstruct(say,struct Node node), thennode->next->prevwon't compile because->can only be applied to pointers, whilenode.next->prevwill. That being said, theintentbehind these two pieces of code is the same. They both mean "go to some node, pick out itsnextfield, then read theprevfield of whatever node that is."
Can anyone explain why the following statement on Page 187 of Edition 2 for malloc implementation is used: ``` nunits = (nbytes+sizeof(Header)-1)/sizeof(Header)+1; ``` p187 Malloc Specifically, why the offsets -1 and +1 are used to calculate nunits.
It rounds up the size of the allocation requested to the next unit ofsizeof(Header)and divides bysizeof(Header)to give the number of units of headers needed to store the data requested, and adds one to give it a header to use for the control information that will be wrecked when you write outside the bounds of the allocated memory. If the header size is 16 bytes, for example, then the request sizes produce: ``` 1..16 2 17..32 3 33..48 4 ``` Etc.
Using thearm-none-eabi-gcctoolchain. During ARM development using options-nostdlibin the linker,i can use unsigned int, int etc. However foruint8_ti have to use--specs=nano.specs, since they are in the newlib standard library. So how isunsigned intbeing resolved? i have been doing ARM development for quite some time using an IDE. Hence didnt know how the underlying stuff works. Was going through some bare metal tutorial when i encountered these doubts. Thank you.
unsigned intis a basic type defined by the C standard (see C99 §6.2.5, page 33here), it isn't defined anywhere else, the compiler already knows how to handle it. uint8_tand other similar types are implementation defined and therefore you may find those defined in library headers.
I want to print Japanese characters using the C program. I've found the Unicode range of some Japanese characters, converted them to decimal and used the for loop to print them: ``` setlocale(LC_ALL, "ja_JP.UTF8"); for (int i = 12784; i <= 12799; i++) { printf("%c\n",i); } ``` locale.h and wchar.h are present in the header. The output gives me only ?????????? characters. Please let me know how it could be resolved.
%cis only able to print characters from 0 to 127, for extended characters use: ``` printf("%lc\n", i); ``` or better yet ``` wprintf(L"%lc\n", i); ```
Im writing a c program for an university exam, and im dealing with the following issue: when I try to print the "£" character to the screen with cout or printf, it comes out the "ù" character instead. What I'm doing wrong?
On Windows the console uses another code page. Add this to your includes: ``` #include <windows.h> ``` Add this as the first line of yourmainfunction: ``` SetConsoleOutputCP(1252); ``` Or a more portable solutiuon: Add this to your includes: ``` #include <locale.h> ``` Add this as the first line of yourmainfunction: ``` setlocale(LC_ALL, ""); ```
If I declare a variable in an if condition in C, is that variable also available to the else branch? For example: ``` if((int x = 0)){ foo(); } else{ x++; bar(x); } ``` Couldn't find the answer, at least not the way that I worded it. Please help.
You can't declare a variable in an if condition in C... Declare variable in if statement (ANSI C) If you declare inside the if scope, for example: ``` if(something){ int x = 0; } else{ x++; // will cause a compilation error bar(x); } ``` x in 'else' is undeclared because in C a local variable can only be used by statements contained within the code block where they are declared.
If you were trying to prevent a buffer overflow attack for a C program that you were writing, you would simply modify your code to be safer. However, what if you werejustgiven a binary executable, made from C source code, that was susceptible to buffer overflow attacks (which you could cause by using objdump and smashing the stack). If you didn't have access to the source code for said executable, what are some methods you could use to stop your attack from working? Edit: When you run the executable, you are prompted for a file name to compress. You give it the file name and it zips it up for you.
write a wrapper program that pipes the input and output for 'badprog' through it and ensure the correct lengths and / or contents of the inputs
I'm running Debian on an x86_64 Intel processor. gcc (Debian 8.3.0) compiles the following program ``` #include <stdio.h> #include <stdalign.h> #include <stddef.h> int main(){ printf("%zd\n",alignof(max_align_t)); } ``` and outputs ``` 16 ``` What datatype requires a 16 byte alignment?
On x86_64,_Alignof(long double)==16.
I am getting core dump by this little programm. ``` #include <dirent.h> int main(void) { printf("process n%s",(long)getpid()); exit(0); } ``` can you explain me why?
You need to know where your functions come from, what they're returning and how to print the return value. ``` #include <unistd.h> #include <stdio.h> int main(void) { printf("process n%ld", (long)getpid()); } ```
u and v are unsigned integers ``` for (shift = 0; ((u | v) & 1) == 0; ++shift) { u >>= 1; v >>= 1; } ``` I cannot understand ((u | v) & 1) == 0 logic, what if u = 9 and v = 10, what would be the return of the logic function.
Ifu = 9, then the binary bit representation ofuis...1001. Ifv = 10, then the binary bit representation ofvis...1010. If you binary-or these values using|, you will get...1011. If you now binary-and the above value with1(i.e. binary...0001), you will get...0001. Finally, if you compare binary...0001to0using==, the values are different and therefore the result of the==operator will be0.
Since I could not find any documentation, does anyone know what clock is used on macOS to return value for ancillary headerSCM_TIMESTAMP_MONOTONICwhenSO_TIMESTAMP_MONOTONICis set? From tests, seems that it could beCLOCK_MONOTONIC_RAWwhich would make sense, but it could also beCLOCK_UPTIME_RAWbut that would be a weird choice since it does not advance during sleep? I assume that forSO_TIMESTAMPthe return ofgettimeofdayis used?
WhenSO_TIMESTAMPis set,getmicrotime()is used. WhenSO_TIMESTAMP_MONOTONICis set,mach_absolute_time()is used. Source:https://opensource.apple.com/source/xnu/xnu-6153.61.1/bsd/netinet/ip_input.c
I have implemented the following function in which it gets the path of a file and then tries to delete it from the file system. The function doesn't work properly, because when I call it to remove a file, the file will not be deleted until I close the program. When I close the program, the file that I specified will be deleted. I don't know what is wrong with the code: ``` bool DeleteFileOnSystem(const char* arg_path, const char* arg_name_file) { char c_FilePath[MAX_PATH]; strcpy_s(c_FilePath, MAX_PATH, arg_path); strcat(c_FilePath, arg_name_file); if (DeleteFile(c_FilePath)) return true; else return false; } ```
It does delete file and nothing is wrong. Apparently your program opens file somewhere else and does not close it. So the handle stays open until program exists. Make sure you close your file handles. This behavior ofDeleteFileis a feature, not a bug.
as a beginner in learning embedded softwares ,I can not understand thenuance between reserved memory and allocated memory, can anybody help me ?
In your quoted paragraph, they are only talking about the call stack (which is one of the possible types of memory). The call-stack has a maximum size that is "reserved" at compile time, but it is mostly unused when the program starts. Your local variables and function calls get pushed onto the stack when you make a function call -- that temporarily "allocates" memory until the function returns -- then it is "deallocated". If you allocate more memory than you reserved -- for example with an infinite recursion, then your program will have a ....... Stack Overflow Error.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed3 years ago.Improve this question Can someone explain what is happening at every step? I know the final output is 140.5, but I am unsure why that is. What is happening at each line that is resulting in 140.5? ``` #define PI 3.1 #define calcCircleArea(r) (PI * (r) * (r)) #define calcCylinderArea(r,h) (calcCircleArea(r) * h) int main() { double i = calcCylinderArea(3.0,5.0 + 1); printf("%g", i); } ```
Step 0 ``` calcCylinderArea(3.0,5.0+1) ``` Step 1 ``` (calcCircleArea(3.0)*5.0+1) ``` notice that it is not(5.0+1).Problem begins here. Step 2 ``` ((PI*(3.0)*(3.0))*5.0+1) ``` Step 3 ``` ((3.1*(3.0)*(3.0))*5.0+1) ```
``` #include <stdio.h> main() { int n=10; for(int a=n;a>=1;a++) //for bringing out numbers from 1-10 { int e=a%2; //int e to figure out if the number is even(divisible by 2) if(e==0) printf("%d\n",a); //printing the even numbers } } ``` I am new to programming. Learning C. Here I am trying to make a program that prints even numbers till 10. Executing this code leads to endless even numbers starting from 10. Can't seem to figure out the logic error here. Some help, please?
The logic for the for loop is not correct. ``` int n = 10; for(int a = 0; a <= n; a++) { if(a%2==0){ printf(a); } } ``` Notice that this is stating at 0, because in CS almost all the time the count starts at 0.
I have defined a struct (let call it test) in file a.h, this struct should be used by many files. In the file b.h I need to use this struct, but not as a pointer (struct test a[32]and notstruct test* a) as one of the attributes of another struct (let call it test_container). but I'm receivingerror: array type has incomplete element type. I'm guessing it happening because the compiler does not know the test struct, so it can't determent how much space does test_container required. so I'm trying to add#include <a.h>in b.h, but then I'm receivingfatal error: a.h: No such file or directory. both files are in the same directory. what is the problem?
Use#include "a.h"to include your own.h. By the way you should post real code instead of description.
Let's say i've a .txt file where i store a list of patient with their personal data. ``` Region Unique Hospital Code Surname Name FiscalCode/ID Patient Status X 006 Rossi Mario RSSRMA56B76B249P 0 ``` This is my enum ``` enum patientStatus { HomeCare=0, HospitalCare, SubIntensiveCare, IntensiveCare, Recovered }; ``` Should i use %d to print that enum?
I'd always save the stringified form of the enumerator value to a file, e.g."HomeCare","HospitalCare", &c. In this way you guard against theenumvalues having a different backing type, or even being reordered during program refactoring. And one can read the file too without having to consult a manual. Of course there will be some overhead in converting the string into the enumerator, so there's some work to do there. But performance wise, I/O will still be the bottleneck.
Since the C language doesn't have a half float implementation, how do you send data to the ONNXRuntime C API?
There's possibly an example you can follow linked from here:https://github.com/microsoft/onnxruntime/issues/1173#issuecomment-501088662 You can create a buffer to write the input data to using CreateTensorAsOrtValue, and access the buffer within the OrtValue using GetTensorMutableData. ONNXRuntime is using Eigen to convert a float into the 16 bit value that you could write to that buffer. ``` uint16_t floatToHalf(float f) { return Eigen::half_impl::float_to_half_rtne(f).x; } ``` Alternatively you could edit the model to add a Cast node from float32 to float16 so that the model takes float32 as input.
I wrote the program that came up with the first n terms of the hofstadter q sequence. (1,1,2,3,3,4...) Now I have to come up with the biggest term of this series. I wrote this code, but it didn't work. (for exapmle I want to first 5 term of this sequence.1 1 2 3 3 that is okay.Now I find biggest value of this array so 3) I have to useint(arr[ ],int index,int maximum). How can I fix it? ``` } ```
``` int maximum=arr[0]; ``` Here, you assignmaximumtoarr[0]. At the moment you assign the value,arr[0] = 0, somaximumis always equal to0. You have to assignmaximumto the return value offmfunction: ``` maximum = fm(arr,0,n); ```
I have defined a struct (let call it test) in file a.h, this struct should be used by many files. In the file b.h I need to use this struct, but not as a pointer (struct test a[32]and notstruct test* a) as one of the attributes of another struct (let call it test_container). but I'm receivingerror: array type has incomplete element type. I'm guessing it happening because the compiler does not know the test struct, so it can't determent how much space does test_container required. so I'm trying to add#include <a.h>in b.h, but then I'm receivingfatal error: a.h: No such file or directory. both files are in the same directory. what is the problem?
Use#include "a.h"to include your own.h. By the way you should post real code instead of description.
Let's say i've a .txt file where i store a list of patient with their personal data. ``` Region Unique Hospital Code Surname Name FiscalCode/ID Patient Status X 006 Rossi Mario RSSRMA56B76B249P 0 ``` This is my enum ``` enum patientStatus { HomeCare=0, HospitalCare, SubIntensiveCare, IntensiveCare, Recovered }; ``` Should i use %d to print that enum?
I'd always save the stringified form of the enumerator value to a file, e.g."HomeCare","HospitalCare", &c. In this way you guard against theenumvalues having a different backing type, or even being reordered during program refactoring. And one can read the file too without having to consult a manual. Of course there will be some overhead in converting the string into the enumerator, so there's some work to do there. But performance wise, I/O will still be the bottleneck.
Since the C language doesn't have a half float implementation, how do you send data to the ONNXRuntime C API?
There's possibly an example you can follow linked from here:https://github.com/microsoft/onnxruntime/issues/1173#issuecomment-501088662 You can create a buffer to write the input data to using CreateTensorAsOrtValue, and access the buffer within the OrtValue using GetTensorMutableData. ONNXRuntime is using Eigen to convert a float into the 16 bit value that you could write to that buffer. ``` uint16_t floatToHalf(float f) { return Eigen::half_impl::float_to_half_rtne(f).x; } ``` Alternatively you could edit the model to add a Cast node from float32 to float16 so that the model takes float32 as input.
I wrote the program that came up with the first n terms of the hofstadter q sequence. (1,1,2,3,3,4...) Now I have to come up with the biggest term of this series. I wrote this code, but it didn't work. (for exapmle I want to first 5 term of this sequence.1 1 2 3 3 that is okay.Now I find biggest value of this array so 3) I have to useint(arr[ ],int index,int maximum). How can I fix it? ``` } ```
``` int maximum=arr[0]; ``` Here, you assignmaximumtoarr[0]. At the moment you assign the value,arr[0] = 0, somaximumis always equal to0. You have to assignmaximumto the return value offmfunction: ``` maximum = fm(arr,0,n); ```
Let's say i've a .txt file where i store a list of patient with their personal data. ``` Region Unique Hospital Code Surname Name FiscalCode/ID Patient Status X 006 Rossi Mario RSSRMA56B76B249P 0 ``` This is my enum ``` enum patientStatus { HomeCare=0, HospitalCare, SubIntensiveCare, IntensiveCare, Recovered }; ``` Should i use %d to print that enum?
I'd always save the stringified form of the enumerator value to a file, e.g."HomeCare","HospitalCare", &c. In this way you guard against theenumvalues having a different backing type, or even being reordered during program refactoring. And one can read the file too without having to consult a manual. Of course there will be some overhead in converting the string into the enumerator, so there's some work to do there. But performance wise, I/O will still be the bottleneck.
Since the C language doesn't have a half float implementation, how do you send data to the ONNXRuntime C API?
There's possibly an example you can follow linked from here:https://github.com/microsoft/onnxruntime/issues/1173#issuecomment-501088662 You can create a buffer to write the input data to using CreateTensorAsOrtValue, and access the buffer within the OrtValue using GetTensorMutableData. ONNXRuntime is using Eigen to convert a float into the 16 bit value that you could write to that buffer. ``` uint16_t floatToHalf(float f) { return Eigen::half_impl::float_to_half_rtne(f).x; } ``` Alternatively you could edit the model to add a Cast node from float32 to float16 so that the model takes float32 as input.
I wrote the program that came up with the first n terms of the hofstadter q sequence. (1,1,2,3,3,4...) Now I have to come up with the biggest term of this series. I wrote this code, but it didn't work. (for exapmle I want to first 5 term of this sequence.1 1 2 3 3 that is okay.Now I find biggest value of this array so 3) I have to useint(arr[ ],int index,int maximum). How can I fix it? ``` } ```
``` int maximum=arr[0]; ``` Here, you assignmaximumtoarr[0]. At the moment you assign the value,arr[0] = 0, somaximumis always equal to0. You have to assignmaximumto the return value offmfunction: ``` maximum = fm(arr,0,n); ```
I've the question abouttypedefstatement. Hereis the code how i always write this statement: ``` typedef struct name { }name_t; ``` And here is the another example how i can write that: ``` typedef struct { }name; ``` Question is: what is purpose of that ways?
You need to use the first format if you have to refer to the type before thetypedefis completed. This is necessary if the structure contains a pointer to the same type. This comes up when defining linked lists. ``` typedef struct name { int value; struct name *next; }name_t ``` You can't usename_t *next;inside the structure declaraction, becausename_tisn't defined until later.
MPI_Comm_sizereturns the number of MPI processes. Obviously that cannot be negative. Is there a specific reason for returning an signedintas opposed to and unsigned one? The documentation does not mention a possible returned negative value.
The return value is a status/error code, but yes the size ptr is expected to be a ptr to int. I can't be sure, but this is probably mainly due to legacy, but it is consistently used, such that you can easily have an integer loop from 0 to comm_size, and pass the iterator to e.g. MPI_Comm_rank which also expects a ptr to int.
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 having trouble with the following line of code. ``` //check number of words if ((isblank(s[i]) != 0 && isblank(s[i+1] == 0))) words++; ``` I would like to count the number of "blanks" that is followed by a non-blank, but combining these 2 isblanks do not seem to count correctly. Could someone please help me out?
I think it is a typo problem, your bracket is not in the correct place. In this case theisblank()function getTRUEparameter if thes[i+1]is equal to 0, otherwiseFALSE: isblank(s[i+1] == 0) I believe you wanted the to write the following:isblank(s[i+1]) == 0
hello everyone I'm puzzled why this function returns 0 every time. I use arr[0] as index and define it size of array in main func. ``` int sum_array (int arr[]) { int result; arr[0] = arr[0]-1; if(arr[0]<=0){ return 0; } result = ((sum_array(arr))+(arr[arr[0]])); return result; } ``` If I useif(arr[0]<=1)instead ofif(arr[0]<=0)it returns 5. I also don't get why it returns 5. ``` array = {0,1,1,2,3,3,4} ```
the following proposed code: uses recursionperforms the desired functionality and now, the proposed code: ``` int sum_array (int arr[]) { if(arr[0]<=0) { return 0; } else { int index = arr[0]; arr[0]--; return arr[ index ] + sum_array( arr ); } } ```
I tried to implement Quicksort. It works fine except when there is a duplicate key, in which case there is an infinite loop and it never terminates. Can you help me understand what I am doing wrong? ``` // quick sort void quickSort(int arr[], const unsigned size) { // base case if (size < 2) return; int pivot = arr[size / 2]; unsigned L = 0, U = size - 1; // partitioning while (L < U) { while (arr[L] < pivot) L++; while (arr[U] > pivot) U--; swap(&arr[L], &arr[U]); } quickSort(arr, L); // sort left array quickSort(&arr[U + 1], size - L - 1); // sort right array } ```
You have theless thanandgreater thanconditions. But there is no condition for=. This is why it will run an infinite loop. Change them to<=and>=.
I am trying to include#include <pthread.h>in my project which uses CLion but I am cannot use it directly. Is there any specific way to include pthread to a C project?
I finally came up with a solution. Since I am using MinGW I Used MinGW installation manager and install packages that need to execute pthreads and openmp related tasks in CLion. Here is the procedure. After opening the installation manager go to all packages and select the select packages named using mingw32-pthreads-w32 and select them for installation. Then go to the installtion -> Apply changes to install new packages. The you can use pthread.h and omp.h inside your c or c++ program without any problem.
I am experiencing an issue with O_DIRECT. I am trying to use it withopen(), but I get an error like: ``` error: O_DIRECT undeclared (first use in this function) ``` I am including<fcntl.h> I grepped/usr/include/directory forO_DIRECTand it exists inx86_64-linux-gnu/bits/fcntl-linux.h. I tried to include this file instead, but then I get this error: ``` error: #error Never use <x86_64-linux-gnu/bits/fcntl-linux.h> directly; include <fcntl.h> instead. ``` I am trying to all of this in Eclipse CDT project on newly installed Ubuntu 20.04 system.
You should define_GNU_SOURCEbefore including<fcntl.h>or add-D_GNU_SOURCEto your compiler command. Note that this reduces portability of your program.
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 having trouble with the following line of code. ``` //check number of words if ((isblank(s[i]) != 0 && isblank(s[i+1] == 0))) words++; ``` I would like to count the number of "blanks" that is followed by a non-blank, but combining these 2 isblanks do not seem to count correctly. Could someone please help me out?
I think it is a typo problem, your bracket is not in the correct place. In this case theisblank()function getTRUEparameter if thes[i+1]is equal to 0, otherwiseFALSE: isblank(s[i+1] == 0) I believe you wanted the to write the following:isblank(s[i+1]) == 0
This question already has answers here:Is it optional to use struct keyword before declaring a structure object?(3 answers)Closed3 years ago. I tried typing the following code in a simple C project, but it keeps saying that MyStruct is undefined – unless I addstructbefore everyMyStruct(i.e.struct MyStruct my_struct;which just feels wrong?). ``` struct MyStruct { int my_int; } int main() { MyStruct my_struct; my_struct->my_int = 1; return 0; } ```
It’s not wrong, it’s the way C works. Type name isstruct MyStruct(it would be simplyMyStructin C++). If you feel that inconvenient, make a typedef, like: ``` typedef struct MyStruct { ... } MyStruct; ``` That may or may not be considered a good practice, though. Also note that a struct (but not a typedef) and a function can have the same name (without thestructprefix).sigactionis a real-word example of that.
Recently I have been watching a lot of socket programming tutorials for C. In every single one of those videos, the header filesys/typesis included, but when I run the code that is written in the video without thesys/types, I get no warnings or errors. What does this header file do and why is it so common?
That file defines many types used in other files. On older systems, it was necessary to include itbeforeother system headers. From a man page for thesocketsyscall: ``` SYNOPSIS #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> int socket(int domain, int type, int protocol); ... NOTES POSIX.1 does not require the inclusion of <sys/types.h>, and this header file is not required on Linux. However, some historical (BSD) implementations required this header file, and portable applications are probably wise to include it. ```
I want the user to input a height in range 2-8 inclusive if any other number is entered it should re-prompt user ... i have tried ``` int main(void) { int height; do{ height = get_int("Enter The Height: "); } while (height<=1 && height<=9); return height; } ``` the program runs with no errors but even if I input 9 it does not re-prompt me..
You want to ask again as long as the height is outside of the desired range. So you want to ask again as long as the height is less than the minimum or greater than the maximum. ``` do { ... } while (height < 2 || height > 8); ``` You were using&&where you should have be using||, and<=where you should have been using>=.
I have a sketch written in Arduino IDE which monitors on 2 RXs pins signal data and writes it to Serial Monitor. I have a problem that it from 1 RX the data are always written twice, but another RX (response) is OK, what could be the problem? So I don't think it is problem in program of MCU.
Your SIM800L module may have Command Echo enabled. You can send the following commands to change it: ``` ATE0 // Disable echo temporarily; After SIM800 reset, saved setting will be used. ATE1 // Enable echo temporarily; After SIM800 reset, saved value will be used. ATE0&W // Disable echo and save setting ATE1&W // Enable echo and save setting ``` Reference:SIM800_Series_AT_Command_Manual(page 35, page 355 end)
I have import and tested this project: https://github.com/android/ndk-samples/tree/master/hello-jni in Android Studio and worked well. But when I copy the code for another new project I have the follow error: “Incompatible point typesjclassand `jobject” In this line: ``` g_ctx.mainActivityClz = (*env).NewGlobalRef(clz); ``` enter image description here Is it not possible to use “NewGlobalRef” to create a new reference for a class in more recent versions?
NewGlobalRefalways returns ajobjecteven though you're giving it ajclass(which is a subclass ofjobject). You can solve this warning by explicitly downcasting tojclass, either as ``` (jclass)env->NewGlobalRef(...) ``` or ``` static_cast<jclass>(env->NewGlobalRef(...) ```
IsNPTLfromglicsource tree the canonicallibpthreaddistribution forpthread? Want to make sure because there's also an ambiguouslibpthreadnamed project hosted onHurd.
There is no such thing as "canonical libpthread" -- it is different on different platforms. On Linux, GLIBC provides POSIX thread implementation as part of it (in thenptldirectory), and that's what most Linux programs use. But it's possible to use other C libraries (uClibc, dietlibc, Musl), and they providetheir ownthread implementation. It would generallynotwork to try to link NPTL with Musl (or any other non-GLIBC libc implementation). On Solaris, or AIX, or HP-UX, the POSIX thread implementation is completely different and hasnothingto do with NPTL (or any other open-source implementation). there's also an ambiguous libpthread named project hosted on Hurd. That looks like a fork of GLIBC with Hurd-specific patches.
This question already has answers here:Precedence between member access from a pointer and cast(2 answers)Closed3 years ago. I tried to castconst void*tostruct struct_name*in the following code: ``` int struct_cmp (const void *a, const void *b) { return (struct struct_name*)a->number-(struct struct_name*)b->number; } ``` But the cast does not work and the compiler returnerror: request for member ‘number’ in something not a structure or unionCould anyone please explain why it does not work and how to fix it?
That's the right syntax: ``` ((struct struct_name*)a)->number ``` And as @Zan pointed, you're missing a * in b.
For glibc <= 2.23, it looks like the generic definition of malloc'smutex_lockmacro uses anintas a mutex.1means in use, and0means free. It defines this generic set of macros: ``` typedef int mutex_t # define mutex_init(m) (*(m) = 0) # define mutex_lock(m) ({ *(m) = 1; 0; }) # define mutex_trylock(m) (*(m) ? 1 : ((*(m) = 1), 0)) # define mutex_unlock(m) (*(m) = 0) ``` Formutex_lock(m), what purpose does0;serve?
The expression({ *(m) = 1; 0; })is a GCC extension to standard C, and it's called astatement expression. It allows you to have multiple arbitrary statements inside an expression. But all non-void expressions must result in a value, and for statement expressions [t]he last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct So the last0;is simply the result of the expression.
I have the following code: ``` int main() { char** a = {"bob", "alex", "john"}; for (int i = 0; i < 3; i++) { printf('%d', sizeof(a[i])); } } ``` What I try to do here, is to initialize an array of string, iterate through it and print the size for each word of it. But I get segmentation error. What is wrong with my approach ?
Here is a working code: ``` #include <stdio.h> int main() { char* a[3] = {"bob", "alex", "john"}; for (int i = 0; i < 3; i++) { printf("%d\n", strlen(a[i])); } } ``` Notice that the differences arechar* a[3]instead ofchar**,"%d"instead of'%d'andstrleninstead ofsizeof.
For glibc <= 2.23, it looks like the generic definition of malloc'smutex_lockmacro uses anintas a mutex.1means in use, and0means free. It defines this generic set of macros: ``` typedef int mutex_t # define mutex_init(m) (*(m) = 0) # define mutex_lock(m) ({ *(m) = 1; 0; }) # define mutex_trylock(m) (*(m) ? 1 : ((*(m) = 1), 0)) # define mutex_unlock(m) (*(m) = 0) ``` Formutex_lock(m), what purpose does0;serve?
The expression({ *(m) = 1; 0; })is a GCC extension to standard C, and it's called astatement expression. It allows you to have multiple arbitrary statements inside an expression. But all non-void expressions must result in a value, and for statement expressions [t]he last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct So the last0;is simply the result of the expression.
I have the following code: ``` int main() { char** a = {"bob", "alex", "john"}; for (int i = 0; i < 3; i++) { printf('%d', sizeof(a[i])); } } ``` What I try to do here, is to initialize an array of string, iterate through it and print the size for each word of it. But I get segmentation error. What is wrong with my approach ?
Here is a working code: ``` #include <stdio.h> int main() { char* a[3] = {"bob", "alex", "john"}; for (int i = 0; i < 3; i++) { printf("%d\n", strlen(a[i])); } } ``` Notice that the differences arechar* a[3]instead ofchar**,"%d"instead of'%d'andstrleninstead ofsizeof.
my issue: when I compile and build my program in C (using gcc compiler and geany as editor), no problem, fil object and executable are fine. But when I try to execute from Geany or manually from Prompt (as Admin), I get this kind of error. It became to appear after installing Visual Studio, I don't know if it causes some issue like this. Before its installation I had no problem. I've set all kinds of permission, r/w files and dirs, but everytime I go view Property File of my .exe I find "Read Only" permission. Then, I try to execute, Promt give me exit error code 5 and my .exe file have been deleted automatically. How can I solve this problem? Thanks all folks.
Exit error code 5 means access denied. Together with the executable being deleted automatically, that points to your antivirus being at fault. Replace it with a better one.
Hereyou'll find the following statement: #importis not a well designed feature. It requires the users of a header file to know that it should only be included once. What is the problem with this?
The article states the problem pretty exactly: If you write a header with the intention that it's been used with #import (aka without any include guards/etc), then youexpectthe user of that header file to use #import or other means to make sure that the file is only included once. If the user doesn't know that, or if the header is used with a compiler that doesn't support #import (or does something else with that command), then your header will not work properly. And, especially in big projects with many people working on it, there's a good chance that someday someone might accidantally #include that header instead, or that the project gets ported to a different compiler some time in the future.
In C we cannot assignint variable = true;, where as the below code executes. ``` typedef struct mystruct { int variable; } mystruct_; int main(void){ // Your code here! mystruct_ st = {true}; printf("%i",st.variable); } ``` Why true isn't valid value forint variable = true, but is valid for anintmember in a struct? Can someone please explain why?
In C we cannot assignint variable = true; This is not correct. It compiles and run successfully. The following code compiles and runs perfectly on GCC. ``` #include <stdio.h> #include <stdbool.h> typedef struct mystruct { int variable; } mystruct_; int main(void){ int variable = true; mystruct_ st = {true}; printf("%i %i",st.variable, variable); } ``` By the way, thestdbool.hcontains the following: ``` #define true 1 #define false 0 ``` That's why it should work withint.
What's the difference between the implementation ofstrstr()andstd::string::find()? Eg: ``` char* str = "abc\0hijk@#$%"; char* temp; std::string str1; for (int i=0; i <=12; i++) { str1.push_back(str[i]); } strstr(temp, "@#");// can not handle'\0' str1.find("@#");// success ```
Thestd::stringclass is a C++ class that represents a string which can contain a null character. Its member functions, likefind, are designed to handle those embedded nulls. strstr(a function from C) works withchar*pointers, which point to C-style strings. Because C-style strings are null-terminated, they cannot handle embedded nulls. To this effect,strstris documented as follows: Locate substringReturns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.The matching process does not include the terminating null-characters, but it stops there. The italicized part is relevant here.
I was wondering whether clang's new amazing custom size (things like 13-bit int, or 70-bit int, etc.) will get added to gcc.
Well. C23 has finally implemented them as_BigInt