question
stringlengths
25
894
answer
stringlengths
4
863
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.Closed4 years ago.Improve this question Surprisingly I can't find an easy reference on this, I want to compute: ``` float x = /*...*/; float next = nextint(x); ``` where next is strictly greater thanx(ie ifxis an integer, return the next higher integer). Ideally without branches.
You seem to want floor + 1: ``` float next = floorf(x) + 1; // or std::floor ``` Note that this gives you the mathematically next integer, rounded to nearest representable value, which for largexmay bexitself. This does not produce a strictly larger representable integer in such case. You should consider whether this is what you intend.
Is there a way to "generate" a function name by using the operator ## and a variable value. For example: ``` #define FUN_I(fun, fun_id) fun##fun_id #define FUN(fun, fun_id) RECV_CB_FUN_I(fun, fun_id) int foo0(int x) { // do something } int main() { int i = 0; FUN(foo,i)(1); } ``` MacroFUNgeneratesfooi. Is there a way to getfoo0somehow, or I have to use the actual number 0 in this case, e.gFUN(foo, 0)(1); Cheers
You have to use actual 0 (or another macro). Macro expansion is handled by the C pre-processor at compile time. It knows nothing about runtime values of variables.
I have a C header as part of a C++ library. This C header would only make sense compiled by a C compiler, or by a C++ compiler within anextern "C" { ... }block, otherwise unresolved link errors would happen. I thought to add a block such as: ``` #ifdef __cplusplus #error "Compiling C bindings with C++ (forgot 'extern \"C\"'?)" #endif ``` in the C header, but unfortunately the__cplusplusmacro is defined also within anextern "C" { ... }block. Is there another way to detect this condition correctly?
The common practice is not to demand client code wraps your header inextern "C", but to do so conditionally yourself. For instance: ``` #ifdef __cplusplus extern "C" { #endif // Header content #ifdef __cplusplus } #endif ``` That way client code is automatically correct without doing anything beyond including the header.
This question already has answers here:How to check if user input is a float number in C?(2 answers)Closed4 years ago. I am working on a simple temperature converter in C and I am facing an issue with the user input. I need a function like isdigit() that works on float. Any suggestion ???
There is no such function in the C standard library. You need to implement yourself this functionality. Read more inHow to check if user input is a float number in C?
This question already has answers here:How to check if user input is a float number in C?(2 answers)Closed4 years ago. I am working on a simple temperature converter in C and I am facing an issue with the user input. I need a function like isdigit() that works on float. Any suggestion ???
There is no such function in the C standard library. You need to implement yourself this functionality. Read more inHow to check if user input is a float number in C?
Hi I have a defined structure like this: ``` typedef struct { unsigned short Limit; unsigned long Offset; } DT_Info; ``` However, the actual size of this is 16 byte instead of 10 byte. The "Offset" will start at [DT_Info + 8]. Is there a way that I can make the compiler adjust the "Offset" start at [DT_Info + 2]? Thank you very much!
The extra space is padding for alignment. If you're sure that your target architecture doesn't need it, you can disable it by adding__attribute__((__packed__))to the declaration.
This question already has an answer here:right shift count >= width of type or left shift count >= width of type(1 answer)Closed4 years ago. I am trying to fill a 64-bit unsigned variable by combining 16-bit and 8-bit values: ``` uint8_t byte0 = 0x00; uint8_t byte1 = 0xAA; uint8_t byte2 = 0x00; uint8_t byte3 = 0xAA; uint16_t hword0 = 0xAA00; uint16_t hword1 = 0xAAAA; uint64_t result = ( hword0 << 32 ) + ( byte3 << 24 ) + ( byte2 << 16 ) + ( byte1 << 8 ) + ( byte0 << 0 ); ``` This gives me a warning. left shift count >= width of type [-Wshift-count-overflow] uint64_t result = ( hword0 << 32 )
hword0is 16 bits long and you request for a 32 bit shift. Shifting more than the number of bits - 1 is undefined. Solution is to convert your components to the destination type :uint64_t result = ( ((uint64_t)hword0) << 32 ) +etc.
So I havechar **sentencewithsentence[0] = string0, sentence[1] = string1, etc. Is there a way I can print the entire array in lldb? So that it shows up as{string0, string1, ...}
This is answered in: View array in LLDB: equivalent of GDB's '@' operator in Xcode 4.1 particularly, you can use theparraycommand in any recent lldb. There isn't a way to do this in the Xcode Locals view, but you can do this in the Xcode Debugger Console.
This question already has an answer here:right shift count >= width of type or left shift count >= width of type(1 answer)Closed4 years ago. I am trying to fill a 64-bit unsigned variable by combining 16-bit and 8-bit values: ``` uint8_t byte0 = 0x00; uint8_t byte1 = 0xAA; uint8_t byte2 = 0x00; uint8_t byte3 = 0xAA; uint16_t hword0 = 0xAA00; uint16_t hword1 = 0xAAAA; uint64_t result = ( hword0 << 32 ) + ( byte3 << 24 ) + ( byte2 << 16 ) + ( byte1 << 8 ) + ( byte0 << 0 ); ``` This gives me a warning. left shift count >= width of type [-Wshift-count-overflow] uint64_t result = ( hword0 << 32 )
hword0is 16 bits long and you request for a 32 bit shift. Shifting more than the number of bits - 1 is undefined. Solution is to convert your components to the destination type :uint64_t result = ( ((uint64_t)hword0) << 32 ) +etc.
So I havechar **sentencewithsentence[0] = string0, sentence[1] = string1, etc. Is there a way I can print the entire array in lldb? So that it shows up as{string0, string1, ...}
This is answered in: View array in LLDB: equivalent of GDB's '@' operator in Xcode 4.1 particularly, you can use theparraycommand in any recent lldb. There isn't a way to do this in the Xcode Locals view, but you can do this in the Xcode Debugger Console.
I have declared macros like this: ``` #define F_MASK_4_BIT 0xF #define GET_F_4BIT_MASK(F, P) (((F) & (F_MASK_4_BIT << (P * 4))) >> (4 * P)) ``` using macro like this: ``` uint8_t Feature = GET_F_4BIT_MASK(E, P); ``` WhereEisuint64_tdatatypePisuint8_tdatatype Which gives warning by Prefast:C6297: Arithmetic overflow: 32-bit value is shifted, then cast to 64-bit value. Results might not be an expected value. How to fix this?
It's pretty self-explaining. IfPhas any value larger than7(7*4=28, max is 31), theF_MASK_4_BIT << (P * 4)will overflow. BecauseF_MASK_4_BITis a integer constant of typeint. Fix this by using an appropriate type for the integer constant: ``` #define F_MASK_4_BIT 0xFull ```
I have a doubt that why 3 variables wstart = wend = start; are used to initialise the loop.if the value of any of these variable changes will it change the value of both variable ??? ``` void reverseletter(char str[], int start, int end) { int wstart, wend; for (wstart = wend = start; wend < end; wend++) { if (str[wend] == ' ') continue; // Checking the number of words // present in string to reverse while (str[wend] != ' ' && wend <= end) wend++; wend--; //Reverse the letter //of the words reverse(str, wstart, wend); } } ```
wstart = wend = startis the same as ``` wend = start; wstart = start; ``` if the value of any of these variable changes will it change the value of both variable ? No, changing one variable won't affect the others, all 3 are independent variables.
When I call ``` gtk_text_buffer_create_tag(buffer, "small_distance", "foreground", "green"); ``` in my program it warns at runtime: g_object_set_is_valid_property: object class 'GtkTextTag' has no property named '\u0004'
You have to "NULL-terminate" the list of args: ``` gtk_text_buffer_create_tag(buffer, "small_distance", "foreground", "green", NULL); ``` Notice the NULL as "last parameter". More on this topic: The param list is treated asg_object_set(). And it states value for the first property, followed optionally by more name/value pairs,followed by NULL
I want to change the value of_"ans"_in every condition of this script: ``` main(){ char in; int ans=0; printf ("Enter character"); scanf ("%c",&in); if (in == '+' && in == '/' && in == '*' && in == '-'){ ans=10; } } ``` How do I do that?
if (A && B)…does not mean: do this if A is true, anddo this if B is true. It means: do this if A is true and B is true. To make a condition so theifis triggered if A is true and is triggered if B is true, you useA || B. This means: do this if A is true or B is true.
I had the same problem as in this question:After installing minGW, gcc command is not recognized. I have downloaded MinGW Installer and have followed the instruction that is held in thislinkand in thislink; however, I still get the same "not recognized" message. What is left to fix? EDIT: Forgot to add a screenshot.screencap of relevant area
Have you checked your path in the windows GUI? Search in windows (Windows+S) for "environment variables" and click "edit the system environment variables." Then click environment variables (the button). Add the path to your MinGW/bin (binaries) folder to yoursystemPATH variable!! (not user). Try this. If you have, you will need to close your cmd window and open a new one, as well as possibly needing to restart/sign out and sign in. Also make sure you installed the gcc part of MinGW and not just g++ compiler (I can't remember the install options right now).
I'm trying to duplicate an 8-bit value to 32-bit and wanted to ask if it's possible to write a single line algorithm to duplicate the bit values. For example: ``` 1100 1011 -> 1111 1111 0000 0000 1111 0000 1111 1111 ``` If it's possible, I would like to understand what's the logic behind it.
There are only 256 8-bit values, so a simple lookup table would occupy 1kb, and the lookup is trivial. It's hard to believe that any bithack would have superior performance.
``` (gdb) set disassemble intel Ambiguous set command "disassemble intel": disassemble-next-line, disassembler-options. ``` When i set the disassembly syntax to intel, it show this error.
Please use: ``` set disassembly-flavor intel ``` seeGDB Manualfor more details
I have existing C program which i want to call from tibco bw6. Is there any direct approach, like bw allow to invoke java code. One possible solution is to use java invoke and jni. Direct call will be more preferable if possible
if you have the .exe file you can use External Command activity otherwise I do not see any other simple solutions than to use swig with jni. Regards
I am looking to calculate the below sum but using the products digits, not the products themselves: These are the initial values: 2 + 12 + 8 = 22 but what I want to achieve is the following, so that the digit 12 is actually seen as a 1 and a 2 separately 2 + 1 + 2 + 8 = 13 Using C language is there a formula in which I can use to perform this task?
Supposing you have an array of the values you can do : ``` #include <stdio.h> unsigned sum(const unsigned * a, size_t sz) { unsigned sum = 0; while (sz--) { unsigned v = *a++; while (v) { sum += v%10; v /= 10; } } return sum; } int main() { const unsigned a[] = { 2, 12, 8 }; printf("sum = %u\n", sum(a, sizeof(a)/sizeof(*a))); } ``` Compilation and execution : ``` /tmp % gcc -pedantic -Wextra s.c /tmp % ./a.out sum = 13 ```
I get this error with this code compiling with gcc 8.2: ``` #define literal "string" switch(i) { case literal[0]: break; } ``` Could the compiler reduce the expression literal[0] to 's' in my example?
C2011 6.4.8.2p3requires each case label's expression to be aninteger constant expression. Integer constant expressions are a restricted subset of constant expressions, defined in §6.6p6. String literals may not appear in integer constant expressions. 6.4.8.2p3 is a "constraints" paragraph, so this program is ill-formed. So the answer to your question, as literally asked, is: the compilercouldreduce"string"[0]to's', but it's not allowed to; it is required to reject your program instead.
I have been working on extending a Python application using ctypes to call a shared library in C code. I have a boolean variable in Python which I would like to check periodically in an infinite loop in the C code to see if it changes. Is there a way to send the memory address of the python variable to the C function and access the content? Thank you in advance!
You can't pass a reference to an actual Pythonbool. But you could make actypes.c_bool, pass a pointer to it to your C code, and then have Python code assign it's.valueattribute to change the value from C's point of view. ``` from ctypes import * # Flag initially false by default, can pass True to change initial value cflag = c_bool() # Call your C level function, passing a pointer to c_bool's internal storage some_c_func(byref(cflag)) # ... other stuff ... # If C code dereferences the bool* it received, will now see it as true cflag.value = True ```
How can I find the running time of a recursive function. For example: ``` void fun_list(LLnode_t * head) { if (head == NULL) { printf("\n"); return; } printf("%d ", head-> data); if (head->next != NULL) { fun_list(head->next); } printf("%d ", head->data); } ``` I know that we are supposed to find the running time of the recursive case and the base case. I think the running time of the base case is O(1). How would I go about finding the running time of the recursive case?
The time complexity would be O(n), where 'n' is how many times the recursive functions is called. It is basically calculated by multiplying the complexity of the base case by how many times it is called by the recursion. So the complexity is linear.
Is it legal to do a type-punning between an integer and an array of integers? Specific code: ``` #include <nmmintrin.h> #include <stdint.h> union Uint128 { __uint128_t uu128; uint64_t uu64[2]; }; static inline uint_fast8_t popcnt_u128 (__uint128_t n) { const union Uint128 n_u = {.uu128 = n}; const uint_fast8_t cnt_a = _mm_popcnt_u64(n_u.uu64[0]); const uint_fast8_t cnt_b = _mm_popcnt_u64(n_u.uu64[1]); const uint_fast8_t cnt = cnt_a + cnt_b; return cnt; } ```
Yes, type punning between all the data types through unions is explicitly foreseen by the C standard. There are no special provisions for arrays that would forbid that.
I am trying to code a program, which will examine state space of simple game. This program will use heuristic function, and I want to order generated states in min-heap by the given value of that heuristic function. But what size of heap it should be? The maximum number of states which could be generated is 9!, which is quite a lot, I think. How to manage this, if I do not want to allocate that huge memory space at once? I am coding this in C. Any ideas?
Assuming you will need to store one integer value for each state. Total size =9! * sizeof int (4byte) = 1.384MB. It isn't quite much! Also if there is no inner loop to compute the states then the time complexity should be O(10^6) and should take few miliseconds to compute. Yes.you can create heap without knowing the final size.Just use linked list and dynamic memory allocation.
I have been working on extending a Python application using ctypes to call a shared library in C code. I have a boolean variable in Python which I would like to check periodically in an infinite loop in the C code to see if it changes. Is there a way to send the memory address of the python variable to the C function and access the content? Thank you in advance!
You can't pass a reference to an actual Pythonbool. But you could make actypes.c_bool, pass a pointer to it to your C code, and then have Python code assign it's.valueattribute to change the value from C's point of view. ``` from ctypes import * # Flag initially false by default, can pass True to change initial value cflag = c_bool() # Call your C level function, passing a pointer to c_bool's internal storage some_c_func(byref(cflag)) # ... other stuff ... # If C code dereferences the bool* it received, will now see it as true cflag.value = True ```
How can I find the running time of a recursive function. For example: ``` void fun_list(LLnode_t * head) { if (head == NULL) { printf("\n"); return; } printf("%d ", head-> data); if (head->next != NULL) { fun_list(head->next); } printf("%d ", head->data); } ``` I know that we are supposed to find the running time of the recursive case and the base case. I think the running time of the base case is O(1). How would I go about finding the running time of the recursive case?
The time complexity would be O(n), where 'n' is how many times the recursive functions is called. It is basically calculated by multiplying the complexity of the base case by how many times it is called by the recursion. So the complexity is linear.
Is it legal to do a type-punning between an integer and an array of integers? Specific code: ``` #include <nmmintrin.h> #include <stdint.h> union Uint128 { __uint128_t uu128; uint64_t uu64[2]; }; static inline uint_fast8_t popcnt_u128 (__uint128_t n) { const union Uint128 n_u = {.uu128 = n}; const uint_fast8_t cnt_a = _mm_popcnt_u64(n_u.uu64[0]); const uint_fast8_t cnt_b = _mm_popcnt_u64(n_u.uu64[1]); const uint_fast8_t cnt = cnt_a + cnt_b; return cnt; } ```
Yes, type punning between all the data types through unions is explicitly foreseen by the C standard. There are no special provisions for arrays that would forbid that.
I am trying to code a program, which will examine state space of simple game. This program will use heuristic function, and I want to order generated states in min-heap by the given value of that heuristic function. But what size of heap it should be? The maximum number of states which could be generated is 9!, which is quite a lot, I think. How to manage this, if I do not want to allocate that huge memory space at once? I am coding this in C. Any ideas?
Assuming you will need to store one integer value for each state. Total size =9! * sizeof int (4byte) = 1.384MB. It isn't quite much! Also if there is no inner loop to compute the states then the time complexity should be O(10^6) and should take few miliseconds to compute. Yes.you can create heap without knowing the final size.Just use linked list and dynamic memory allocation.
I am trying to convert a decimal value to binary using the function I wrote in C below. I cannot figure out the reason why it is printing 32 zeroes rather than the binary value of 2. ``` #include <stdlib.h> #include <stdio.h> #include <string.h> #include <limits.h> int binaryConversion(int num){ int bin_buffer[32]; int mask = INT_MIN; for(int i = 0; i < 32; i++){ if(num & mask){ bin_buffer[i] = 1; mask >> 1; } else{ bin_buffer[i] = 0; mask >> 1; } } for(int j = 0; j < 32; j++){ printf("%d", bin_buffer[j]); } } int main(){ binaryConversion(2); } ``` Thanks
Two mistakes: You use>>instead of>>=, so you're not actually ever changingmask.You didn't declaremaskasunsigned, so when you shift, it'll get sign-extended, which you don't want.
I have a project where I need a ton on structs, and as an example, I will use this codebyte (not from project) ``` typedef struct THING{ int a; int b; float stuff; } THING; ``` The question I have is can I have a header file containing these typedefs and structs (i.e. structures.h) WITHOUT a related code file (structures.c)? Or what would be the proper method to do this? Thanks
There's no hard rule that a header file with a given name has to have a corresponding source file of the same name. If your header only has struct type definitions and typedefs then there's no need for there to be a corresponding .c file. If the file had function or global variable declarations then they would need to be defined in a .c file somewhere, however that file doesn't have to have the same name as the .h file.
I have a project that uses malloc a lot. And I wonder if there is a possibility to somehow check if all my mallocs are protected from aNULLreturn? Maybe to define something in header file? I tried to do it myself, checked forums - all in vain. Any possible variants?
You can replace all calls tomallocwith a wrapper function that performs the necessary NULL check: ``` void *safe_malloc(size_t s) { void *p = malloc(s); if (!p) { perror("malloc failed"); exit(1); } return p; } ``` You can also do the same forcallocandrealloc.
Fromman setbufon Ubuntu: You must make sure that the space that buf points to still exists by the time stream is closed, which also happens at program termination. For example, the following is invalid: Invalid sample code from manpage: ``` #include <stdio.h> int main(void) { char buf[BUFSIZ]; setbuf(stdin, buf); printf("Hello, world!\n"); return 0; } ``` Why is it invalid? Local variablebufis destroyed after program returns viareturn 0;.
Once thereturnis executed,bufno longer exists, but program execution continues with the calling of exit handlers and closing of streams. So, when the stream is closed, the buffer does not exist.
I have a function taking a function pointer, and I want to store the return value if the function pointed to by the pointer returns, and just run the function otherwise. Something like this: ``` static void threadStart(void (*function)(void*), void* arg) { if(function does not return void) (void*) store = function(arg); else(function()) }; ``` How can I do this? I tried just doing: ``` static void threadStart(void (*function)(void*), void* arg) { (void*) store = function(arg); }; ``` But this produces a compilation error.
You can't. Becausefunctionis declared asvoid (*function)(void*)it always returns void, so you don't need to.
Before using a pthread_mutex_t pthread_mutex_init() should be called, and after it's not longer required it should be destroyed using pthread_mutex_destroy(). My question is, what happens if my process terminates before it can call pthread_mutex_destroy(), for example a SIGKILL, SIGINT or SIGABORT? Is it possible that some resource will leak? Same question goes to pthread_cond_init/destroy as well.
Not on any platform you're likely to use. Objects like mutexes and condition variables are just chunks of memory in the process' address space. When a process terminates, its address space ceases to exist. So it's not possible for any resources to leak. Process-shared resources are more complex. While the resources won't leak, they may still exist and may even still be in use by other processes.
in the following code: ``` float sfrand( int *seed ) { float res; seed[0] *= 16807; *((unsigned int *) &res) = ( ((unsigned int)seed[0])>>9 ) | 0x40000000; return( res-3.0f ); } ``` source:http://iquilezles.org/www/articles/sfrand/sfrand.htm
seed[0]is same as*seed, that is the first integer (possibly the only one, if it doesn't point to an array) pointed to byseedpointer. *=operator is "assignment by product" operator, seed[0] *= 16807;is same as *seed = *seed * 16807;, which is what the line you ask about does. The whole function is a simple algorithm to generate pseudo-random numbers, it seems. The purpose of modifying the seed is, that next call will produce a different pseudo-random number.
I newly try to learn pointers in C . so I use (null pointers)int *pnumber = NULL;but I don't get it why I get 17824320 in output.could you please explain ? ``` #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include<stdlib.h> int main() { int number = 0; int *pnumber = NULL; number = 10; pnumber = &number; printf("%d \n", number); printf("%d \n", pnumber); return 0; } ``` And the output is 1017824320 (I think memory address)
pnumber = &number; ... printf("%d \n", pnumber); The initial NULL values coming fromint *pnumber = NULL;is modified bypnumber = &number;so you write the value ofpnumberbeing the address ofnumber If you doprintf("%d \n", *pnumber);that writes 10
Here's the code: this function is for reverse a array. ``` void rev(int* nums, int count){ for(int i = 0; i<count; i++){ int temp = *(nums+i); *(nums+i) = *(nums+count-1-i); *(nums+count-1-i) = temp; } } ``` this one is for implementing the function rev(). ``` void rotate(int* nums, int numsSize, int k) { int*q = nums; int count = numsSize - k; rev(nums, count); q = q+k; rev(q, k); rev(nums, numsSize); } ``` I pass the address of the array inrev(), but when it goes out of the for loop ofrev(),nums[]did not change. what's wrong with my code?
Yourrev()reverse the array twice, which means that the array remaing original. You can resolve this by changing the loop conditioni<counttoi<count-1-i.
I wanna write a program that translates a message entered by the user into B1FF-speak. However, the program seems to crash here: ``` #define MAX_LEN 80 char message[MAX_LEN]; printf("Enter a message: "); for (int i = 0; i < MAX_LEN - 1; i++) scanf("%c", message[i]); for (int i = 0; i < MAX_LEN - 1; i++) printf("%c", message[i]); ``` Where is the mistake? I can't seem to find it. I wanna understand why this specific piece of code crashes my program. Thanks in advance.
You need to add an ampersand in the scanf statement. ``` scanf("%c", &message[i]); ```
This question already has answers here:What is the significance of forward declaration in C programming?(4 answers)Closed4 years ago. ``` void viewMenu(){ //code viewSellMenu(); } void viewSellMenu(){ //code viewMenu(); } ``` How do i have to code those 2 function so they can have a mutual relation?
To call a function, the compiler needs to know itsdeclaration, i.e. what's it called, that it's a function, and what the parameters and return type are: ``` void viewSellMenu(void); // declaration of viewSelMenu // *definition* of viewMenu also serves as declaration void viewMenu(){ //code viewSellMenu(); // can be called because compiler knows declaration } // *definition* of viewSelMenu void viewSellMenu(){ //code viewMenu(); } ```
I have a function in C which gets a pointer and prints its disassembly code. ``` void print_dis(void *addr) { print_dis(addr); } ``` everything is working just fine but now I would like to pass this memory address from the command line as argv. How can I pass a memory address and assign it to a pointer so it will run like: my_prog 0x1234567890abcd and that print_dis will get this address as addr
You can convert string from argv[1] to unsigned long and assign it to a generic pointer using cast operator (void*), as is shown in example bellow.Be careful, it is dangerous! ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { void* ptr = (void*) strtoul(argv[1]+2,0,16); printf("%lX", (unsigned long) ptr); }. /* Output: /a.out 0x123456789abcdef Result ptr:123456789ABCDEF */ ```
I was wondering if there is a way to run a random statement in C that I created, such as a function. I know how to run a random integer but not how to randomly pick from a list of statements that I created.
you can do like this with yourrandomValuethat you got fromrand()function: ``` int statement = randomValue % nState; ``` in above code, I assume that your program havenSatestates and you can use this variable in yourswitch.
In the following code, how is the value ofstprinted along with the count of the numbers of characters in the string? Is the character string in printf printed before the string value ", the value returned ..." is printed? ``` #include <stdio.h> int main() { char st[] = "CODING"; printf("While printing "); printf(", the value returned by printf() is : %d", printf("%s", st)); int out = printf("%s", "hello"); return 0; } ```
Before the secondprintfstatement is called, its arguments must first be evaluated. One of those arguments is another call toprintf. So the innerprintfis called first, printing "CODING", and that call returns the number of characters printed. That value is then passed to the outerprintfstatement to print that value.
In system programming class, we are told that all system calls are made in c. For example opening a file for reading/writing. Does java run c codes behind?
Yes java runs C Code behind the scene. Using the native keyword. For Instance: System.currentTimeMillis() is a Native Method Here is a good explaination how to use Native code:https://www.baeldung.com/java-native
In system programming class, we are told that all system calls are made in c. For example opening a file for reading/writing. Does java run c codes behind?
Yes java runs C Code behind the scene. Using the native keyword. For Instance: System.currentTimeMillis() is a Native Method Here is a good explaination how to use Native code:https://www.baeldung.com/java-native
I tried defining a large number by #define, that didn't work. ``` int main() { long *N; N = (long *)malloc(10^10 * sizeof(int)); int n = 0, sum = 0; scanf("%d", &n); //long N = 10 ^ 10; //int size[N]; for (int i = 0; i < n; i++) { scanf("%lu",(N + i)); sum = sum + *(N+i); } printf("%d", sum); free(N); return (0); } ```
^is a bitwise XOR operator. The result ofoperator^is the bitwise XOR value of the operands. 10^10 * sizeof(int)is10^ (10*4)because of precedence rules and will result in 34 bytes being allocated. And if the value ofnis greater than 8, you will end up accessing memory that is out of bounds for your program in the following statement. ``` scanf("%lu",(N + i)); ``` To avoid this, you can first read intonand then usemalloclike this: ``` malloc(n * sizeof(int)) ```
I want to Print Pointer Array value in Reverse ``` #include <stdio.h> #define size 5 int main() { int a[size] = {1,2,3,4,5}; int i; int *pa = a; for(i = size; i >0; i--) { printf("a[%d] = %d\n",i,*pa); pa++; } return 0; } ``` Output: ``` a[5] = 1 a[4] = 2 a[3] = 3 a[2] = 4 a[1] = 5 ``` The output I want is: ``` a[5] = 5 a[4] = 4 a[3] = 3 a[2] = 2 a[1] = 1 ```
replace with this ``` #include <stdio.h> #define size 5 int main() { int a[size] = {1,2,3,4,5}; int i; int *pa = (a+size-1); for(i = size; i >0; i--) { printf("a[%d] = %d\n",i,*pa); pa--; } return 0; } ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed4 years ago.Improve this question why output is blank and why loop will run ``` for(i=1;i<=-10;i++) printf("*"); ``` if i=-1 or i= -10 doesn't matter its run once why
Your loop will iterate as long asiis less than or equal to-10. As long asiis larger than-10that condition will never be true and the loop will not iterate, not even once. Ifi == -10to begin with, the loop will iterate once. Then you doi++which increases the value ofi?to-9and the condition becomes false, and the loop won't iterate again. Note that the above is only true iffiis asignedinteger. Ifiis an unsigned integer things becomes very different. Then the-10will be converted to an unsigned value, and that value will become very large, and the loop will iterate a lot.
``` int i = 3; int j = (i)++; ``` vs ``` int i = 3; int j = i ++; ``` Is there a difference between how the above two cases are evaluated? Is the first case equivalent to incrementing an rvalue or is it undefined behaviour?
i++and(i)++behave identically. C 2018 6.5.1 5 says: A parenthesized expression is a primary expression. Its type and value are identical to those of the unparenthesized expression. It is an lvalue, a function designator, or a void expression if the unparenthesized expression is, respectively, an lvalue, a function designator, or a void expression. The wording is the same in C 1999.
``` int i = 3; int j = (i)++; ``` vs ``` int i = 3; int j = i ++; ``` Is there a difference between how the above two cases are evaluated? Is the first case equivalent to incrementing an rvalue or is it undefined behaviour?
i++and(i)++behave identically. C 2018 6.5.1 5 says: A parenthesized expression is a primary expression. Its type and value are identical to those of the unparenthesized expression. It is an lvalue, a function designator, or a void expression if the unparenthesized expression is, respectively, an lvalue, a function designator, or a void expression. The wording is the same in C 1999.
Could someone explain to me the following syntax: ``` typedef struct { int (*jac) (void *state, float * J); } aType; (...) aType myVar; ``` I can access myVar.jac, but what are "state" and "J" and how to access them? Thanks!
stateandJare not fields of your struct. They're parameters of the function pointerjac, whichisa member of your struct. This points to a function which takes avoid *and afloat *as parameters and returns anint. You can use it like this, for example: ``` int myfunc(void *state, float *J) { ... } ... a_type myVar; myVar.jac = myfunc; char buffer[100]; float f; ... myVar.jac(buffer, &f); ```
Could someone explain to me the following syntax: ``` typedef struct { int (*jac) (void *state, float * J); } aType; (...) aType myVar; ``` I can access myVar.jac, but what are "state" and "J" and how to access them? Thanks!
stateandJare not fields of your struct. They're parameters of the function pointerjac, whichisa member of your struct. This points to a function which takes avoid *and afloat *as parameters and returns anint. You can use it like this, for example: ``` int myfunc(void *state, float *J) { ... } ... a_type myVar; myVar.jac = myfunc; char buffer[100]; float f; ... myVar.jac(buffer, &f); ```
I have a program that creates a quad tree using malloc. I then have a function that then removes the tree by freeing all nodes. On a level one tree I free all 5 allocs, however on a level 2 I only free 17 of 21 allocs an I'm having trouble seeing where the problem is. Any help in this would be very helpful, below is the removeTree function: ``` void removeTree(Node *node) { int i = 0; if( node->child[0] == NULL ) free(node); else { for ( i=0; i<4; ++i ) { removeTree( node->child[i]); } } return; } ```
In the case where you have children, you'll leak the current node. The algorithm should look something like this: ``` void removeTree(Node *node) { if (node == NULL) return; int i; for (i = 0; i < 4; ++i) { removeTree(node->child[i]); node->child[i] = NULL; } free(node); } ```
This question already has answers here:What exactly is a translation unit in C(4 answers)Closed4 years ago. I think I've read that compiling multiple files withgccat the same time would achieve the same thing as adding all sources into a single source file, as perSingle Compilation Unit, but I can't find any sources on that anymore. Is that true? We are currently trying to shrink a binary to the smallest size possible and are applying multiple techniques to achieve that. We reached the point where the discussion is about the differences between Single Compilation Unit,Link Time Optimizationand changing the build to compile all sources in a single compiler call, something likegcc -o binary $CFLAGS $INCLUDES $CDEFS a.c b.c c.c d.c e.c.
No. Each independent .c file passed to a compiler is considered a single translation unit, so multiple files passed to a compiler produce multiple independent translation units.
So just experimenting with pointers in C. ``` void inc(int *p){ ++(*p); } int main(){ int x = 0; int *p; *p = x; inc(p); printf("x = %i",x); } ``` Why is this printing "x = 0" instead of "x = 1"?
Here's your error: ``` *p = x; ``` You're dereferencingp, which is unassigned, and giving it the current value ofx. Soxisn't changed because you didn't pass a pointer toxto your function, and dereferencing an uninitialized pointer invokesundefined behavior. You instead want to assign theaddress ofxtop: ``` p = &x; ``` Alternately, you can removepentirely and just pass the address ofxtoinc: ``` inc(&x); ```
I have a projet compiling with Cmake. I use Gcov to know code coverage during execution on a target. I use GCOV_PREFIX to change the directory of .gcda files. But I have only 45 .gcda files in this directory and the rest in source folders and subfolders. (600). How can i have all .gcda files in this same directory ?
The problem came from the environment variable. I would set the environment variable as a user and start the program as an administrator (sudo). Solutions: Declare the variable as an administratorLaunch the program as a user./startStart the program as an administrator with the -E option sudo -E ./start Here is the quote from the man page: -E, --preserve-env Indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the user does not have permission to preserve the environment.
My code uses ZLIB, and it seems that there are problems in usingfmemopen()and ZLIB functions afterwards... Is there an equivalent offmemopen()in ZLIB? Or how can I create it if no equivalent exists?
No there is not. Furthermore, there is no need for such a thing, since zlib provides in-memory functions for compression and decompression.
Im trying to write a program to randomly generate a number (term x) between [-2,2]. I then want to update the term using a while loop. I know how to use drand48() and srand() but I know I cant use drand48() for this since it only computes numbers between 0 and 1. Im only about a month in to using C so im still pretty confused about it all. Thanks!
If you calldrand48(), you get the range [0.0, 1.0). (This is a half-open interval, because drand won't return 1.0, only things very close to 1.) If you multiply the return valuedrand48()by 4, you get the range [0.0, 4.0). If you subtract 2 from4*drand48(), you get the range [-2.0, 2.0). So, therefore: ``` 4*drand48() - 2 ``` PS: I assume you're trying to generate a real number, not an integer. If you're trying to get an integer, use therand()solution that @WeatherVane posted.
Im trying to write a program to randomly generate a number (term x) between [-2,2]. I then want to update the term using a while loop. I know how to use drand48() and srand() but I know I cant use drand48() for this since it only computes numbers between 0 and 1. Im only about a month in to using C so im still pretty confused about it all. Thanks!
If you calldrand48(), you get the range [0.0, 1.0). (This is a half-open interval, because drand won't return 1.0, only things very close to 1.) If you multiply the return valuedrand48()by 4, you get the range [0.0, 4.0). If you subtract 2 from4*drand48(), you get the range [-2.0, 2.0). So, therefore: ``` 4*drand48() - 2 ``` PS: I assume you're trying to generate a real number, not an integer. If you're trying to get an integer, use therand()solution that @WeatherVane posted.
First of all, forgive me if this is a naive question; I'm just a beginner trying to learn. I am aware that : ``` char* a = "CD"; ``` Stores the string inread-only memory; so any changes to the strings are not possible. (constant) But I did know that this was the case when using malloc too; ``` char* a = malloc(3*sizeof(char)) ; a = "CD" ; a[0] = 'S' ; // even regular a = "MR"; does not work ``` I'm so confused I thought this is stored in theheap... Why can't I modify the string?
a = "CD";does exactly the same thing aschar* a = "CD";: it stores the address of"CD"intoa. The value returned by the call tomallocis overwritten, and the allocated memory is leaked. The right way to do this is tocopythe string: ``` strcpy(a, "CD"); ```
AFAICTwchar_tis always 32-bit wide on Apple targets. What is the sign ofwchar_ton: x86 Apple Darwin (32-bit MacOSX)x86_64 Apple Darwin (64-bit MacOSX)ARM iOS (32-bit)AArch64 iOS (64-bit) ?
ISO/IEC 9899:2017 §7.20.3/4: Ifwchar_t(see 7.19) is defined as a signed integer type, the value ofWCHAR_MINshall be no greater than −127 and the value ofWCHAR_MAXshall be no less than 127; otherwise,wchar_tis defined as an unsigned integer type, and the value ofWCHAR_MINshall be 0 and the value ofWCHAR_MAXshall be no less than 255. So looking atWCHAR_MINwill tell you. iOS ABI Function Call Guide: In iOS, as with other Darwin platforms, bothcharandwchar_tare signed types.
For some reason my palindrome function is not working, I'd love some help on it: Code ``` int Pal(char *s, int a, int b) { if (a>= b) return 1; if (s[a] != s[b]) return 0; return Pal(s, ++a , --b); } int main() { char *s = "civic"; if (Pal(s , 1, strlen(s))) printf("YES\n"); else printf("No\n"); } ``` It keeps printing No, and I'm clueless to why this is happening.
You're starting point for the function is incorrect: ``` if (Pal(s , 1 ,strlen(s) )) ``` Arrays in C and C++ have a starting index of 0. So you're actually starting at the second character and ending at the null terminating byte at the end of the string. Use a value of 1 less for both the start and the end: ``` if (Pal(s, 0, strlen(s)-1 )) ```
This question already has answers here:Difference between | and || , or & and && [duplicate](4 answers)Closed4 years ago. As said hereMicrosoft docs - CreateFileA function dwDesiredAccessThe requested access to the file or device, which can be summarized as read, write, both or neither zero).The most commonly used values are GENERIC_READ, GENERIC_WRITE, or both (GENERIC_READ | GENERIC_WRITE) When using both READ and WRITE permissions, why is it writtenGENERIC_READ | GENERIC_WRITEand notGENERIC_READ && GENERIC_WRITE? Does the|has anything to do with the bitwise OR operator? if yes, why do we use that instead of&&?
GENERIC_READandGENERIC_WRITEare bit flags - values that only have one bit set. To combine them you use the bitwise or operator|.&&is not a bitwise operator, but a logic operator.
I know C++ and I am learning C. I would like to define nullptr as NULL, but when I initialize a struct using brackets it causes an error and says expected '}'. I'm using the visual studio compiler and a sample of my code is bellow: ``` #define nullptr NULL; typedef struct { int data; struct Node* next; } Node; //works fine Node myNode1; myNode1.data = 1; myNode1.next = nullptr; //works fine Node myNode2 = {1, NULL}; //error E0067 expected a '}' Node myNode3 = {1, nullptr }; ```
Definenullptras ``` #define nullptr NULL ``` with no trailing;.
I was on the CS50 credit problem. I was trying to find the number’s second-to-last digit. For example,4003600000000014.It should be4,0,6,0,0,0,0,1. I am confused by this loop. When I use numbers e.g.1,2,...15to replace2i-1, it worked. But in this loop, it did not work. It gave me6,6,6,6,6,6,6,6Thank you for your help! ` ``` long answer=get_long("Number: "); int i; long a; for (i=1; i<9 ; i++) { a= fmod((answer / (pow(10,2i-1))),10); printf("%ld\n",a) } ``` `
The expression2i-1isn't what you think it is. 2iis actually a complex number constant. When you then pass the complex value2i-1topow, the imaginary part gets truncated and the actual value passed is-1. When multiplying two numbers / variables, you have to use the*operator: ``` 2*i-1 ```
My issue concerns this line: ``` int f = makecontext( &threadList[ numThreads ].context ``` My program compiles without error without the assignment operation, but does not work at all. The line appears to do nothing. When I add "int f =" the compiler gives me the error: ``` my_pthread.c:41:10: error: void value not ignored as it ought to be ``` I don't understand how this is happening, since ucontext should always return 0 or -1. Any help is appreciated.
Themakecontextfunction is declared as: ``` void makecontext(ucontext_t *ucp, void (*func)(), int argc, ...); ``` It returns no value, so you can't assign the result of the function to anything.
Is there any good reason to prefer ``` MPI_Abort(MPI_COMM_WORLD, MY_ERROR_CODE); ``` to ``` exit(MY_ERROR_CODE); ``` in an MPI-based parallel code written in C? So far I've never used the former.
Read the documentation of theMPI_Abortfunction:https://www.open-mpi.org/doc/v2.0/man3/MPI_Abort.3.php. Theexitfunction just terminates the calling process.MPI_Aborton the other hand makes a "best attempt" to abort all tasks in the group of comm not just the calling process.
I know C++ and I am learning C. I would like to define nullptr as NULL, but when I initialize a struct using brackets it causes an error and says expected '}'. I'm using the visual studio compiler and a sample of my code is bellow: ``` #define nullptr NULL; typedef struct { int data; struct Node* next; } Node; //works fine Node myNode1; myNode1.data = 1; myNode1.next = nullptr; //works fine Node myNode2 = {1, NULL}; //error E0067 expected a '}' Node myNode3 = {1, nullptr }; ```
Definenullptras ``` #define nullptr NULL ``` with no trailing;.
I was on the CS50 credit problem. I was trying to find the number’s second-to-last digit. For example,4003600000000014.It should be4,0,6,0,0,0,0,1. I am confused by this loop. When I use numbers e.g.1,2,...15to replace2i-1, it worked. But in this loop, it did not work. It gave me6,6,6,6,6,6,6,6Thank you for your help! ` ``` long answer=get_long("Number: "); int i; long a; for (i=1; i<9 ; i++) { a= fmod((answer / (pow(10,2i-1))),10); printf("%ld\n",a) } ``` `
The expression2i-1isn't what you think it is. 2iis actually a complex number constant. When you then pass the complex value2i-1topow, the imaginary part gets truncated and the actual value passed is-1. When multiplying two numbers / variables, you have to use the*operator: ``` 2*i-1 ```
My issue concerns this line: ``` int f = makecontext( &threadList[ numThreads ].context ``` My program compiles without error without the assignment operation, but does not work at all. The line appears to do nothing. When I add "int f =" the compiler gives me the error: ``` my_pthread.c:41:10: error: void value not ignored as it ought to be ``` I don't understand how this is happening, since ucontext should always return 0 or -1. Any help is appreciated.
Themakecontextfunction is declared as: ``` void makecontext(ucontext_t *ucp, void (*func)(), int argc, ...); ``` It returns no value, so you can't assign the result of the function to anything.
I'm getting a‘GL_FRAMEBUFFER_EXT’ undeclaredand I'm unable to find the header file, where should it be? I'm using c and OpenGL ES, not OpenGL.
Khronos header files are here: https://www.khronos.org/registry/OpenGL/index_es.php For OpenGL ES 1.x you want this one: ``` #include <GLES/glext.h> ``` ... but note that the define isGL_FRAMEBUFFER_OES, not*_EXT, as by this point the extension was an official extension for OpenGL ES rather than a multi-vendor extension for OpenGL. For OpenGL ES 2.x onwards the functionality is core, so you can use useGL_FRAMEBUFFERfrom the main header.
Trying to adjust the PWM period value using the macro ``` __HAL_TIM_SET_COMPARE(&htim4,TIM_CHANNEL_3,299); ``` but it does not work. However the macro ``` __HAL_TIM_SET_AUTORELOAD(&htim4, 599); ``` works fine. why the__HAL_TIM_SET_COMPAREdoes not work ?. The board I am using is NUCLEO-F401RE with CUBE-MX generated project on Truestudio.
I had similar issues with this macro, and would opt instead for: ``` htim4.Instance->CCR3=299; ``` Supposing you want to set the capture and compare register of channel three forhtim4to 299 to modify your PWM duty cycle.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed3 years ago.Improve this question Where is the directory? i've searched for possibly all the directories but couldn't find any file related to the program
In the currentworking directory. If it does not maybe the call is not successfully. Check its return-code.
This question already has answers here:How to get address of a pointer in c/c++?(12 answers)Displaying the address of a string(4 answers)Closed4 years ago. I have an array of char pointers and I want to know the address these pointer are pointing too. Essentially I want to know the address of the string the char pointer points to. I want to know How to get access to0x555555769280for example I can see it in the debugger, but I want to be able to print the address.
When you try to print a pointer, the value stored will be printed instead of address becausestd::coutwill treatchar *as a null-terminated string and print the string. To get the address, you can cast it to a pointer. Try this: ``` cout<< (void *) ptr2[0]; ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed3 years ago.Improve this question Where is the directory? i've searched for possibly all the directories but couldn't find any file related to the program
In the currentworking directory. If it does not maybe the call is not successfully. Check its return-code.
This question already has answers here:How to get address of a pointer in c/c++?(12 answers)Displaying the address of a string(4 answers)Closed4 years ago. I have an array of char pointers and I want to know the address these pointer are pointing too. Essentially I want to know the address of the string the char pointer points to. I want to know How to get access to0x555555769280for example I can see it in the debugger, but I want to be able to print the address.
When you try to print a pointer, the value stored will be printed instead of address becausestd::coutwill treatchar *as a null-terminated string and print the string. To get the address, you can cast it to a pointer. Try this: ``` cout<< (void *) ptr2[0]; ```
This question already has answers here:How does the ternary operator work?(12 answers)Closed4 years ago. This is on C: ``` #include <stdio.h> int main() { int a=100,b; b= (a>100)?a++:a--; printf("%d %d\n",a,b); } ``` b assigned the value 100 but when trying ``` int main() { int a=100,b; b= (a>100) printf("%d %d\n",a,b); } ``` b prints the value 1 as it returns true. why is it different when using '?:' operator?
The?:operator evaluates either the thing before the:or the thing after the:to determine what it evaluates to. In this case,(a>100)is false, so it evaluates toa--. Since that's a post-decrement, the decrement happens after its value is provided, so it evaluates to the100value thatbhad before it was decremented. Thusbgets this value. So in the first example, the result of evaluatinga--is assigned tob. In the second example, the result of evaluating(a>100)is assigned tob.
I know that segfault is a common manifestation of undefined behavior. But I have two small questions about it: Are ALL segfaults undefined behavior?If no, is there any way to ensure a segfault? What is a segmentation fault?is far more general than my question and none of the answers answers any of my questions.
A segmentation fault simply means that you did an invalid access to memory -- either because the address requested is not mapped (mapping error) or because you don't have permissions to access it (access error). There are segmentation faults that are intended. One such example can be foundhere-- a mini application that deliberately plays with permissions of memory pages in order to detect where writes are being made by a given function.The easiest way is to use theraisefunction. Source: ``` #include <signal.h> int main() { raise(SIGSEGV); return 0; } ```
How can I find out the number of comparison operations for a qsort? I have an array of pointers that should be sorted. This array of pointers points to an array of structures. ``` struct oristru { char string1[TITLE_FIELDLENGTH]; char string2[AUTHORS_FIELDLENGTH]; short int 1; }; const struct oristru oristrukts[] = { ...} const struct oristru *temp_oristru[ARRAYLEN(oristrukts)]; struct oristru *p_sortst[ARRAYLEN(oristrukts)]; qsort(*p_sortst, ..); ```
Supposing you're sorting with functionfx() ``` qsort(..., fx); ``` just tweakfx() ``` // global var to count comparisons unsigned long ncomp = 0; int fx(const void *a, const void *b) { ncomp++; /* return ...; */ } ```
This question already has answers here:Undefined, unspecified and implementation-defined behavior(9 answers)Closed4 years ago. if the variable is initialized (i = 0), it's still 1 each time the function func is called, BUT when i is not initialized: ``` #include <stdio.h> int funct(void); int main(void) { funct(); funct(); funct(); return 0; } int funct(void) { int i; static int j = 0; i++; j++; printf(" i = %d j = %d\n", i, j); } ``` the output is ``` i = 1 j = 1 i = 2 j = 2 i = 3 j = 3 ``` I don't understand why the variable i behaves like a static one!
The value is unspecified, so anything goes. But, likely the same memory is reused for each call tofunctand with that, the same memory is reused and theijust pick up the old value left from the previous run.
I am writing a simple program to convert a number(+ve,32-bit) from binary to decimal. Here's my code: ``` int main() { int n=0,i=0; char binary[33]; gets(binary); for (i = 0; i < 33, binary[i] != '\0'; i++) n=n*2+binary[i]-'0'; printf("%d",n); } ``` If I removebinary[i]!='\0', then it gives wrong answer due to garbage values but if I don't it gives the correct answer. My question is: does thegetsfunction automatically add a '\0' (NULL) character at the end of the string or is this just a coincidence?
Yes it does, writing past the end ofbinary[33]if it needs to. Never usegets; automatic buffer overrun. SeeWhy is the gets function so dangerous that it should not be used?for details.
Well i have only one semester of C so i am little confused withHWNDand how to use it. I just want to print active window. I found -GetActiveWindow,GetForegroundWindow. But i just dont understand how to use this function to print that active window. I was trying to do something like. ``` HWND GetActiveWindow(); printf("%s", GetActiveWindow); ``` But that is probably bad use and not working.If someone can gave me a working example i will be very thankfull.
``` TCHAR buf[256]; GetWindowText( GetActiveWindow(), buf, sizeof buf / sizeof *buf ); wsprintf( TEXT( "Window text: %s\n" ), buf ); ```
I am using regex under vxworks and have no possibility to include "regex.h". I am getting the compilerwarning "unrecognized character escape sequence" for the codeif (sscanf(token, "%*[^\[][%d]", &idx) != 1)because of the '\' and the following '['. Is there a possibility to get rid of that compilerwarning without using the regex.h and stuff like it is done here:Unable to match regex in C
You may want to try something like ``` #include <stdio.h> int main(void) { char buf[99]; int idx, n; while (fgets(buf, sizeof buf, stdin)) { buf[strcspn(buf, "\n")] = 0; // remove ENTER if (sscanf(buf, "%*[^[][%d%n", &idx, &n) != 1) { printf("no number in %s\n", buf); } else { printf("number found: %d (left over string: \"%s\")\n", idx, buf + n); } } return 0; } ``` See code running on ideone
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed4 years ago.Improve this question Is it ok to use . as a member qualifier instead of the symbol -> for structures in GNU c. The compiler does not complain when symbol . used in place of ->.
.is used to access members of a structure;->is used to access members of a structure pointed to. The latter dereferences the pointer and then gets the member. Sop->xis equivalent to(*p).x. Example: ``` struct P { int x; int y; }; struct P myP = {1,2}; struct P *p= &myP; printf("%d, %d\n", myP.x, myP.y); // prints 1, 2 printf("%d, %d\n", p->x, p->y); // prints the same printf("%d, %d\n", (*p).x, (*p).y); // is the same ```
How will we print the below pattern in C language? Please explain the logic. ``` 1 12A 123BA 1234CBA 12345DCBA 123456EDCBA 1234567FEDCBA 12345678GFEDCBA 123456789HGFEDCBA 12345678910IHGFEDCBA ```
Please explain the logic. To printnum_linesof that patternfor eachlinefrom1to includingnum_linesdo:printnum_lines - linespacesprint each numberifrom1to includinglineprint each character from'A' + line - 2to including'A'print a newline characterrepeat
I defined a struct and I do not want to put the volatile into the struct because other instance may not need it (e.g. RAM caching). Now I need that a particular array of this struct be volatile. ``` typedef struct{ uint8_t rxPacket[FIFO_SIZE]; uint8_t length; int8_t rssi; uint8_t lqi; }rawRx_t; ``` Is this the right way to have each (struct) element of the array volatile ? ``` static volatile rawRx_t rawRxBuffer[NB_MAX_RX_FRAME]; ```
Yes. Paring it down and switching the type to somethingcdecl.orgcan parse, we get: ``` volatile int rawRxBuffer[]; ``` and the corresponding output is: ``` declare rawRxBuffer as array of volatile int ``` the point is that it's an "array of volatile", i.e. each array element is volatile.
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.Closed4 years ago.Improve this question I am trying to use side effect operator in my expression which does not have just a variable. My program was compiled successfully but I got a runtime error "Segmentation fault" Here is my code: ``` int main() { int x = 1; printf(1 + (x++)); return 0; } ```
C requires you to format the string, this way it knows what it should print. What you have in your example is nothing but memory addresses, which makes the C compiler confused. ``` int main() { int x = 1; printf("%d\n", (1 + (x++))); return 0; } ```
I am writing a simple program to convert a number(+ve,32-bit) from binary to decimal. Here's my code: ``` int main() { int n=0,i=0; char binary[33]; gets(binary); for (i = 0; i < 33, binary[i] != '\0'; i++) n=n*2+binary[i]-'0'; printf("%d",n); } ``` If I removebinary[i]!='\0', then it gives wrong answer due to garbage values but if I don't it gives the correct answer. My question is: does thegetsfunction automatically add a '\0' (NULL) character at the end of the string or is this just a coincidence?
Yes it does, writing past the end ofbinary[33]if it needs to. Never usegets; automatic buffer overrun. SeeWhy is the gets function so dangerous that it should not be used?for details.
Well i have only one semester of C so i am little confused withHWNDand how to use it. I just want to print active window. I found -GetActiveWindow,GetForegroundWindow. But i just dont understand how to use this function to print that active window. I was trying to do something like. ``` HWND GetActiveWindow(); printf("%s", GetActiveWindow); ``` But that is probably bad use and not working.If someone can gave me a working example i will be very thankfull.
``` TCHAR buf[256]; GetWindowText( GetActiveWindow(), buf, sizeof buf / sizeof *buf ); wsprintf( TEXT( "Window text: %s\n" ), buf ); ```
I am using regex under vxworks and have no possibility to include "regex.h". I am getting the compilerwarning "unrecognized character escape sequence" for the codeif (sscanf(token, "%*[^\[][%d]", &idx) != 1)because of the '\' and the following '['. Is there a possibility to get rid of that compilerwarning without using the regex.h and stuff like it is done here:Unable to match regex in C
You may want to try something like ``` #include <stdio.h> int main(void) { char buf[99]; int idx, n; while (fgets(buf, sizeof buf, stdin)) { buf[strcspn(buf, "\n")] = 0; // remove ENTER if (sscanf(buf, "%*[^[][%d%n", &idx, &n) != 1) { printf("no number in %s\n", buf); } else { printf("number found: %d (left over string: \"%s\")\n", idx, buf + n); } } return 0; } ``` See code running on ideone
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed4 years ago.Improve this question Is it ok to use . as a member qualifier instead of the symbol -> for structures in GNU c. The compiler does not complain when symbol . used in place of ->.
.is used to access members of a structure;->is used to access members of a structure pointed to. The latter dereferences the pointer and then gets the member. Sop->xis equivalent to(*p).x. Example: ``` struct P { int x; int y; }; struct P myP = {1,2}; struct P *p= &myP; printf("%d, %d\n", myP.x, myP.y); // prints 1, 2 printf("%d, %d\n", p->x, p->y); // prints the same printf("%d, %d\n", (*p).x, (*p).y); // is the same ```
How will we print the below pattern in C language? Please explain the logic. ``` 1 12A 123BA 1234CBA 12345DCBA 123456EDCBA 1234567FEDCBA 12345678GFEDCBA 123456789HGFEDCBA 12345678910IHGFEDCBA ```
Please explain the logic. To printnum_linesof that patternfor eachlinefrom1to includingnum_linesdo:printnum_lines - linespacesprint each numberifrom1to includinglineprint each character from'A' + line - 2to including'A'print a newline characterrepeat
I defined a struct and I do not want to put the volatile into the struct because other instance may not need it (e.g. RAM caching). Now I need that a particular array of this struct be volatile. ``` typedef struct{ uint8_t rxPacket[FIFO_SIZE]; uint8_t length; int8_t rssi; uint8_t lqi; }rawRx_t; ``` Is this the right way to have each (struct) element of the array volatile ? ``` static volatile rawRx_t rawRxBuffer[NB_MAX_RX_FRAME]; ```
Yes. Paring it down and switching the type to somethingcdecl.orgcan parse, we get: ``` volatile int rawRxBuffer[]; ``` and the corresponding output is: ``` declare rawRxBuffer as array of volatile int ``` the point is that it's an "array of volatile", i.e. each array element is volatile.
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.Closed4 years ago.Improve this question I am trying to use side effect operator in my expression which does not have just a variable. My program was compiled successfully but I got a runtime error "Segmentation fault" Here is my code: ``` int main() { int x = 1; printf(1 + (x++)); return 0; } ```
C requires you to format the string, this way it knows what it should print. What you have in your example is nothing but memory addresses, which makes the C compiler confused. ``` int main() { int x = 1; printf("%d\n", (1 + (x++))); return 0; } ```
If I read the generated C code from "Hello World!" in Nim, I see this line STRING_LITERAL(TM_xLHv575t3PG1lB5wK05Xqg_2, "Hello world!", 12); How is the sequenceTM_xLHv575t3PG1lB5wK05Xqg_2created? Is the Nim compiler actually generating this name from itself, or does it use pre-defined names for variables when translating to C?
It is generating the names using md5 hash of a module info as a base. The process is mostly confined to thecompiler/cgen.nimfile. The actual name comes from here:https://github.com/nim-lang/Nim/blob/d5da450100f35008df06ecf812f1eeabda05d285/compiler/cgen.nim#L233 The components of the name are derived from the module parameters here:https://github.com/nim-lang/Nim/blob/d5da450100f35008df06ecf812f1eeabda05d285/compiler/cgen.nim#L1468
I understand there is an increment of ii and x shifts left, but how does it go from 1 to being 3? Then from 13(D) to being 69? and so on... ``` #include <stdio.h> int main() { int x = 1; int ii; for (ii = 0; ii < 8; ii++) { x = (x << ii) | 1; printf("0x%.8X\n", x); } return (0); } ``` and This is the output ``` 0x00000001 0x00000003 0x0000000D 0x00000069 0x00000691 0x0000D221 0x00348841 0x1A442081 ```
Just write everything on a paper in binary to understand it, like that: 1 = 0000 0001 i:1 ... 0000 0010 | 0000 0001 = 0000 0011 (hex: 3) i:2 ... 0000 1100 | 0000 0001 = 0000 1101 (hex: d) i:3 ... 0110 1000 | 0000 0001 = 0110 1001 (hex: 69) i:4 ... etc.
I've looked for C APIs, but I've only found C++ API's that can't be used inside a C code. Are there any C (not C++ or C#) APIs or another way for using AMPL in a C code?
There being no C API for AMPL as far as I can tell, your best bet is to write C++ wrappers for the tasks you want to perform, assigning them C linkage (extern "C") and building them with a C++ compiler. Done correctly, these will be callable from C code. The C code will not be able to handle AMPL objects directly, however, so your wrappers will need to perform some kind of data marshaling in both directions. I do recommend wrappers specific to your particular tasks, as opposed to generic wrappers for the whole API. I suspect that you would find the latter a much larger and more difficult task.
In my Makefile im doing like: ``` BINS = 1 2 3 4 ``` then ``` OBJS := $(patsubst %,%.o,$(BINS)) ``` This prints:1.o 2.o 3.o 4.o But I want it to look like: ``` 1/1.o 2/2.o 3/3.o 4/4.o ``` When I do it like this: ``` OBJS := $(patsubst %,%/%.o,$(BINS)) ``` I get: ``` 1/%.o 2/%.o 3/%.o 4/%.o ``` How can I accomplish what I need?
Make isn't very good with dummy variables, but you can usetheforeachfunction: ``` BINS = 1 2 3 4 OBJS := $(foreach bin,$(BINS),$(bin)/$(bin).o) ```
I've created a database using mysql, and now i need to connect it with C, basically just to call some functions, already created in SQL. I've installed the "C Connector" from mysql website. When i try to compile my program usinggcc db.ci have this error: db.c:2:19: fatal error: mysql.h: No such file or directory compilation terminated. So, looking on the forum I understood that i need to include 'mysql.h' path when i compile my program, using -I, but it stills gives me an error. The path where is mysql.h is the following: C:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include Any idea?
You can try this: ``` gcc db.c -l mysql ``` That is usually how you compile programs with libraries such as this. if that does not work, try following this link:https://dev.mysql.com/doc/refman/5.7/en/c-api-building-clients.html
I tried to send snmp UDP packet through vlan interface by using "setsockopt bind to interface", but in client side when i capture packet using wireshark i can capture the packet both in eth0.4092 and eth0. 1:I tried to bind the interface name using setsockopt, its working but packet reaching at eth0 and eth0.4092 2:I tried with bind to specific address , no change expected:The packet should reach only at vlan interface.
It is expected, packet with vlan tag reach at eth0 and vlan tag removed packet reach at eth0.4092, vlan is a software feature so the packet should reach at physical interface then only it moves to virtual interface.
I know that a static local variable is in existence for the life of a program. But does a static local variable maintain the same memory address? Or does the compiler just ensure that it exists and can be accessed within the local scope?
In C objects don't move around during their lifetime. As long as an object exists, it will have the same address. Variables with static storage (this includes variables with block scope declared asstatic) have a lifetime that covers the whole execution of the program, so they have a constant address.