question
stringlengths
25
894
answer
stringlengths
4
863
I am fairly new to C. I am trying to compile a C program found at this link (based on a scientific publication): https://static-content.springer.com/esm/art%3A10.1038%2Fncomms11219/MediaObjects/41467_2016_BFncomms11219_MOESM262_ESM.txt but am experiencing difficulty. The issue arises because the custom header file has been placed with the C program itself for some odd reason. I need to know where the header file ends so that I can paste the entire header file into a fresh script to allow successful compilation. Could someone point me in the right direction?
You will have to split the.txtfile into two files. Lines 1 through 1974 should go into a.cfile. Lines 1975 through 3484 should go intopolygyny14.h. There are a few lines at the end of the.txtfile that can be discarded as they don't appear to contain valid C code.
I'm just trying out a BMI (body mass index) calculator in C, but I keep on getting 0 as the final answer. Here's the code: ``` #include <stdio.h> int main(){ int weight, height; printf("Enter your weight in kilograms: "); scanf("%d", &weight); printf("Enter your height in meters: "); scanf("%d", &height); printf("Your BMI(body's mass index) is %f\n", weight/height*height); return 0; } ``` It displays 0 as the result. I just need it to display the number with decimals (using%fand usingintfor weight and height).
Since the variables are integers, it's doing integer arithmetic, and returning an integer result. Printing an integer with%fcauses undefined behavior. Cast one of the variables to float to get a float result. ``` printf("Your BMI(body's mass index) is %f\n", (float)weight/(height*height)); ``` Also, you have the formula wrong, it should beweight/(height*height).
In my c programming homework I am asked toinitialize an array using an initializer list delimited by braces.I've googled every thing and I can't find an example of an initializer list delimited by braces. By the way, the array I am initializing is 2-D so if you could format your answer so that it is representative of a 2-D array, that would be very helpful. Thanks
Here's an example: ``` int a[ 2 ][ 3 ] = { { 5, 6, 7 }, { 10, 20, 30 } }; ```
I'm just trying out a BMI (body mass index) calculator in C, but I keep on getting 0 as the final answer. Here's the code: ``` #include <stdio.h> int main(){ int weight, height; printf("Enter your weight in kilograms: "); scanf("%d", &weight); printf("Enter your height in meters: "); scanf("%d", &height); printf("Your BMI(body's mass index) is %f\n", weight/height*height); return 0; } ``` It displays 0 as the result. I just need it to display the number with decimals (using%fand usingintfor weight and height).
Since the variables are integers, it's doing integer arithmetic, and returning an integer result. Printing an integer with%fcauses undefined behavior. Cast one of the variables to float to get a float result. ``` printf("Your BMI(body's mass index) is %f\n", (float)weight/(height*height)); ``` Also, you have the formula wrong, it should beweight/(height*height).
In my c programming homework I am asked toinitialize an array using an initializer list delimited by braces.I've googled every thing and I can't find an example of an initializer list delimited by braces. By the way, the array I am initializing is 2-D so if you could format your answer so that it is representative of a 2-D array, that would be very helpful. Thanks
Here's an example: ``` int a[ 2 ][ 3 ] = { { 5, 6, 7 }, { 10, 20, 30 } }; ```
``` #include<stdio.h> main() { int array[20]={1,5,10,15,20}; array[10]=*array+1; array[1]=*(array+2)++; array[5]=*(array+3)*array[4]; printf("array[10]=%d\narray[1]= %d\narray[5] = %d\n",array[10], array[1], array[5]); return 0; } ``` I got "Ivalue required as increment operand" error. What can I do to fix my codes?
In this statement ``` array[1]=*(array+2)++; ``` the right hand expression is equivalent to ``` array[1]=*( (array+2)++ ); ``` that is at first the postfix increment is applied to the temporary object (pointer)array + 2and its result (the pointer before incrementing) is dereferenced. You may not increment a temporary object. If you mean to post-increment the value of the pointed element then you should write ``` array[1] = ( *(array+2) )++; ``` If you want to pre-increment the value then you should write ``` array[1] = ++*(array+2); ```
I can't find proper way to get count of rows returned after successful execution of SELECT statement via ODPI-C. Hope you can help me. EDITED: There is a function ``` int dpiStmt_getRowCount(dpiStmt *stmt, uint64_t *count) ``` but it only returns the number of rows affected by the last DML statement that was executed or the number of rows currently fetched from a query.
This is not ODPI-C specific. Oracle Database doesn't provide this automatically on SELECT statements. You have to fetch the rows and then count them. Or run 'SELECT COUNT'.
I'm trying to get the input of a user in the followingparam1,param2,param3problem is that I'm not allowed to use scanf. I want to retrieve those 3 parameters into 3 different variables but: - I don't know how to get them because they're separated by a comma - I can't manage to use well sscanf and from what I've seen, I don't think fgets can help me. Ex: ``` char a1, a2, a3; printf("Enter data\n"); sscanf(input,"%[^,],%[^,],%[^,]", &a1, &a2, &a3); ``` I'm not asked to type the arguments that I want. Is there something I'm missing here ?
You can usefgetsandsscanflike: ``` char input[10]; char a1, a2, a3; if (fgets(input, sizeof input, stdin)) { if (sscanf(input, "%c,%c,%c", &a1, &a2, &a3) == 3) { // ok - go on and use a1, a2, a3 } else { // not good, the input doesn't match the pattern } } else { // not good, didn't get any input } ```
Title is pretty self-explanatory on what I want to do. My current try: ``` chdir("/Path/I/want/"); //this is different that the path my program is located at char * ls_args[] = { "ls" , "ls -l", NULL}; execv(ls_args[0], ls_args); } ``` I am not getting any errors or output, any help?
Execv function needs full path of the command which you have to execute. So, instead of giving"ls", you should find out where the ls is located in your system by $ which ls it will probably be in /bin folder. So you have to give"/bin/ls"to exec. Also any argument to ls should be another member in array. So instead of using char * ls_args[] = { "ls" , "ls -l", NULL}; use char * ls_args[] = { "/bin/ls" , "-l", NULL};
I am writing an application using ncurses and trying to get a CTRL-M keypress from the keyboard. Ncurses is returning CTRL-J (aka \n) whenever I press CTRL-M (aka \r), so I suspect somewhere it is doing a CRLF translation. My program is running in raw() mode so I don't think it should be doing any translation. Is this an ncurses problem or is it coming from somewhere upstrea, like the terminal driver? How can I get it to give me raw key presses without translation? FWIW I am using ncurses on Linux, running bash in xfce4-terminal. My TERM is xterm-256color. I've searched on Google and checked the ncurses docs but can't find anything on this issue.
You need to callnonl(). Although it is documented in theoutoptsmanual section, it affects input as well.
``` FILE*f; if ((f = fopen("tester.bin", "rb"))==NULL) { printf("File cannot be opened"); exit(1); } int *Number_Filep = (int*)malloc(sizeof(int)); fread(*(Number_Filep), sizeof(int), 1,f); printf("%d", *Number_Filep); FILE*fp; if ((fp = fopen("Data.txt", "w"))==NULL) { printf("File cannot be opened"); exit(1); } fprintf(fp,"Age: %d", *(Number_Filep)); fclose(fp); free(Number_Filep); fclose(f); ``` In the file, the number is 5, but when I run the console application, it shows a random big number. How to fix it, so that it reads the correct number?
fread's first argumentis a pointer, but you're calling it like this: ``` fread(*(Number_Filep), sizeof(int), 1,f); ``` ...so the first argument is*(Number_Filep)- an integer. This is not what you wanted to do. You should read like this: ``` fread(Number_Filep, sizeof(int), 1,f); ```
I am testing this piece of code in c ``` long long n = 1000000; long long var1,var2; int x = 50000; var1 = n * x * x; var2 = x * x * n; printf("var1 = %lld\n", var1); printf("var2 = %lld\n", var2); ``` When i run it produces this output ``` var1 = 2500000000000000 var2 = -1794967296000000 ``` I don't understand why changing the order of variables being multiplied produced an overflow.
In this case associativity is left to right, so what happens is: ``` var1 = (n * x) * x; var2 = (x * x) * n; ``` In case ofn * x, thexwill be converted tolong longsincenislong long, so it has a higher conversion rank. Therefore, this partial result will not overflow. But withx * x, both operands areinttherefore the result will beintas well, and that can't hold the value2,500,000,000, which causes the overflow.
This question already has answers here:Why does division result in zero instead of a decimal?(5 answers)Closed3 years ago. ``` #include <stdio.h> int main() { float a = 355/113; printf("%f", a); return 0; } ``` Why is this returning 3.0000 instead of 3.141592?
The division is being performed using integer arithmetic and the result of the division is converted to a float. If you want float division use floating point literals such as 355.0 and 113.0.
I'm trying to make a program which ask a user for their 16 digit credit card number. I want to store the users input into a long int variable. How do I read the users input without using scanf?
``` #include <stdio.h> #include <cs50.h> #include <stdlib.h> int main(void) { long cn; char buf[20]; do { printf("card number please: "); fgets(buf, 19, stdin); cn = strtol(buf, NULL, 0); } while (cn < 1); printf("%ld\n", cn); } ```
While debugging with lldb a macOS application, is it possible to watch the contents of a register for changes with a watchpoint ? I mean not the memory to which the address contained in the register points to, but the contents of the register itself, for example from 0x000000000 to 0x000000001 ? Thanks a lot for your help.
I don't think there's any way to get the processor to trap when a particular register changes value. In any case, not one that lldb has access to. Short of that, you'd have to instruction-single-step and check the value on each stop. That would work, but will be pretty slow.
``` void get_elemnts(int *array, int max_index){ for(int i = 0; i < max_index; i++){ printf("enter element 0%d: ", i); scanf("%d", array + i); } } ``` **scanf("%d", array + i);**Can someone explain? I have a code that gets the elements of an array from the user input. And at the moment I have difficulties with understanding what exactly this part of the code does
There are three concepts involved: scanf("%d", pointer)method will read the integer value (%d) fromstdinand write it to the memory referenced bypointer.Nature of arrays: arrays in C are stored linearly in memory: int array of sizenis justn * sizeof(int)bytes in memory and the variable of the array is the same as the pointer to its first element.Pointer arithmetic:array + imoves the pointer byimemory cells of type int which isi * sizeof(int)bytes. This is exactly where the i'th element of array is. Soarray + iis a pointer toarray[i].
``` #include <stdio.h> #include <stdlib.h> int main() { int i; char str[4]; scanf("%s",str); printf("%s",str); } ``` input scan output scan Here I declare an array of 4 characters. I used '%s' that is used for strings. I am not able to understand how can we input 4 char elements and get correct answer when one space should be utilized for the NULL character. The input should only work with up to 3 elements.
scanf()does not check its arguments. You could even enter more than 4 characters andscanf()would happily overwrite the memory area that comes after your array. After that, your program might crash or all kinds of funny things might happen. This is called a buffer overflow and it is a common cause of vulnerabilities in software.
If I have a char:char ch and i want to assign it a numeric value of a digit, for example, if the user enters 0, i want the char to have the value 0 ('\0') and not 48 ('0') if i tryscanf("c", &ch)it will assign48(ascii value for 0), and if i tryscanf("d", &ch)i get an error. I know it can be done by receiving it as string, and then converting it into char, and then usingch-'0'to get the numeric value, but is it possible without this extra steps?
assign numeric value of digit intocharusingscanf Since C99, the direct way is ``` char ch; scanf("%hdd", &ch); // or to insure reading only 1 character scanf("%1hdd", &ch); ``` Before that, the below is common.@Lundin ``` char ch; int ch_int; if (scanf("%d", &ch_int) == 1) { ch = ch_int; ``` Or read thecharand convert from its character value to its numeric value. (OP is already familiar with this) ``` char ch; scanf("%c", &ch); ch -= '0'; ```
What's wrong with my code? Why am I not getting any output?I'm practicing for embedded system. running code screenshot ``` #include <stdio.h> int checkP (int n) { for (int i=2; i<n; i++) if(n%i==0) return (0); return (1); } int nextP (int n) { do n++; while (!checkP(n)); return n; } int main (void) { int x = 34; //user input for (int i = 2; i < x - 1; i = nextP(i)) { if (checkP(x - 1)) { printf ("\n %d + %d", i, x-1); } } } ```
x-1is always33, you want to usex-i, so that the sum ofiandx-iisx. Theifshould look like that: ``` if (checkP(x - i)) { printf ("\n %d + %d", i, x-i); } ``` https://ideone.com/jAIfa2 Output: ``` 3 + 31 5 + 29 11 + 23 17 + 17 23 + 11 29 + 5 31 + 3 ```
``` #include <stdio.h> int printArray(a[], unsigned int n){ if (n == 4){ printf("%d", a[4]); } else { printf("%d", printArray(a,n+1)); // here is the error, I know. But why? } } int main(){ int a[5] = {1,2,3,4,5}; printArray(a,0); } ``` I am a begginer with C. I am trying to print each of the elements of the array, but it only prints the last one correctly, and not the former ones. I know there's something about recursive way wrong. It's the first time I use recursive way without return and using printf. Maybe is this that misleaded me? Output: ``` $ ./a.out 5 0 1 1 0 ```
You should print the array item, not the return value of the function, Use this code ``` int printArray(int *a, unsigned int n){ if (n == 4){ printf("%d", a[4]); } else { printf("%d", a[n]); printArray(a,n+1); } } ```
This question already has answers here:crash when free pointer to function(4 answers)Closed3 years ago. I'm learning about function pointer viathis page. As I know,free()function acceptsvoid *pointer, just asmalloc()returns. Since function pointers are also just pointer, I've just got curious. Is it possible, or legal to callfree()for function pointers? If so, what happens?
According todocumentation: Thefree()function frees the memory space pointed to byptr, whichmust have been returned by a previous calltomalloc(),calloc()orrealloc(). Otherwise, or iffree(ptr)has already been called before,undefined behavioroccurs. Undefined behaviormeans anything can happen, so don't do that. When programming in C or C++ we want to stay in the realm of defined behavior.
This question already has answers here:What does the number in parentheses shown after Unix command names in manpages mean?(7 answers)Closed3 years ago. Looking libunwind.h docs(https://www.nongnu.org/libunwind/docs.html), All functions(ex.libunwind-ia64(3), unw_get_proc_name(3)) have fnc name + (3). What means (3)?
The number refers to the section in the Linux manual that the documentation for these functions reside in. When using themancommand to look up documentation you can optionally specify the section, for exampleman unw_get_proc_nameorman 3 unw_get_proc_name. You would need to specify the section if there was a manual entry with that name in a different section. This practice goes back to the UNIX days. I've personally seen it going back to Solaris 2.5.1 (1994-1995), but it's probably older than that.
``` #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int x = 100, i; double D[x]; for(i=0; i < 100; i++) scanf("%f", D++); return 0; } ``` The code has two errors: "%f"rather then"%lf"- compilation errorD++- compilation error But why isD++an error? asDis a pointer to the first element of the array and++can be used on an array, like pointers?
Dis not a pointer to the first element of an array.Disan array, and an array "decays" into a pointer to its first element in most contexts. The++operator cannot be used on an array because it modifies its operand, and an array is not modifiable (although its element are).
ERROR: type should be string, got "\nhttps://en.wikipedia.org/wiki/Resource_acquisition_is_initialization\n\nThere is an example of how RAII works. I always thought that C++ gets this behavior from C. That when you define a variable in a function, that variable becomes invalid when you leave the function. Though maybe the concept has no meaning when there is no object. C does not initialize structs but C++ does. Is that the difference? I am a bit confused.\n"
I always thought that ... That when you define a variable in a function, that variable becomes invalid when you leave the function You've thought correctly. You seem to be confused about what RAII is for. It is for management of dynamic resources such as dynamic memory allocations. It relies on language features such a constructors and destructors, which do not exist in C.
I am currently writing a conditional statement that evaluates floating-point values. ``` float condition; if(condition) // then do something else // do something else ``` If condition is, say, 0.5 or 1/2, would the statement be considered True or False? In other words, would the program execute the "then" or the "else" portion?
If the condition is equal to 0, it is considered false, otherwise it is considered true. Section 6.8.4.1 of theC standardregarding theifstatement states: 1The controlling expression of anifstatement shall have scalar type2In both forms, the first substatement is executed if the expression compares unequal to 0 Floating point types are considered scalar types, so they are valid as the expression of anif. This also works for the values infinity and NaN, both of which compare unequal to 0.
This question already has answers here:How can I convince Eclipse CDT that a macro is defined for source code editing and code completion?(4 answers)Closed2 years ago. Where should I define preprocessors macros so that eclipse calls gcc with the-D marco=defarguments I tried withProject Properties > C/C++ General > Preprocessor Include, Path, Macros etc...but the arguments are not passed to the toolchain.
This setting is indeed located in Project Properties, but in C/C++ Build:
Whats means for "project"? And in follow statement "If a type is declared but not used, then it is unclear to a reviewer if the type is redundant or it has been left unused by mistake." Whats mean "if type is redundant"? What is a redundant type?
MISRA document does not contain a strict definition of the "project". Intuitively, a project can be defined as a collection of source files used to build a set of artifacts. Redundant type in this context means a type definition that is not used in the project sources. They can be easily detected using-Wunused-local-typedefsoption in the recent versions of gcc and clang.
I don't understand how to include average of digits in my code ``` #include <stdio.h> int main() { int n, s; printf("Enter number : "); scanf("%d",&n); s = 0; while (n > 0) { s += n%10; n /= 10; } printf("Sum of digit : %d\n",s); return 0; } ```
Try this: ``` #include <stdio.h> int main() { int n, s,i=0; printf("Enter number : "); scanf("%d",&n); s = 0; while (n > 0) { s += n%10; n /= 10; i++; } printf("Sum of digit : %d\n",s); if(i!=0) printf("Average is %f\n",(float)s/i); else printf("Average is Undefined\n"); return 0; } ```
I want to create a file on/dev/mmcblk0, if it doesn't exist already, and then write to it. My question is how to check if there is already such file on the sdcard and then access it, does it show up like/dev/mmcblk0/somefile?
/dev/mmcblk0points to a drive, so you will need to mount the drive first before you can see what files are available on it or create new files.
``` //myfuncs.h void func1(void); void func2(void; ``` I'm doing unit testing. Using CMock with ceedling, is there any way to mock func1(), but run func2() as it was originally written?
To my knowledge, you can't. You must split the header file into two and generate mocks for one of them. There are unit test frameworks that can mock one or more functions in a header file,Nala(which I'm maintaining) for example. But I guess you want to use CMock with Ceedling, so it's not really an option.
If we have a 32bit pattern of 1111 1111 1000 0000 0000 0000 0000 0000, which is -2^23 in int, when we convert int to float will this be -INF?
Conversions in C operate onvalues, and the value -2^23 is representable infloat, so the result of the conversion is the value -2^23.
I have been using atoi since an year ago and I got an issue in the recent days that the expression atoi("20") is giving a value of 0 as output. And when I went through google I came to know that it is deprecated and strtol have to be used. The interesting point I came to know is atoi internally uses strtol. So, how can the issue be solved when I change it to strtol?
The explication frommanpage: Theatoi()function converts the initial portion of the string pointed to by nptr to int. The behavior is the same as: strtol(nptr, NULL, 10); except that atoi() does not detect errors. The atol() and atoll() functions behave the same as atoi(), except that they convert the initial portion of the string to their return type of long or long long. For more infos, you can see the difference of two functions in this topicatoi - strtol
I want to have a fixed size integer of 64 bits in linux kernel. My questions: If I useunsigned long, then it may be 64-bit on one architecture and 32-bit on another. Right?What would be the data type the for fixed 64-bit integer? I am specifically referring to linux kernel
If I use unsigned long, then it may be 64-bit on one architecture and 32-bit on another. Right? Yes, the size ofunsigned longis implementation-defined and therefore non-portable. What would be the data type the for fixed 64-bit integer? int64_toruint64_t.
I was trying to do a program that analyzes poker hands, however I am extremely confused and I don't know where to start. The suits are represented by the lettersC(clubs),D(diamonds),H(hearts) andS(spades). The value of the cards is represented by the numbers and the lettersA(ace),2,3,4,5,6,7,8,9,T(ten),J(jack),Q(queen) andK(king). The program is supposed to receive input likeAS KC QC JH 9D. But the difficult part is that it should be able to receive 5, 7, 9 or 10 cards (strings with 2 chars). Note: each card is made of two chars (example:2C). Thank you in advance :)
I will offer incremental suggestions in this answer: To determine how many cards are in the hand/set: you can callstrlen(string)to count the number of characters in the string.Once you know how many cards are there, you can use aswitchstatement:switch(number_of_cards) { ... }to branch the processing logic into distinctcases.
``` #include <stdio.h> #include <stdlib.h> int main(void) { system("title ์„ธ์ œ๊ณฑ, ๋‚˜๋ˆ—์…ˆ"); int num1, num2, triple; float division; printf("์ •์ˆ˜๊ฐ’ 2๊ฐœ ์ž…๋ ฅ : "); scanf_s("%d %d", &num1, &num2); triple = num1 * num1 * num1; printf("์„ธ์ œ๊ณฑ ์—ฐ์‚ฐ ๊ฒฐ๊ณผ : %08d", &triple); division - (float)num1 / num2; printf("๋‚˜๋ˆ—์…ˆ ์—ฐ์‚ฐ ๊ฒฐ๊ณผ : %8.3f", &division); return 0; } ```
printf("๋‚˜๋ˆ—์…ˆ ์—ฐ์‚ฐ ๊ฒฐ๊ณผ : %8.3f", &division);The&before the variable name means you are printing the address of the variable, not the value of it. Tryprintf("๋‚˜๋ˆ—์…ˆ ์—ฐ์‚ฐ ๊ฒฐ๊ณผ : %8.3f", division); You need the&in thescanf_s, but not in theprintfs
I have this function that swaps integers passed by reference, it works fine in C++ but it does not work in C. ``` #include <stdio.h> void swap(int & x, int & y) { int z = x; x = y; y = z; } int main() { int a = 0, b = 1; swap(a, b); printf("a is now %d\n", a); printf("b is now %d\n", b); } ``` Why doesn't it work in C?
C and C++ have some overlap, but they are two different languages. C has no references. Even the claim that C++ is a superset of C is outdated. C has evolved since C++ started as "C with classes" and not all features added to C are also incorporated into C++. Hence it should not be too surprising that what works in one does not necessarily work in the other.
Why my tool for analysis of the rule for MISRA report a possible violation for this for loop ? For example ``` for(; i != 0 ; i = f(r) ) { int a = 9 + i; } ```
According to MISRA C 2012 document, the third clause of aforstatement shall be an expression whose only persistent side effect is to modify the value of the loop counter and it shall not use objects that are modified in theforloop body. These restrictions also apply to all functions called withinforstatement. From the code you provided, I can guess, thatf(r)function call contains side effects, such as modification of global variables orrargument. All other requirement described in rule 14.2 text are met.
I was trying to do a program that analyzes poker hands, however I am extremely confused and I don't know where to start. The suits are represented by the lettersC(clubs),D(diamonds),H(hearts) andS(spades). The value of the cards is represented by the numbers and the lettersA(ace),2,3,4,5,6,7,8,9,T(ten),J(jack),Q(queen) andK(king). The program is supposed to receive input likeAS KC QC JH 9D. But the difficult part is that it should be able to receive 5, 7, 9 or 10 cards (strings with 2 chars). Note: each card is made of two chars (example:2C). Thank you in advance :)
I will offer incremental suggestions in this answer: To determine how many cards are in the hand/set: you can callstrlen(string)to count the number of characters in the string.Once you know how many cards are there, you can use aswitchstatement:switch(number_of_cards) { ... }to branch the processing logic into distinctcases.
``` #include <stdio.h> #include <stdlib.h> int main(void) { system("title ์„ธ์ œ๊ณฑ, ๋‚˜๋ˆ—์…ˆ"); int num1, num2, triple; float division; printf("์ •์ˆ˜๊ฐ’ 2๊ฐœ ์ž…๋ ฅ : "); scanf_s("%d %d", &num1, &num2); triple = num1 * num1 * num1; printf("์„ธ์ œ๊ณฑ ์—ฐ์‚ฐ ๊ฒฐ๊ณผ : %08d", &triple); division - (float)num1 / num2; printf("๋‚˜๋ˆ—์…ˆ ์—ฐ์‚ฐ ๊ฒฐ๊ณผ : %8.3f", &division); return 0; } ```
printf("๋‚˜๋ˆ—์…ˆ ์—ฐ์‚ฐ ๊ฒฐ๊ณผ : %8.3f", &division);The&before the variable name means you are printing the address of the variable, not the value of it. Tryprintf("๋‚˜๋ˆ—์…ˆ ์—ฐ์‚ฐ ๊ฒฐ๊ณผ : %8.3f", division); You need the&in thescanf_s, but not in theprintfs
I have this function that swaps integers passed by reference, it works fine in C++ but it does not work in C. ``` #include <stdio.h> void swap(int & x, int & y) { int z = x; x = y; y = z; } int main() { int a = 0, b = 1; swap(a, b); printf("a is now %d\n", a); printf("b is now %d\n", b); } ``` Why doesn't it work in C?
C and C++ have some overlap, but they are two different languages. C has no references. Even the claim that C++ is a superset of C is outdated. C has evolved since C++ started as "C with classes" and not all features added to C are also incorporated into C++. Hence it should not be too surprising that what works in one does not necessarily work in the other.
Why my tool for analysis of the rule for MISRA report a possible violation for this for loop ? For example ``` for(; i != 0 ; i = f(r) ) { int a = 9 + i; } ```
According to MISRA C 2012 document, the third clause of aforstatement shall be an expression whose only persistent side effect is to modify the value of the loop counter and it shall not use objects that are modified in theforloop body. These restrictions also apply to all functions called withinforstatement. From the code you provided, I can guess, thatf(r)function call contains side effects, such as modification of global variables orrargument. All other requirement described in rule 14.2 text are met.
I have this function that swaps integers passed by reference, it works fine in C++ but it does not work in C. ``` #include <stdio.h> void swap(int & x, int & y) { int z = x; x = y; y = z; } int main() { int a = 0, b = 1; swap(a, b); printf("a is now %d\n", a); printf("b is now %d\n", b); } ``` Why doesn't it work in C?
C and C++ have some overlap, but they are two different languages. C has no references. Even the claim that C++ is a superset of C is outdated. C has evolved since C++ started as "C with classes" and not all features added to C are also incorporated into C++. Hence it should not be too surprising that what works in one does not necessarily work in the other.
Why my tool for analysis of the rule for MISRA report a possible violation for this for loop ? For example ``` for(; i != 0 ; i = f(r) ) { int a = 9 + i; } ```
According to MISRA C 2012 document, the third clause of aforstatement shall be an expression whose only persistent side effect is to modify the value of the loop counter and it shall not use objects that are modified in theforloop body. These restrictions also apply to all functions called withinforstatement. From the code you provided, I can guess, thatf(r)function call contains side effects, such as modification of global variables orrargument. All other requirement described in rule 14.2 text are met.
This question already has answers here:What does #x inside a C macro mean?(4 answers)Closed3 years ago. ``` #include <stdio.h> #define get(s) #s //*** int main() { char str[] = get(hello); //*** printf("%s\n", str); return 0; } ``` Help me to understand the two lines with the//***comment? Can anyone describe what's happening in the#define?
This is using the preprocessor'sstringificationfeature. You can read more about it athttps://en.cppreference.com/w/c/preprocessor/replaceunder "# and ## operators". The effect is that the second marked line expands to ``` char str[] = "hello"; ```
Is it possible that a function in ANSI C cannot be accessed from some other file? How and when functions have limited access? At first I thought that if a function is not included in any header it's private.But it doesn't seem to be the case.
Are all functions in c global? No. For one thing, what many call (sloppily)global, the C Language callsfile scopewithexternal linkage. Also, even in a translation unit (a fancy way to say "preprocessed C file"), a function identifier is only visible (in scope) from its declaration to the end of the translation unit (or even the enclosing block). To give a function identifierinternal linkage(so another function or object of the same name can exist in a different object file) you use thestatickeyword.
I'm trying to use the raylib on Visual Studio 2019, I followedthis tutorialI can build without anywarning, but when I run my program a error windows saying that it can't find "raylib.dll" apear. What can I do to solve this ?
I solve my issue by placing the raylib.dll that's inthis raylib distributionin the folder where my executable is build
I'm trying to return dynamically created char array from function. But returned array doesn't have characters i created in function. I'm using this code. ``` bool test(char** myCharArray) { char *response = malloc(2); response[0] = 'A'; response[1] = 'B'; *myCharArray = response; return true; } int main() { char* testArray; bool result = test(&testArray); char c1 = testArray[0]; char c2 = testArray[1]; // c1 is not equal to 'A' // c2 is not equal to 'B' } ``` What is the problem?
Problem was not related to my code. In MPLABX linker configuration 'Heap Size' was 0. When i write necessary value there problem solved.
I am trying to write a function that counts the number of characters in a string up until it finds 0, and only counts up until then. For example, if we have a string "hello0bye", it will only count the number of characters in "hello". I know there is strlen, but I'm unsure of how to implement the 0 in this. I'm trying to write this using either a for loop or a while loop. Thank you!
Something like this? #include <stdio.h> #include <stdlib.h> int count_char_until_zero(char *str); int main() { int i = count_char_until_zero("kaja0pia"); printf("Char num until zero: %d\n", i); return 0; } int count_char_until_zero(char *str) { int i = 0; while(str[i] != '0') { i++; } return i; }
I'm trying to return dynamically created char array from function. But returned array doesn't have characters i created in function. I'm using this code. ``` bool test(char** myCharArray) { char *response = malloc(2); response[0] = 'A'; response[1] = 'B'; *myCharArray = response; return true; } int main() { char* testArray; bool result = test(&testArray); char c1 = testArray[0]; char c2 = testArray[1]; // c1 is not equal to 'A' // c2 is not equal to 'B' } ``` What is the problem?
Problem was not related to my code. In MPLABX linker configuration 'Heap Size' was 0. When i write necessary value there problem solved.
I am trying to write a function that counts the number of characters in a string up until it finds 0, and only counts up until then. For example, if we have a string "hello0bye", it will only count the number of characters in "hello". I know there is strlen, but I'm unsure of how to implement the 0 in this. I'm trying to write this using either a for loop or a while loop. Thank you!
Something like this? #include <stdio.h> #include <stdlib.h> int count_char_until_zero(char *str); int main() { int i = count_char_until_zero("kaja0pia"); printf("Char num until zero: %d\n", i); return 0; } int count_char_until_zero(char *str) { int i = 0; while(str[i] != '0') { i++; } return i; }
I'm writing a script in C and I execute it with the&in order to run it on the background. I need to terminate the program with ctrl-z (SIGTSTP) There is a main loop that intentionally prevents the script from terminating. I need to terminate it with ctrl-z and ctrl-z will not respond while the process is running the background. How can I send the signal(from terminal) to the background process and how can I manipulate it?
You have to handle the signal and terminate the program when you receive the signal SIGTSTP. To understand what I'm talking about:C signal handling - Wikipedia Any guide/manual about handling signals in C should help you. P.S.: you can terminate the program in any moment with functionexit()from<stdlib.h>.
Let's say I have a filetest.cwhich accepts a text file and starts as follows: ``` int main(int argc, char **argv) { ... return 0; } ``` I will typically compile the file and execute the binary as follows:./test input.txt. Now, I wish to call themainfunction programmatically in another function in the same file. How should I proceed?
You can do this as follows: ``` #include <stdio.h> int main(int argc, char *argv[]); void func() { char *argv[] = { "./test", "another.txt", NULL }; main(2, argv); } int main(int argc, char *argv[]) { if (argc > 1) { printf("Processing %s...\n", argv[1]); } /* ... */ func(); return 0; } ``` This should output something like: ``` Processing input.txt... Processing another.txt... ``` Beware of endless recursion!
I got an assignment in which I can use any method, as long as it is part of the ANSI - c standard. I want to usefreopen, except I don't know if its part of the standard. I have looked at "The C programming language" book's list of methods and it doesn't seem to be there, but it was in C89 so I doubt it isn't in ANSI.
freopen()functionconforms to C89. And C89 isANSI C.
This question already has answers here:Segmentation fault on large array sizes(7 answers)Closed3 years ago. I have an array populated with integers: ``` #include <stdio.h> #define MAX 4000000 int main() { int primes[MAX + 1]; // init array with all numbers for(int i = 1; i <= MAX; i++) primes[i] = i; return 0; } ``` With 4 byte integers, it seems this should only use up 4M * 4 or 16 MB. But I'm getting a segmentation fault when I run this program. I don't understand why.
As with any structure too large to accommodate on the stack, the solution is to dynamically allocate: ``` #include <stdio.h> #include <stdlib.h> #define MAX 4000000 int main() { int* primes = calloc(MAX + 1, sizeof(int)); // init array with all numbers for(int i = 1; i <= MAX; i++) primes[i] = i; free(primes); return 0; } ```
I have a function which returns some value and some parameters: ``` uint8 myFunction(uint8* param1); uint8 myFunction(uint8* param1) { *param1 = 3; return 1; } ``` Later in my code I would like to use the function once with returning a value like: ``` uint8 a; uint8 b; a = myFunction(b); ... ... ``` and once with just ignoring the parameter, like: ``` a = myFunction(void); ``` How to do this in C?
I'd recommend adding a NULL check before dereferencingparam1- that would be wise anyway. Then you can just pass NULL where you want to ignore it. ``` uint8 myFunction(uint8* param1) { if (param1 != NULL) { *param1 = 3; } return 1; } ``` calling code can then just passNULL: ``` a = myFunction(NULL); ``` Of course, it would be good to clearly document this behavior.
I have a function which returns some value and some parameters: ``` uint8 myFunction(uint8* param1); uint8 myFunction(uint8* param1) { *param1 = 3; return 1; } ``` Later in my code I would like to use the function once with returning a value like: ``` uint8 a; uint8 b; a = myFunction(b); ... ... ``` and once with just ignoring the parameter, like: ``` a = myFunction(void); ``` How to do this in C?
I'd recommend adding a NULL check before dereferencingparam1- that would be wise anyway. Then you can just pass NULL where you want to ignore it. ``` uint8 myFunction(uint8* param1) { if (param1 != NULL) { *param1 = 3; } return 1; } ``` calling code can then just passNULL: ``` a = myFunction(NULL); ``` Of course, it would be good to clearly document this behavior.
I am trying to get two random numbers between 0 and 11 but i get the same number whenever i execute my code. These numbers are 7 and 10. Here is my code: ``` void track_machine(){ int X = 0,Y = 0; //Coordinates double D = 0,R = 0; //Distance and replacement refresh_position(&X,&Y,&D,&R); printf("%d\n",X); printf("%d\n",Y); } void refresh_position(int *X, int *Y, double *D, double *R){ *X = rand()%12; *Y = rand()%12; } ```
With ``` #include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ ``` callsrand(time(NULL));at the start of your program - before you userand()- to set a different seed every time. The "random-number-generator" is, despite its name, still a deterministic algorithm. When starting with the same seed values (whensrandis not called), it will always produce the same results.
I am trying to compile a C program and display its output in a tab from Vim. My set up looks like this: hellomain.c ``` #include<stdio.h> #include<stdbool.h> int main() { int i = 100; bool b =0; printf("hello world :)"); return 0; } ``` makefile ``` program: hellomain.c gcc -o hello hellomain.c ``` When I run:make | copen, courtesy of thispost, I see a window like this: ``` gcc -o hello hellomain.c Press ENTER or type command to continue ``` After pressing the enter, the program compiles and I see a new horizontally split tab containing thegcccommand, but not the output of the program: What's the issue here?
``` :make && ./hello ``` Did you try this ? Alternatively, try below ``` :make && ./hello | copen ```
This question already has answers here:Why does division result in zero instead of a decimal?(5 answers)Closed3 years ago. ``` #include <stdio.h> main() { int c=2,n=5; float percent; percent=(c/n)*100; printf("%.3f\n",percent); } ``` what's wrong in this code please..?
``` percent=(c/n)*100; 2/5 ---> 0 because it is integer division 0*100 ---> 0 ``` It is an integer division, So you can change this to ``` percent=((float)c/n)*100; 2/5 ----> 0.4 0.4*100 ----> 40.0 ```
I am trying to get two random numbers between 0 and 11 but i get the same number whenever i execute my code. These numbers are 7 and 10. Here is my code: ``` void track_machine(){ int X = 0,Y = 0; //Coordinates double D = 0,R = 0; //Distance and replacement refresh_position(&X,&Y,&D,&R); printf("%d\n",X); printf("%d\n",Y); } void refresh_position(int *X, int *Y, double *D, double *R){ *X = rand()%12; *Y = rand()%12; } ```
With ``` #include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ ``` callsrand(time(NULL));at the start of your program - before you userand()- to set a different seed every time. The "random-number-generator" is, despite its name, still a deterministic algorithm. When starting with the same seed values (whensrandis not called), it will always produce the same results.
I am trying to compile a C program and display its output in a tab from Vim. My set up looks like this: hellomain.c ``` #include<stdio.h> #include<stdbool.h> int main() { int i = 100; bool b =0; printf("hello world :)"); return 0; } ``` makefile ``` program: hellomain.c gcc -o hello hellomain.c ``` When I run:make | copen, courtesy of thispost, I see a window like this: ``` gcc -o hello hellomain.c Press ENTER or type command to continue ``` After pressing the enter, the program compiles and I see a new horizontally split tab containing thegcccommand, but not the output of the program: What's the issue here?
``` :make && ./hello ``` Did you try this ? Alternatively, try below ``` :make && ./hello | copen ```
This question already has answers here:Why does division result in zero instead of a decimal?(5 answers)Closed3 years ago. ``` #include <stdio.h> main() { int c=2,n=5; float percent; percent=(c/n)*100; printf("%.3f\n",percent); } ``` what's wrong in this code please..?
``` percent=(c/n)*100; 2/5 ---> 0 because it is integer division 0*100 ---> 0 ``` It is an integer division, So you can change this to ``` percent=((float)c/n)*100; 2/5 ----> 0.4 0.4*100 ----> 40.0 ```
This question already has answers here:Why does division result in zero instead of a decimal?(5 answers)Closed3 years ago. ``` #include <stdio.h> main() { int c=2,n=5; float percent; percent=(c/n)*100; printf("%.3f\n",percent); } ``` what's wrong in this code please..?
``` percent=(c/n)*100; 2/5 ---> 0 because it is integer division 0*100 ---> 0 ``` It is an integer division, So you can change this to ``` percent=((float)c/n)*100; 2/5 ----> 0.4 0.4*100 ----> 40.0 ```
AutoConf has--hostoption to specify an architecture the file will be run on. But if I specify--host=i686-linux-gnu, no option-m32is added togcccompiler. What did I understand wrong about AutoConf? Because in this case, if I compile my program on 64 bit machine, it won't run on host machine.
Passing--host=i686-linux-gnuwill cause autoconf to look for and usei686-linux-gnu-gcc, etc. rather thangcc. This is expected to be a cross toolchain that produces 32-bit binaries. If you don't want to use a cross toolchain but just-m32, you should just passCC="gcc -m32"(andCXX="g++ -m32"if the program uses C++) to configure.
AutoConf has--hostoption to specify an architecture the file will be run on. But if I specify--host=i686-linux-gnu, no option-m32is added togcccompiler. What did I understand wrong about AutoConf? Because in this case, if I compile my program on 64 bit machine, it won't run on host machine.
Passing--host=i686-linux-gnuwill cause autoconf to look for and usei686-linux-gnu-gcc, etc. rather thangcc. This is expected to be a cross toolchain that produces 32-bit binaries. If you don't want to use a cross toolchain but just-m32, you should just passCC="gcc -m32"(andCXX="g++ -m32"if the program uses C++) to configure.
This question already has an answer here:Visual C++ dump preprocessor defines(1 answer)Closed3 years ago. Sorry for the what I am sure is a basic question, but I must not be using the right terms when searching for an answer with code that has hundreds of header files. Simply searching the files for#definestatements is tedious. Is there an easy way in Visual Studio or VSCode to just have it step through the files and give me a list of all values literals and their values?
The closest you can get is to use the/Pcompiler switch to dump the preprocessed output to a file. It's going to be pretty huge, but it shows you precisely what the compiler is working with, and you can do a text search in the output file to find what you're looking for.
I want to adjust the size of a custom control and make it topmost when it is active and has at least one line. Is it safe or even good coding to callSetWindowPos()from inside the same controlWindowProc()? I am working on WinAPI directly.
Yes it is safe. Many developers do this to alter the state of their window. For example, developers will callSetWindowPos()with theSWP_FRAMECHANGEDflag during theirWM_CREATEhandler to recalculate the client area of their window. CallingSetWindowPos()with the same window handle of the same control'sWindowProcis fine, just make sure all handles and flags are valid.
Hello I am a complete beginner in a university course for C programming. I am trying to compare 4 inputs for exact matches using strcmp. The code only take into account the first two though. Is it possible to compare two strcmp values to compare 4 inputs?
You can concatenate the results via&&. ``` if (strcmp(str1, str2) == 0 && strcmp(str1, str3) == 0 && strcmp(str1, str4) == 0) { printf("They match!") } ```
I have a struct that is nameditem, now I have another struct that is calledarraythat callsitem. Thestruct item arrayofListis required to be of the size5 ``` #include <stdio.h> #include <string.h> #define MaxItems 5 #define NameLength 20 #define UnitLenght 6 struct item { char name[NameLength]; float amount; char unit[UnitLenght]; }; struct array { struct item arrayofList; }; int main(void) { struct array shopping[MaxItems]; ``` Am I giving the list size of 5 or am I doing it incorrectly
You probably want this: ``` #include <stdio.h> #include <string.h> #define MaxItems 5 #define NameLength 20 #define UnitLenght 6 struct item // one item { char name[NameLength]; float amount; char unit[UnitLenght]; }; int main(void) { struct item shopping[MaxItems]; // array of MaxItems struct items ... } ```
Here's my C code: ``` char *ptr = "0xfff1342809062Cac"; char *pEnd; long long value = strtoll(ptr, &pEnd, 0); printf("%lld\n", value); printf("errno: %d\n", errno); ``` I compiled it with gcc-8.3.0, and the output is: ``` 9223372036854775807 errno: 34 ``` I'm confused that strtoll gives an unexpected value and set errno to 34.
This behaviour is correct. On your system the maximum value forlong long, i.e.LLONG_MAXis9223372036854775807. The value in your string is larger than this; and the specified behaviour if the value is out of range and too big is: returnLLONG_MAXanderrnois set toERANGE(presumably 34 on your system). Perhaps consider usingstrtoulland anunsigned long longreturn value , since that string would fit in that data type.
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed3 years ago. I am not able to understand why the following code printing garbage value ``` #include <stdio.h> void main(){ int arr[5],i=0; while(i<5) arr[i]=++i; for(i=0;i<5;i++) printf("%d",arr[i]); } ```
The statement ``` arr[i]=++i; ``` is effectively equivalent to ``` i = i + 1; arr[i] = i; ``` Which means you will not initialize the first element (at index0) in the array. What's worse is that you will write at index5as well, and that'sout of boundsand will lead toundefined behavior. Uninitialized local variables will have anindeterminatevalue, which could be seen as random or garbage. I recommend that you have aforloop like the one used for printing the values for your initialization as well: ``` for (i = 0; i < 5; ++i) arr[i] = i + 1; ```
This question already has answers here:Most efficient way to set n consecutive bits to 1?(3 answers)Closed3 years ago. I want to set an N amount of bits in a byte (byte always starts as 0) and store it using a pointer. Imagine: ``` void SetBits(uint8_t bytesToSet, uint8_t* var) {} ``` How would I go about implementing this (using C)?
Where should that N bits be set? To the left, to the right? If you want to have those N bits to the right, your function should look like this: ``` void SetBits(uint8_t bitsToSet, uint8_t* var) { if (bitsToSet < 8) *var = (1 << bitsToSet) - 1; else {*var = 0; *var = ~(*var);} } ``` For an example, for the callSetBits(5,&a), variableawill hold the value0b00011111.
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 am reversing an array using pointers : ``` void reverse(int *a,int n){ int i = 0,j = n-1; while(i < j){ int tmp; tmp = *(a+i); *(a+i) = *(a+j) *(a+j) = tmp; i++; j--; } ``` } The error i get : ``` error: invalid operands to binary * (have โ€˜intโ€™ and โ€˜int *โ€™) *(a+i) = *(a+j) ~~~~~~ *(a+j) = tmp; ^~~~~~ ``` I am very confused about why this happens.
the only problem is missing;here*(a+i) = *(a+j).
I want to make a calculator with the C language. When I take input from the user, if it is not from + , -,* or /, I want to print "Please enter a operator". My code is like this: ``` #include<stdio.h> #include<math.h> int main(){ int sayi1,sayi2; char operator; printf("HESAP MAKINESI V1.0\n"); printf("Islemi giriniz (+,-,*,/):\n"); scanf("%c",&operator); if(operator != char(+,-,*,/)){ printf("Please use a operator"); return 0;}} ``` But my code is not working. How can I fix it?
This: ``` if(operator != char(+,-,*,/)) ``` Is not proper C syntax. Character constants are enclosed in single quotes, and you must compare each character individually. ``` if ((operator != '+') && (operator != '-') && (operator != '*') && (operator != '/')) { ``` Here, the logical AND operator&&evaluates to true of both operands are true.
I would like to know if ``` int v [10]; ``` Allocates (besides 10*sizeof(int) bytes) also a pointer to integer to this vector.
No, there is no additional pointer allocation. Ten ints-worth of memory is allocated on the stack (if declared inside the function) or in the data segment (if declared globally). Although v conceptually contains the address of the beginning of this memory block, it doesn't need any additional storage for it, since v disappears when the code is compiled.
I have currently an issue with debugging with visual studio code . I want to attach GDB to a C (.so) shared library module that is called via a main python program that interfaces with the C shared library with F2PY. How do I procede to create a launch configuration in vscode for gdb to debug that C shared library?
Cross-language debugging from Python to C is only available in Visual Studio, not in VS Code.
Please consider the following command: ``` gcc myfile.c -o myapp.exe -Lmydir -lmylib ``` mydirinclues the following file: ``` `libmylib.a` ``` I know that by default,gccwants to dodyanmiclinking. However, as you can see it does not find alibmylib.sodynamic library, only alibmylib.astaticone. Does that mean thatgccwillstatically linklibmylib.ainto the result executable?
This behavior is up to the linker, not GCC. Standard linker behavior is to try a dynamic library then a static onein each path componentof the link search path. For example, if the first directory searched has only a static library by the name, the second directory will not be searched at all, even if it has a dynamic one. As such, for normal user expectations to work correctly, corresponding dynamic and static versions of the same library need to be placed in the identical location.
There are three variables that need to be tested against the same value (var1 or var2 or var3 > 255). If the comparison is true for any of them, the corresponding variable's value needs to be set to 255. Here's what i came up with: ``` if (r > 255) r = 255; if (g > 255) g = 255; if (b > 255) b = 255; ``` and ``` r += (r > 255) * (255 - r); g += (g > 255) * (255 - g); b += (b > 255) * (255 - b); ``` Since these are quite similar, so I was wondering if there's a way to shorten this code somehow.
Since these are quite similar, so I was wondering if there's a way to shorten this code somehow. You couldshorten this code somehowby using a macro: ``` #define LIMIT(v) if (v > 255) v = 255 LIMIT(r); LIMIT(g); LIMIT(b); ```
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 I'm trying to implement knapsack using OpenGL. I'm generating balls of given weight and profit taking values from the user, and then draw balls on the screen. I want to send the balls which are selected into a box but I'm not at all able to move the ball. Can you suggest a way to move a ball from point A to point B forming a trajectory in 2d? https://drive.google.com/open?id=1JIowM4NGLGOFWKosk6VTIB3SDGF4D_WI
I thinklinear interpolationis what you need.
Please consider the following command: ``` gcc myfile.c -o myapp.exe -Lmydir -lmylib ``` mydirinclues the following file: ``` `libmylib.a` ``` I know that by default,gccwants to dodyanmiclinking. However, as you can see it does not find alibmylib.sodynamic library, only alibmylib.astaticone. Does that mean thatgccwillstatically linklibmylib.ainto the result executable?
This behavior is up to the linker, not GCC. Standard linker behavior is to try a dynamic library then a static onein each path componentof the link search path. For example, if the first directory searched has only a static library by the name, the second directory will not be searched at all, even if it has a dynamic one. As such, for normal user expectations to work correctly, corresponding dynamic and static versions of the same library need to be placed in the identical location.
There are three variables that need to be tested against the same value (var1 or var2 or var3 > 255). If the comparison is true for any of them, the corresponding variable's value needs to be set to 255. Here's what i came up with: ``` if (r > 255) r = 255; if (g > 255) g = 255; if (b > 255) b = 255; ``` and ``` r += (r > 255) * (255 - r); g += (g > 255) * (255 - g); b += (b > 255) * (255 - b); ``` Since these are quite similar, so I was wondering if there's a way to shorten this code somehow.
Since these are quite similar, so I was wondering if there's a way to shorten this code somehow. You couldshorten this code somehowby using a macro: ``` #define LIMIT(v) if (v > 255) v = 255 LIMIT(r); LIMIT(g); LIMIT(b); ```
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 I'm trying to implement knapsack using OpenGL. I'm generating balls of given weight and profit taking values from the user, and then draw balls on the screen. I want to send the balls which are selected into a box but I'm not at all able to move the ball. Can you suggest a way to move a ball from point A to point B forming a trajectory in 2d? https://drive.google.com/open?id=1JIowM4NGLGOFWKosk6VTIB3SDGF4D_WI
I thinklinear interpolationis what you need.
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 currently learning bitwise operations in C. Given a byte(spaced for readability): 11 01 11 10 Must turn it into: 10 11 01 11 How do I go about doing this?
Mask and shift: ``` int a = 0b11011110; int b = ((a & 0b11000000) >> 6) | ((a & 0b00110000) >> 2) | ((a & 0b00001100) << 2) | ((a & 0b00000011) << 6); ``` I used binary constants here, but in "real life" you'll more often see hex - use whichever makes the most sense and reads best for your use case. ``` int b = ((a & 0xc0) >> 6) | ((a & 0x30) >> 2) | ((a & 0x0c) << 2) | ((a & 0x03) << 6); ```
``` for (unsigned i = 0; i < 3; i++) { if (i == 2) i = -1; } ``` I can't understand why this loop is infinite. I get that it wraps around wheni = -1but UINT_MAX is greater than 3.
If I rewrite your code, then might more clear to see why ``` unsigned i = 0; while (i < 3) { if (i == 2) i = -1; i++; } ``` i++happens at the end of the loop soibecame0again.
I am trying to understand C pointers. I tried this simple code: ``` double der(double a) { //printf("Value of a is %d\n", a); return (cos(a+eps)-cos(a-eps))/(2*eps); } void EX5(){ double x; double (*fun_pointer)(double) = &der; printf ("saisir un point "); scanf ("%lf",&x); printf ("cos reel = %lf \n", cos(x)); printf ("cos approximatif = %lf", der(x)); double *r; r=*(fun_pointer)(x); printf ("cos approximatif = %lf", r); } ``` But I get ``` invalid type argument of unary โ€˜*โ€™ (have 'double') ``` Where Am I doing wrong please?
It should be like this: ``` double r; r = fun_pointer(x); ``` The function returns adouble, notdouble*, so you don't need to dereference it. It's not necessary to dereference a function pointer when calling it, this is done automatically.
I am working withFreeRTOSand I am usingxQueueReceive()within a task that I created withxTaskCreate(). The task does only handle received network packets. Here's the task's implementation: ``` while(1) { if(sys_link_recv_queue != NULL) { mb32_packet_t packet; if(xQueueReceive(sys_link_recv_queue, &packet, portMAX_DELAY)==pdPASS) { // process packet ... } } } ``` When usingportMAX_DELAY, the queue waits indefinitely until a queue item gets available. My question is now whether I loose valuable CPU time during this wait state or if this is the recommended way of doing this. If it's not the most economical way of doing this, what's the alternative?
you do not. it is not polling. Your task is going to the blocked state and does not "consume" any CPU time. When something will place something in that queue your task status will be changed to "waiting" or "runnable" and eventually executed.
I want to search and replace a pointer ``` char* test ``` however, when I type ``` :%s/char* test/something/g ``` I get ``` E486: Pattern not found: char* test ``` I assume this is due to vim trying to use regex in search. How can i tackle this issue? Is it possible to replace such text?
You need to escape star symbol. This should work: ``` :%s/char\* test/something/g ```
``` for (unsigned i = 0; i < 3; i++) { if (i == 2) i = -1; } ``` I can't understand why this loop is infinite. I get that it wraps around wheni = -1but UINT_MAX is greater than 3.
If I rewrite your code, then might more clear to see why ``` unsigned i = 0; while (i < 3) { if (i == 2) i = -1; i++; } ``` i++happens at the end of the loop soibecame0again.
I am trying to understand C pointers. I tried this simple code: ``` double der(double a) { //printf("Value of a is %d\n", a); return (cos(a+eps)-cos(a-eps))/(2*eps); } void EX5(){ double x; double (*fun_pointer)(double) = &der; printf ("saisir un point "); scanf ("%lf",&x); printf ("cos reel = %lf \n", cos(x)); printf ("cos approximatif = %lf", der(x)); double *r; r=*(fun_pointer)(x); printf ("cos approximatif = %lf", r); } ``` But I get ``` invalid type argument of unary โ€˜*โ€™ (have 'double') ``` Where Am I doing wrong please?
It should be like this: ``` double r; r = fun_pointer(x); ``` The function returns adouble, notdouble*, so you don't need to dereference it. It's not necessary to dereference a function pointer when calling it, this is done automatically.
I am working withFreeRTOSand I am usingxQueueReceive()within a task that I created withxTaskCreate(). The task does only handle received network packets. Here's the task's implementation: ``` while(1) { if(sys_link_recv_queue != NULL) { mb32_packet_t packet; if(xQueueReceive(sys_link_recv_queue, &packet, portMAX_DELAY)==pdPASS) { // process packet ... } } } ``` When usingportMAX_DELAY, the queue waits indefinitely until a queue item gets available. My question is now whether I loose valuable CPU time during this wait state or if this is the recommended way of doing this. If it's not the most economical way of doing this, what's the alternative?
you do not. it is not polling. Your task is going to the blocked state and does not "consume" any CPU time. When something will place something in that queue your task status will be changed to "waiting" or "runnable" and eventually executed.
I want to search and replace a pointer ``` char* test ``` however, when I type ``` :%s/char* test/something/g ``` I get ``` E486: Pattern not found: char* test ``` I assume this is due to vim trying to use regex in search. How can i tackle this issue? Is it possible to replace such text?
You need to escape star symbol. This should work: ``` :%s/char\* test/something/g ```
Recently, I am reading some source code. I found one syntax I haven't seen before. Also can't found any clue. ``` #define v(t, s, name, ...) \ .. name.size = sizeof((__typeof__(name.buf[0])[]){0, __VA_ARGS__}) / \ sizeof(name.buf[0]) - 1; ``` Let me modify this macro intorealstatement: ``` int a[20]; printf("%d",sizeof((__typeof__(a[0])[]){0,2,4,5})/sizeof(a[0]) - 1); ``` I wondering how do we call the syntax like(int[ ]){1,2,3....}?
It is calleda compound literal.
I'm just starting to dip my toes on coding, starting with C. I asked people how to set an environment for C coding, they said VScode for editing and MinGW for compiling is the best. I got VScode with C/C++ extension installed, but I have trouble installing MinGW. I've installed MinGW Installation Manager, and there are hundreds of packages available to download. Which of them should I install?
See theMinGW documentationabout what packages are recommended. Also, thefree VisualStudio Community Editionmight be better suited for beginners than MinGW, as it is an all-in-one-package.
I have a function that is supposed to convert a decimal number into binary. The thing is for some numbers it works like the output for: 27 = 00011011 but for 5015 it converts it into 82630143 instead 1001110010111 This is my function: ``` int dec(int num) { long bNum = 0; int remNum, i = 1, highNum = 32768; while (num != 0) { remNum = num / highNum; remNum = num % 2; num /= 2; bNum = bNum + remNum * i; i = i * 10; } return bNum; } ``` Any help would be really appreciated.
Asmchcommented1001110010111is way to big for a integer. You can try to save it in aunsigned long long intvariable, but actually the best way is to use a char-array or a char-pointer.
I'm having difficulty formatting my output binary number in C Language. I'm trying to divide the output number into two groups of 8 digits, which would be separated by a single space. this is my printf: ``` printf("%016ld in Binary\n", decNumtoBin); ``` This is my the output 0000001000101011 I wanted to look like this 00000010 00101011
Posting as 'answer', as requested in comments. In order to understand why it works, remember, you aren't actually printing a binary number, but a decimal one. And all you want to do is split it into 2 parts, which can be easily done using a simple division and a modulo. ``` printf("%08ld %08ld in Binary\n", decNumtoBin/100000000, decNumtoBin%100000000); ```
For example, const array of integers is {88, 2, 90, 1, 4} and the printed output would be 90 88 4 2 1 I'm really confused since the requirement is O(n^2) in C
WithO(N^2)solution you could do any form of sorting in descending order and print out accordingly. You useqsort()in<stdlib.h>ORwrite your own sorting algorithm. A few example to get you started: Selection SortInsertion SortBubble Sort More advance sorting algorithm such as QuickSort, MergeSort can possibly give better time complexity improvements.
The1seems unnecessary (and possibly misleading) in the following example, but I have seen this multiple times when used for checking#ifdefs: ``` #ifndef __NEWLIB_H__ #define __NEWLIB_H__ 1 ``` Is there a difference or reason for using the above versus a plain#define __NEWLIB_H__?
1is true, so you can use the macro in an#iftest. That's not usually very useful for header guards, but it certainly doesn't hurt. For other macros which might be tested in boolean expressions, the true value is definitely useful. Some people just like the consistency. And that's the definition thatgccchooses by default if you put-D TESTMEon the command line. However, ``` #define __NEWLIB_H__ 1 ``` is not cool unless it's in an implementation of the standard library, because names starting with two underscores (or an underscore and a capital letter) are reserved for use by the implementation, and should never be used in portable applications.
I'm having difficulty formatting my output binary number in C Language. I'm trying to divide the output number into two groups of 8 digits, which would be separated by a single space. this is my printf: ``` printf("%016ld in Binary\n", decNumtoBin); ``` This is my the output 0000001000101011 I wanted to look like this 00000010 00101011
Posting as 'answer', as requested in comments. In order to understand why it works, remember, you aren't actually printing a binary number, but a decimal one. And all you want to do is split it into 2 parts, which can be easily done using a simple division and a modulo. ``` printf("%08ld %08ld in Binary\n", decNumtoBin/100000000, decNumtoBin%100000000); ```
For example, const array of integers is {88, 2, 90, 1, 4} and the printed output would be 90 88 4 2 1 I'm really confused since the requirement is O(n^2) in C
WithO(N^2)solution you could do any form of sorting in descending order and print out accordingly. You useqsort()in<stdlib.h>ORwrite your own sorting algorithm. A few example to get you started: Selection SortInsertion SortBubble Sort More advance sorting algorithm such as QuickSort, MergeSort can possibly give better time complexity improvements.
The1seems unnecessary (and possibly misleading) in the following example, but I have seen this multiple times when used for checking#ifdefs: ``` #ifndef __NEWLIB_H__ #define __NEWLIB_H__ 1 ``` Is there a difference or reason for using the above versus a plain#define __NEWLIB_H__?
1is true, so you can use the macro in an#iftest. That's not usually very useful for header guards, but it certainly doesn't hurt. For other macros which might be tested in boolean expressions, the true value is definitely useful. Some people just like the consistency. And that's the definition thatgccchooses by default if you put-D TESTMEon the command line. However, ``` #define __NEWLIB_H__ 1 ``` is not cool unless it's in an implementation of the standard library, because names starting with two underscores (or an underscore and a capital letter) are reserved for use by the implementation, and should never be used in portable applications.