question
stringlengths
25
894
answer
stringlengths
4
863
Does thebind()function in linux can modify its argument ? I ask this because asin_portof 0 means that the OS will choose the port, and I would like to get this port after this call.
No, it does not modify the argument. Instead you usegetsocknameafter binding to find out what port you got. You can also usegetsocknameafterconnectto get both the local port assignmentandthe local address (if you have more than one address) correspomnding to the route to the remote host. This works even with UDP whereconnectdoesn't actually send any packets and only logically binds addresses.
I have tried to understand the connection between pointers and arrays. Why this prints"okkoD@@"? Please help. ``` #include <stdio.h> int main(){ char a = 'o'; char b = 'k'; char uga[2]; *(uga) = a; *(uga+1) = b; printf("%s", uga); } ```
It is because a string in C is terminated by 0. So when you do thisprintf("%s", uga);the function will print the characters until it find the 0 element, then it stops. But there is none inuga, so it will keep printing characters from the stack. It is an undefined behavior. Try this ``` #include <stdio.h> int main(){ char a = 'o'; char b = 'k'; char uga[3]; *(uga) = a; *(uga+1) = b; *(uga+2) = 0; // adding string terminating 0 printf("%s", uga); } ```
This question already has answers here:Sizeof returning incorrect array length [duplicate](4 answers)Closed3 years ago. I'm trying to dynamically allocate an array of size 10. But when I print the elements of the array, I get value of 8 elements. (I'm working on the editor provided by hackerrank.) ``` #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { char *s = malloc(1024*sizeof(char)); scanf("%[^\n]", s); int* freq = (int*)calloc(10,sizeof(int)); for(int i=0;i<sizeof(freq);i++) printf("%d ",freq[i]); } ``` Expected output: ``` 0 0 0 0 0 0 0 0 0 0 ``` The output I'm getting: ``` 0 0 0 0 0 0 0 0 ``` Why am I not getting the expected output?
sizeof(freq)will return the size ofint *in bytes in your machine which happens to be 8. Just usei < 10.
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 Is there a way to storefloatvariable for example: PI (3.1415) toint16_tarray, and then print it using pointers?
Size offloatis 4 byte, while size ofint16_tis 2 byte. You can use 2 xint16_telements of array to store singlefloat. ``` #include <math.h> #include <stdint.h> #include <stdio.h> #include <string.h> int main() { const float float_var = M_PI; int16_t int16_arr[10]; // save memcpy(int16_arr, &float_var, sizeof(float)); // load float another_float_var; memcpy(&another_float_var, int16_arr, sizeof(float)); printf("%f\n", another_float_var); } ```
This is the first time I am seeing something like this where a function is like a pointer (but it is not a function pointer ??). See example below. ``` static struct test *MyFunc(struct astr *A, int count) { } MyFunc(B, 100); ``` Can someone explain how the above works as well as why you would use a pointer function (if that is the correct term) as well as why not simply use ``` static struct test MyFunc(struct astr *A, int count) ```
Think of it this way: ``` static (struct test *) MyFunc(struct astr *A, int count) ```
I have a lot of buttons in my gtk program and they have same callback function. How to avoid duplication. For example: ``` g_signal_connect(G_OBJECT(button1), "clicked", G_CALLBACK(button_clicked), data); g_signal_connect(G_OBJECT(button2), "clicked", G_CALLBACK(button_clicked), data); g_signal_connect(G_OBJECT(button3), "clicked", G_CALLBACK(button_clicked), data); g_signal_connect(G_OBJECT(button4), "clicked", G_CALLBACK(button_clicked), data); ``` and do something like this ``` g_signal_connect(G_OBJECT(four_buttons), "clicked", G_CALLBACK(button_clicked), data); ``` How can I do it? Thanks in advance
Use a loop: ``` GtkButton *buttons[] = { button1, button2, button3, button4 }; for (int index = 0; index < 4; index++) g_signal_connect(G_OBJECT(buttons[index]), "clicked", G_CALLBACK(button_clicked), data); ```
How can I write following C expression using left-shift bit-wise operator (<<) and plus sign (+)? ``` y = x * 6; ```
x << nmeans x * 2nby definiton (C18 §6.5.7/4). Knowing that x * 6 means x * 2 + x * 4, which is x * 21+ x * 22, we can rewritey = x * 6;asy = (x << 1) + (x << 2);.
This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Closed3 years ago. I was searching pointers in C and on a given website I found the following usage: ``` int main() { int i; int array[5] = {10, 20, 30, 40, 50}; for(i = 0; i < 5; i++) { printf("%d\n", i[array]); /* Instead of "array[i]"" */ } return 0; } ``` How does it happen and why doesprintffunction understand this?
In Ca[b]will essentially became*(a + b)so if you would dob[a]you would get*(b + a)which is the same. That is why this code works.
I need a simple function that has 3 variables: l (left), m (middle), and r (right) So ``` int l,m,r ``` And when I put in the number 27.2 l should become 2 m should become 7 r should become 2 I can think of dividing the left 2 by deviding by 10 and then cast to int but the other 2 numbers?
Let your number be stored in x. ``` float x = 36.2; x = x*10; int r = (int)x%10; x = x/10; int m = (int)x%10; x = x/10; int l = (int)x%10; printf("%d, %d, %d",l, m, r); ```
I am struggling with calling function that has pointer before it. We have school project to code our own malloc version. Problem is following: I call function like this:char *ptrr = (char*)memory_alloc(10); Function header is this:void *memory_alloc(unsigned int size) And i get fault like this: Cast from pointer to integer of different size. Thanks for any ideas.
Your compiler suspects that you are trying to cast a pointer to an integer.Usually, we get this warning when we try to write something like this: ``` void myFunction (int i) { // .... } int main() { void *p; // = NULL, malloc, calloc, ... myFunction ( (int) p); return 0; } ``` I suggest you look in your code (ideally post it in your question), if you don't have a cast like this.
Below I have an algorithm that is meant to return an integer value that represents the height of a binary tree and I have been asked to find out what the time complexity of it would be, here is the code: ``` struct Node { int data; struct Node *left; struct Node *right; } int FindHeight(struct Node *root) { if (root == NULL) return -1; return max(FindHeight(root->1eft),FindHeight(root->right)) +1; } ``` I'm I right in thinking that this would be 0(1)? Thank you so much in advance.
It is not justif-statement. It ismaxwith recursive call. For your code, the recursion go through all nodes. It goes through each node once so the time complexity is linearO(n). The depth of recursion may vary depending on tree structure. If tree is degenerated the memory complexityO(n). In case of balanced tree, memory complexity isO(ln(n)).
I am studying the C language. When I pass a pointer to gets(), I find it can work well. ``` char *ptr; gets(ptr); puts(ptr); ``` But if I define an array of pointers, it doesn't work. ``` char *ptr[4]; int i=0; for(i=0;i<4;++i) gets(ptr[i]); for(i=0;i<4;++i) puts(ptr[i]); ``` Are they different, or is the first part wrong in fact? I want to know the reason.
You pass a pointer to a function (e.g.gets()) that writes data to a memory location pointed by your pointer. In your case, you have theuninitializedpointer, which means it points to a random memory location (where applications or an operating system resides). This leads to random effects - from "working" to abnormal termination or hanging. You need to reserve memory and assign pointer to point there, e.g. by: ``` char *ptr = (char*)malloc(256); gets(ptr); puts(ptr); free(ptr); ``` Consider to usegets_s()that is more secure.
I have a function to convert byte[] to long in java like this. The length of the array (byte[]) can be 4, 6 or 8 bytes. ``` public long toLong(byte[] dtIn) { try { return Long.parseLong(new String(dtIn).trim()); } catch (Exception ex) { ex.printStackTrace(); } return -1; } ``` Is there a function that is the same as the function above in JNI (C language).?
You can implement like following in JNI C. ``` unsigned long int l = pSrc[0] | (pSrc[1] << 8) | (pSrc[2] << 16) | (pSrc[3] << 24); ``` Here pSrc is the source byte array.
Yesterday I saw the below code. As you can see it hasn't got anybreakI predicted that it would print "354" because I thought thedefaultpart would be finally evaluated (after checking all the cases.) But that isn't practically correct as it printed "345". Can somebody explain the reason? ``` int main () { int a = 2; switch (2*a-1) { case 1: printf ("1"); case 2: printf("2"); case 3: printf("3"); default: printf("4"); case 5: printf("5"); } } ```
Since2*a-1is 3, the code jumped to thecase 3label and kept running from there. The other labels were ignored because no code ever jumped to them. Thedefaultlabel is only jumped to if the value in theswitchdoesn't match any of thecaselabels.
I am trying to ensure that TCP_NODELAY is set (Nagle disabled) for Postgres client and server. I can see that there is code in libpq to use the option when a TCP_NODELAY macro is defined. I've cloned the postgres repo, run: ``` ./configure make CPOT='-DTCP_NODELAY' ``` and tried to link against the resulting static library. That results inundefined reference to symbol 'inet_net_ntop@@GLIBC_2.2.5'adding-lresolvfixes that and then there are a number of other undefined reference issues. I haven't been able to find any official documntation on postgres and TCP_NODELAY. Does libpq and postgres server use TCP_NODELAY by default? Or not? Am I on the right track above? It seems like there should be an easier way?
You are on the right track, but the correct way would be ``` ./configure CPPFLAGS=-DTCP_NODELAY make make install ``` No, PostgreSQL does not useTCP_NODELAYby default.
In a scenario, where I am listening on a TCP port viaINADDR_ANY, and get a client connection, and now want to accept UDP packets from that connection, how can I determine the actual IP address of the interface that routes to that client to bind the UDP socket to that interface instead of INADDR_ANY?getsocknameof my listening socket would returnINADDR_ANYas far as I understand, so is there some other socket API that can provide this info? Or must I manually keep a route table where I try to resolve each client by connecting to it (or send ARP on all interfaces and see which one resolves the address?).
Once you have accepted the connection, you can get the local address of the new (connected) socket thatacceptreturned, with thegetsocknamefunction.
For some reason, I want to get the address ranges of a stack. For example, consider the following example: ``` int main(){ int a = 0; int b = 0; } ``` Is there any generic way I can know the address of a and b (and another other variable on stack), without explicitly use&ain code? Thanks!
Memory address in general, and stacks in particular, are system specific. There exists no way to obtain such information in standard C, nor is there a way to set the stack pointer in C. In fact if youdon'tuse the&operator, the variables are quite likely to get allocated in registers instead of the stack. For the rare case where you actually need to know the stack address, for example when dealing with low level embedded systems, you'd typically go check a linker script and hardcode the value, or use some specific non-standard compiler extension.
Considerarrayis an array of variables of typestructure(struct). When you pass an array of structs as a parameter to a function, you access it with the dot (.) operator:array[0].structField1 Shouldn't it be accessed with the arrow (->) operator, since we're passing the address of the first element of the array, like:array[0]->structField1
The array index operator[]contains an implicit pointer dereference. So ifarrayhas either array-of-struct or pointer-to-struct type, thenarray[0]has struct type and not pointer type.
In a scenario, where I am listening on a TCP port viaINADDR_ANY, and get a client connection, and now want to accept UDP packets from that connection, how can I determine the actual IP address of the interface that routes to that client to bind the UDP socket to that interface instead of INADDR_ANY?getsocknameof my listening socket would returnINADDR_ANYas far as I understand, so is there some other socket API that can provide this info? Or must I manually keep a route table where I try to resolve each client by connecting to it (or send ARP on all interfaces and see which one resolves the address?).
Once you have accepted the connection, you can get the local address of the new (connected) socket thatacceptreturned, with thegetsocknamefunction.
I just wrote a basic c program to run but compiler prompts the error (see attached image). I have installed Dev-C++ before where I did C++ Programming. But when I wrote C code it prompts error I have deleted it & reinstalled the Dev-C++ again but couldn't run please help. IDE Version: 5.11
You must choose the right Project configuration (C project): Remarque : you must have a project path without space. Exemple :C:\Ali\untiled\untiled.c
I'm using an STM32F429ZI chip on my setup. On it I'm using LWIP to handle ethernet packets. When the controller gets a packet, it runs the callback function and reprograms the flash using one of the IAP examples. We've left the IWDG disabled while creating and testing this section. The section works, but when IWDG is reenabled, if crashes only on this particular callback example. I have another callback that takes a message and sends back some status stuff. This does work with IWDG enabled. To be clear, the board only resets on the tftp callback. I've stuff a number of IWDG counter resets all over the tftp file, but it changes nothing. The crash also seems to be different that an IWDG restart. See tftpserver.chere
Turns out our prescaler was way too low. Upped it from 4 (0.125s) to 16(0.5s). Good facepalm to myself.
Below is my final code but no output has been printed in the console. Please help me to find the mistake. ``` #include<stdio.h> #include<string.h> int main() { char s[10] = "Gokul"; int len = 0; while(s[len] != '\0'); len++; for(int i = 0; i < len; i++){ for(int j = 0; j < len; j++){ if(j==i || j == (len-i-1)){ printf("%c", s[i]); } else printf(" "); } printf("\n"); } return 0; } ```
``` while(s[len] != '\0'); len++; ``` Mistake is here.The body of your loop isemptyNext time, use a debugger.
So I've been tried C for like one week and now I'm starting with buffers and everything going with that. I saw many things like ``` char buffer[1024]; ``` So I wonder what they means and how we know what to write between the[ ] (I'm not very familiar with the vocabulary so forgive me if it's absolutely not clear). Thanks
In C, we use[]to define an array of the given type. for example: ``` char buffer[1024]; ``` is nothing but an array of characters (typechar) with length of 1024.and you can access each array member by its index, starting from 0.As an example: ``` int number[10]; int i; ... for (i=0; i<10; i++) { number[i] = i * i; } ... for (i=0; i<10; i++) { printf("Number %d is : %d\n", i, number[i]); } ``` I think reading more about arrays and different data-types in C will help you with that.
I just wrote a basic c program to run but compiler prompts the error (see attached image). I have installed Dev-C++ before where I did C++ Programming. But when I wrote C code it prompts error I have deleted it & reinstalled the Dev-C++ again but couldn't run please help. IDE Version: 5.11
You must choose the right Project configuration (C project): Remarque : you must have a project path without space. Exemple :C:\Ali\untiled\untiled.c
I'm using an STM32F429ZI chip on my setup. On it I'm using LWIP to handle ethernet packets. When the controller gets a packet, it runs the callback function and reprograms the flash using one of the IAP examples. We've left the IWDG disabled while creating and testing this section. The section works, but when IWDG is reenabled, if crashes only on this particular callback example. I have another callback that takes a message and sends back some status stuff. This does work with IWDG enabled. To be clear, the board only resets on the tftp callback. I've stuff a number of IWDG counter resets all over the tftp file, but it changes nothing. The crash also seems to be different that an IWDG restart. See tftpserver.chere
Turns out our prescaler was way too low. Upped it from 4 (0.125s) to 16(0.5s). Good facepalm to myself.
Below is my final code but no output has been printed in the console. Please help me to find the mistake. ``` #include<stdio.h> #include<string.h> int main() { char s[10] = "Gokul"; int len = 0; while(s[len] != '\0'); len++; for(int i = 0; i < len; i++){ for(int j = 0; j < len; j++){ if(j==i || j == (len-i-1)){ printf("%c", s[i]); } else printf(" "); } printf("\n"); } return 0; } ```
``` while(s[len] != '\0'); len++; ``` Mistake is here.The body of your loop isemptyNext time, use a debugger.
So I've been tried C for like one week and now I'm starting with buffers and everything going with that. I saw many things like ``` char buffer[1024]; ``` So I wonder what they means and how we know what to write between the[ ] (I'm not very familiar with the vocabulary so forgive me if it's absolutely not clear). Thanks
In C, we use[]to define an array of the given type. for example: ``` char buffer[1024]; ``` is nothing but an array of characters (typechar) with length of 1024.and you can access each array member by its index, starting from 0.As an example: ``` int number[10]; int i; ... for (i=0; i<10; i++) { number[i] = i * i; } ... for (i=0; i<10; i++) { printf("Number %d is : %d\n", i, number[i]); } ``` I think reading more about arrays and different data-types in C will help you with that.
I am getting an error while running the output(a.exe) of a C program. Command prompt showing "Access is denied". I have reinstalled gcc but same problem is arriving.Here is the screenshot of error
That output is seen, when you try to run a x64 binary on a x86 system. But there are numerous other possibilities. Another likely possibility is your Antivirus realtime scanning. Be sure it does not block access for you. Provide more details and I'll update this accordingly.
This question already has answers here:convert vector<string> into char** C++(4 answers)Closed3 years ago. The API expects an array of zero-terminated c-strings (char*). The array itself is to be terminated with a null pointer (nullptr).
How about using std::transform? ``` #include <iostream> #include <string> #include <vector> #include <algorithm> int main() { std::vector<std::string> v = {"asd","qwe"}; const char** c = new const char*[v.size()]; std::transform(v.begin(), v.end(), c, [](const std::string& s) { return s.c_str(); }); for (size_t i=0;i<v.size();i++) { std::cout << c[i] << std::endl; } delete[] c; return 0; } ``` But do mind that the array(herec) should be in the same scope as the vector(herev) or the vector should not get destroyed before the use of the array(c) is over. If you want achar**instead and notconst char**, you can use.data()instead of.c_str()
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 I have this Macro: #define INLINE __attribute((always_inline)) inline and I want it to turn this: ``` INLINE void DoStuff() { } ``` into this: ``` __attribute__((always_inline)) inline void DoStuff() { } ``` But I am getting this error upon compilation: "declaration does not declare anything" in the macro's expansion. What am I doing wrong?
This the correct way for the gcc family compilers ``` #define INLINE inline __attribute__((always_inline)) int INLINE add(int x, int y) { return x + y; } int main() { printf("%d", add(rand(), rand())); } ``` https://godbolt.org/z/BM6Wjw
Why the error does not occur when I put a float number? ``` int m; if(scanf("%d%",&m)!=1) { printf("Error\n"); exit(1); } ```
Because%dwill consume all decimal digits until the first non-decimal digit. So if you enter"50.5"mwill have the value 50 and the characters".5"will remain in the buffer unread. There are many possible solutions. Here's one: ``` int m ; double fm ; if( scanf("%f%",&fm) != 1 || modf( fm, &m) != 0 ) { printf("Error\n"); exit(1); } ```
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 For example, if I have code in C or C++ where I use typedef to create different kinds of strings like this: ``` typedef char shortString[20]; typedef char longString[50]; typedef char veryLongString[100]; ``` Does doing so actually use up less memory than if I were to have just one typedef string for all my string variables like this? ``` typedef char string[100]; ```
Yes. A typedef is just an alias for a type. So it's equivalent to "Does using an array of 50 characters for a variable use less memory than an array of 100 characters?" Note that if you're using multiple array lengths for strings, it can be complicated to avoid buffer overruns by ensuring you always use the correct length when working with them.
``` struct ListNode { int val; struct ListNode *next; }; struct ListNode* test = malloc(sizeof(struct ListNode*)); test->val = 6; struct ListNode* lex = malloc(sizeof(struct ListNode*)); test->next = lex; return test; ``` At the point I should receive a populated struct. Instead I get this: ``` Line 14: Char 18: runtime error: store to address 0x602000000118 with insufficient space for an object of type 'struct ListNode *' (solution.c) 0x602000000118: note: pointer points here be be be be 00 00 00 00 00 00 00 00 02 00 00 00 ff ff ff 02 08 00 00 20 01 00 80 70 be be be be ``` What's going on here?
You are only allocating space for a ListNode pointer not an actual ListNode. try:struct ListNode* test = malloc(sizeof(struct ListNode));
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 For example, if I have code in C or C++ where I use typedef to create different kinds of strings like this: ``` typedef char shortString[20]; typedef char longString[50]; typedef char veryLongString[100]; ``` Does doing so actually use up less memory than if I were to have just one typedef string for all my string variables like this? ``` typedef char string[100]; ```
Yes. A typedef is just an alias for a type. So it's equivalent to "Does using an array of 50 characters for a variable use less memory than an array of 100 characters?" Note that if you're using multiple array lengths for strings, it can be complicated to avoid buffer overruns by ensuring you always use the correct length when working with them.
``` struct ListNode { int val; struct ListNode *next; }; struct ListNode* test = malloc(sizeof(struct ListNode*)); test->val = 6; struct ListNode* lex = malloc(sizeof(struct ListNode*)); test->next = lex; return test; ``` At the point I should receive a populated struct. Instead I get this: ``` Line 14: Char 18: runtime error: store to address 0x602000000118 with insufficient space for an object of type 'struct ListNode *' (solution.c) 0x602000000118: note: pointer points here be be be be 00 00 00 00 00 00 00 00 02 00 00 00 ff ff ff 02 08 00 00 20 01 00 80 70 be be be be ``` What's going on here?
You are only allocating space for a ListNode pointer not an actual ListNode. try:struct ListNode* test = malloc(sizeof(struct ListNode));
I tried to google and quick search on latest draft for "C lang" and "C18" on openstd org. Will C++ standard support the latest standards of C?
C++ is a general purpose programming language based on the C programming language as described inISO/IEC 9899:2018Programming languages — C (hereinafter referred to as the C standard).C++ provides many facilities beyond those provided by C, including additional data types, classes, templates, exceptions, namespaces, operator overloading, function name overloading, references, free store management operators, and additional library facilities. http://eel.is/c++draft/intro.scope C18 (previously known as C17) is the informal name forISO/IEC 9899:2018, the most recent standard for the C programming language, published in June 2018. It replaced C11 (standard ISO/IEC 9899:2011). https://en.m.wikipedia.org/wiki/C18_(C_standard_revision)
I've been stuck on a bonus my professor gave for a couple of days now: give x^y using only ~ and &Assume the machine use twos complement, 32-bit representations of integers. I've tried many different combinations, and also tried to write out the logic of the operator ^, but it hasn't been working out. Any hints or help would be much appreciated!
The XOR operator can in fact be written as a combination of those two. I'll put this in two steps: A NAND B = NOT(A AND B)A XOR B = (A NAND (A NAND B)) NAND (B NAND (A NAND B)) As described before on math: https://math.stackexchange.com/questions/38473/is-xor-a-combination-of-and-and-not-operators
I tried to google and quick search on latest draft for "C lang" and "C18" on openstd org. Will C++ standard support the latest standards of C?
C++ is a general purpose programming language based on the C programming language as described inISO/IEC 9899:2018Programming languages — C (hereinafter referred to as the C standard).C++ provides many facilities beyond those provided by C, including additional data types, classes, templates, exceptions, namespaces, operator overloading, function name overloading, references, free store management operators, and additional library facilities. http://eel.is/c++draft/intro.scope C18 (previously known as C17) is the informal name forISO/IEC 9899:2018, the most recent standard for the C programming language, published in June 2018. It replaced C11 (standard ISO/IEC 9899:2011). https://en.m.wikipedia.org/wiki/C18_(C_standard_revision)
I've been stuck on a bonus my professor gave for a couple of days now: give x^y using only ~ and &Assume the machine use twos complement, 32-bit representations of integers. I've tried many different combinations, and also tried to write out the logic of the operator ^, but it hasn't been working out. Any hints or help would be much appreciated!
The XOR operator can in fact be written as a combination of those two. I'll put this in two steps: A NAND B = NOT(A AND B)A XOR B = (A NAND (A NAND B)) NAND (B NAND (A NAND B)) As described before on math: https://math.stackexchange.com/questions/38473/is-xor-a-combination-of-and-and-not-operators
I've been stuck on a bonus my professor gave for a couple of days now: give x^y using only ~ and &Assume the machine use twos complement, 32-bit representations of integers. I've tried many different combinations, and also tried to write out the logic of the operator ^, but it hasn't been working out. Any hints or help would be much appreciated!
The XOR operator can in fact be written as a combination of those two. I'll put this in two steps: A NAND B = NOT(A AND B)A XOR B = (A NAND (A NAND B)) NAND (B NAND (A NAND B)) As described before on math: https://math.stackexchange.com/questions/38473/is-xor-a-combination-of-and-and-not-operators
I am writing logger for my embedded application. I need to write all logs to file. Currently I am opening and closing file for every write. To improve performance, is it safe to keep log file open throughout the application scope and call fflush() without closing file for every write ?
If you read the linux programmer's manual, you will find out that fclose will "flushes the stream pointed to by stream and closes the underlying file descriptor". So, you can just call fclose() without fflush(). If you want to write in same file multiple times. you can hold the file opened, and just call fflush multiple times. "fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function". In a word, fflush write buffered data to file, fclose write buffered data and close file.
PostgreSQL makes use ofbackground workersto allow processes working in a concurrent fashion and they have an API for backend/extension developers to control them. So far, I have managed to successfully work with this feature in a demo extension, successfully spawning a number of workers. I am in a situation where one of my workers has to wait for another to finish. What I am doing so far is an infinite loop on an idle worker until the worker being waited for is finished, which can be quite inefficient. So I was wondering how would I go about making the idle process sleep until some signal is sent? What would I be looking for? Is there an extension which does something similar so that I could use for guidance?
I think the official way to do something like this is with condition variables, implemented in the file src/backend/storage/lmgr/condition_variable.c I don't see it being used in any "contrib" extensions, however, just the core code.
Suppose, in C language I have the following code, where pointer variable "word" points to a string literal. ``` const char * word = "HELLO"; ``` Why does this works - ``` printf("\nword[1]: '%c'", word[1]); printf("\nword[2]: '%c'", word[2]); ``` and this doesn't ? ``` printf("\nAddress of word[1]: %p", word[1]); printf("\nAddress of word[2]: %p", word[2]); ```
because the latter is char not pointer.word[1]is the same as*(word + 1)and you just dereference the char pointer. The result ischar you need to: ``` printf("\nAddress of word[1]: %p", (void *)&word[1]); printf("\nAddress of word[2]: %p", (void *)&word[2]); ``` or ``` printf("\nAddress of word[1]: %p", (void *)(word + 1)); printf("\nAddress of word[2]: %p", (void *)(word + 2)); ```
This question already has answers here:Size of character ('a') in C/C++(4 answers)Closed3 years ago. When I run the program below in C, I get the output result to be4. ``` #include <stdio.h> //using namespace std; int main() { printf("%d", sizeof('a')); return 0; } ``` But when I run the code below in C++, I get the output result to be1. ``` #include <iostream> using namespace std; int main() { printf("%d", sizeof('a')); return 0; } ``` Could you please explain why do I get different output for the same code as if'a'is the way we define characters in both the languages ?
In C, a character representation (like'a') has typeint. So,sizeofoperator returns the size of an integer. In C++, it's of a character type.
I'm a beginner with C and am playing with pointer and arrays. Let's say I have the following function ``` GetArrayValues(uint8**pValues, uint32 *pNumValues); ``` where: ``` **pValues points to the first element of the array *pNumValues points to the number of values in the array ``` Let's suppose the array contains 100 uint8 elements. Now each time I call the functionGetArrayValues()I would like to copy all 30 elements starting from index 20 into a new array: ``` uint8 myInternalArray[30] ``` What is the fastest way to do this?
you want something like this ``` void *arrcpy(const void *src, void *dest, size_t pos, size_t len, size_t elemsize) { const unsigned char *csrc = src; memcpy(dest, csrc + pos * elemsize, len * elemsize); } ```
-Wall -Werrorare already set. I need to add some flag to make unused-s not error but warning.-Wno-unuseddiscards warnings at all. I want to see warning and succeed compilation. How? I tried:-Werror=no-unusedbut it does not work. GCC 9.
From theGCC manual: -Werror=Make the specified warning into an error. The specifier for a warning is appended; for example-Werror=switchturns the warnings controlled by-Wswitchinto errors. This switch takes a negative form, to be used to negate-Werrorfor specific warnings; for example-Wno-error=switchmakes-Wswitchwarnings not be errors, even when-Werroris in effect. So the option you want to pass is-Wno-error=unused.
I am trying to copy a string into my struct array. I get the following error message: error: expected ';', ',' or ')' before '.' token for the bold line. I tried different variants but without success. ``` #include <stdio.h> #include <string.h> typedef struct Album { char Interpret[20]; char Titel[10]; int Jahr; int Zustand; } album; album regal[2]; strcpy(char *regal[0].Interpret, "Led Zeppelin"); // here int main() { return 0; } ```
You're attempting to run a statement (a function call in this case) outside of a function. It should be moved insidemain: ``` int main () { strcpy(regal[0].Interpret, "Led Zeppelin"); return 0; } ```
i'm implementing a HLS solution for a project, so I can't use malloc functions. At this moment I have this C code: ``` unsigned short int * samples = NULL; samples = (unsigned short int *)malloc(12*sizeof(unsigned short int)); ``` Can I use: ``` unsigned short int * sample[23]; ``` to implement it?
You have two choices - either declare an array with a fixed size: ``` unsigned short int samples[12]; ``` Or if you're using C99 or newer, a VLA (watch out for stack overflows): ``` int n = 12; unsigned short int samples[n]; ``` The latter would more often seenas a function parameter: ``` void do_something(int n) { unsigned short int samples[n]; ... } ```
I´ve found this piece of code, which uses a pointer to a structure made by a compound literal: ``` int main() { struct s {int i; int x;} *p; int j = 0; p = &((struct s){ j++ }); } ``` My questions are: How isj++a valid expression for modifyingiand/orxand to what it get evaluated?And how can I access the memberiorx? Pointer offsets ofp?
In a compound literal, any unspecified members get default-initialized, just like an initializer list for an object. So ``` (struct s){ j++ }) ``` is equivalent to ``` (struct s){ j++, 0 }) ``` j++is the old value ofjbeforejis incremented, just as in any other assignment. So this will setp->i = 0andj = 1. You can access the members using pointer dereferencing. ``` int x = p->x; int i = p->i; ```
I've got a function which expects a variable and a pointer. ``` void sendCMD(byte cmd, byte data[]){ ... } ``` Is it possible to call this function with the data in anyway like so ``` sendCMD(0xff, { 0x0a, 0x02 }); ``` Since even by googleing I didn't find anything... maybe I haven't looked hard enough, but I'm also not exactly sure what the terms are I should be looking for. Any help is kindly appreciated! Note thatbyteis the same thing as achar!
You can use acompound array literal: ``` sendCMD(0xff, (byte[]){ 0x0a, 0x02 }); ```
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 am currently working on a project which requires me to learn about CMake and GMake. I read about them but still don't get their applications. Can someone provide a few examples of how CMake and GMake are used in software development? Thank You.
makeorgmakeusesMakefiles to describe how to build your code. AMakefilecontains targets and recipes. A target can be an object file or executable and the recipe is how to produce that target. cmakeis a higher level language with the same purpose but with a higher level of abstraction. Withcmakeyou can generate ordinaryMakefilesor files for other build systems, such as Ninja etc.
There is no re-negotiation in TLS1.3, will SSL_write yield SSL_ERROR_WANT_READ? And will SSL_read yield SSL_ERROR_WANT_WRITE? Here are openssl docs in SSL_write and SSL_read
I created an issue in github, and got the developer's answer. https://github.com/openssl/openssl/issues/11211#event-3094172350 In TLS1.3, SSL_write can yield SSL_ERROR_WANT_READ, and SSL_read also can yield SSL_ERROR_WANT_WRITE
This question already has answers here:Square of a number being defined using #define(11 answers)Closed3 years ago. ``` #define x 10 + 5 int main(){ int a = x*x; printf("%d",a); } ``` Can someone explain the difference between these codes? first output is 65 and second one is 225: ``` #define x 15 int main(){ int a = x*x; printf("%d",a); } ```
Everything is related to the priority of operators in mathematics and in C.In the first case,xis replaced by10 + 5sox*xis replaced by10 + 5 * 10 + 5, which equals to 65.As suggest in comments, you should use parenthesis to avoid this problem. ``` #define x (10 + 5) int main(){ int a = x*x; printf("%d",a); } ```
``` #include<stdio.h> int main() { int n,i; float sum=0; scanf("%d",&n); for(i=1;i<=n;i++) { printf("1/%d +",i); sum=sum+1/i; } printf("= %f",sum); return 0; } ``` In this code I've kept thesumvariablefloatto see the values after decimal. But the result doesn't appear to be correct.000000is shown after decimal. Why is this happening? What should I do to get the correct value without changing other variable's datatype? When I change other variables to float datatype,the answer remains correct.
Because both1andiare integers, the expression1/iis evaluated as integer. Therefore, ifi > 1then1/i == 0. You can solve this usingfloat(1)/ior1/float(i)orfloat(1)/float(i).
``` #include<stdio.h> int main() { int n,i; float sum=0; scanf("%d",&n); for(i=1;i<=n;i++) { printf("1/%d +",i); sum=sum+1/i; } printf("= %f",sum); return 0; } ``` In this code I've kept thesumvariablefloatto see the values after decimal. But the result doesn't appear to be correct.000000is shown after decimal. Why is this happening? What should I do to get the correct value without changing other variable's datatype? When I change other variables to float datatype,the answer remains correct.
Because both1andiare integers, the expression1/iis evaluated as integer. Therefore, ifi > 1then1/i == 0. You can solve this usingfloat(1)/ior1/float(i)orfloat(1)/float(i).
I don't know why I get this error withchdir. I tried to useif(chdir(C->args[1])==1); elsebut it does not work: ``` if(C->arg_count > 1) { chdir(C->args[1]); } else { chdir(getenv("HOME")); } ``` This is the error: ``` error: ignoring return value of ‘chdir’, declared with attribute warn_unused_result [-Werror=unused-result] chdir(C->args[1]); ^~~~~ ```
The error is self-explanatory. You need to check the return value: ``` if(chdir("...") == -1) { perror("chdir"); /* return error of some sort, don't continue */ } ``` Make sure to replace the comment above with an actual error likereturn -1;(in a function) orreturn EXIT_FAILURE;(inmain). Also,1is implicitly converted into anunsigned char. You don't need the cast.
``` switch(start) {case 0:printf(""); j=1; break; case 1:printf("\t"); j=2; break; case 2:printf("\t\t"); j=3; break; case 3:printf("\t\t\t"); j=4; break; case 4:printf("\t\t\t\t"); j=5; break; case 5:printf("\t\t\t\t\t"); j=6; break; case 6:printf("\t\t\t\t\t\t"); j=7; break; } ``` start takes input from user, any way to shorten this piece of code??????? Any help is appreciated!!!!!!!!
``` int foo(int start) { for(int x = 0; x < start; x++) printf("\t"); return start + 1; // it is your j } ``` or without the function ``` for(int x = 0; x < start; x++) printf("\t"); j = start + 1; ```
What should thiscurrent -> yesevaluate in if condition? (It's not complete code you can assume any question in yes) ``` typedef struct node { char *question; struct node *no; struct node *yes; } node; node *current; if (current->yes) { current = current->yes; } ``` Thanks a lot for helping
The following code : ``` if (current->yes) { current = current->yes; } ``` is equivalent to ``` if (current->yes != NULL) { current = current->yes; } ``` So the condition is checking yes to not be NULL pointer
I tried to use BUILD_BUG_ON_ZERO in a simple user space application and it is failed to compile ``` #include <stdio.h> #define BUILD_BUG_ON_ZERO(e) ((int)(sizeof(struct { int:(-!!(e)); }))) int main() { int i; BUILD_BUG_ON_ZERO(i); return 0; } error: bit-field ‘<anonymous>’ width not an integer constant #define BUILD_BUG_ON_ZERO(e) ((int)(sizeof(struct { int:(-!!(e)); }))) ``` Can anyone please provide me hints on the error.
The macroBUILD_BUG_ON_ZEROis intended to be used with aconstant expressionas defined in6.6 constant expression. iisn't a constant expression - it's just a local variable. Evenconstqualified objects are not considered "constant expressions" in C (unlike C++). So you'd have to use: literal values (such as0) or,a macro (#define value 0) or,use anenumconstantenum { value = 0,};) to get a constant expression
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 perc=(sum/total)*100; i've been trying to put this in the code in cprogramming,but output for this part is showing 0,,,Why is this happening and what else should I do in these types of scenerios?
Since you didnt post source and this question will be closed soon, the cause is from integer division most likely. Try this instead. ``` float perc = ((float)sum / (float)total) * 100.0; ``` Heres a post on integer division if you are interested in learning why this behavior is doing what it did:What is the behavior of integer division?
What happens when you call read() (or recv()) on an open socket, and you specify a length that is more the number of bytes ready to be read in the buffer (TCP) or the length of the next datagram (UDP)?
In both cases, if the size of the buffer is larger than the amount of available data, what data is available is read and the number of bytes actually read are returned from the function. That return value is what you should use when operating on the data.
how to explain this right ``` char*(*a)(int, int); ``` just explain what does this declaration means. I'm not sure how to explain it right. Thank you very much!
ais a pointer to a function with two parameters of typeintthat returns achar*. The ``Clockwise/Spiral Rule'' cdecl: C gibberish ↔ English
I'm converting a floating point number to bits. For simplicity's sake, let's say there's 4 exponent bits and 4 frac bits. Let's say the value of frac bits is 1/4, so 0100. And say the value e is -9, so the exponent is -2 (e + bias). Now, I can't represent -2 in 4 bits so I would make the exponent bits all 0. I've now got (0 0000 0100), but obviously that's not right. What do I do from this point?
When you increment the exponent from-2to0, you shift the fraction to the right by 2 bits -- the number of its is the difference between zero and the unrepresentable exponent. So the fraction becomes0001, and the full floating point number is ``` 0 0000 0001 ```
If in a function, the arguments are listed in a certain order ``` int foo( size_t bar, int baz ) { /* Some very important code here */ return zap; } ``` does it matter if I call it like: ``` size_t size = 16; int op = 19; foo( size, op ); ``` Or ``` foo( op, size); ```
Yes, it matters. The arguments must be given in the order the function expects them. C passes arguments by value. It has no way of associating a value with an argument other than by position. The names you use in the arguments passed to the function are irrelevant. C does not examine the argument names to figure out which parameters they should be associated with. Generally, arguments may be expressions, not just names, and an argument like57or4+8does not indicate which parameter it should be.
If in a function, the arguments are listed in a certain order ``` int foo( size_t bar, int baz ) { /* Some very important code here */ return zap; } ``` does it matter if I call it like: ``` size_t size = 16; int op = 19; foo( size, op ); ``` Or ``` foo( op, size); ```
Yes, it matters. The arguments must be given in the order the function expects them. C passes arguments by value. It has no way of associating a value with an argument other than by position. The names you use in the arguments passed to the function are irrelevant. C does not examine the argument names to figure out which parameters they should be associated with. Generally, arguments may be expressions, not just names, and an argument like57or4+8does not indicate which parameter it should be.
So this expression comes out to 4: ``` int a[] = {1,2,3,4,5}, i= 3, b,c,d; int *p = &i, *q = a; char *format = "\n%d\n%d\n%d\n%d\n%d"; printf("%ld",(long unsigned)(q+1) - (long unsigned)q); ``` I have to explain it in my homework and I have no idea why it's coming out to that value. I see(long unsigned)castingq+1, and then we subtract the value of whateverqis pointing at as along unsignedand I assumed we would be left with 1. Why is this not the case?
Becauseqis a pointer the expressionq+1employspointer arithmetic. This means thatq+1points to oneelementafterq, not onebyteafterq. The type ofqisint *, meaning it points to anint. The size of aninton your platform is most likely 4 bytes, so adding 1 to aint *actually adds 4 to the raw pointer value so that it points to the nextintin the array.
I am experimenting with pointers in C programming for a project and was looking to get some guidance on whether there are other ways to initialize a pointer constant to the memory address 0x0001a000. The following was my approach: ``` volatile int *firstAddress = (volatile int *)0x0001a000; printf("First Memory address is: %p\n", firstAddress); ``` Are there shorter ways to initialize the above in C programming?
This is exactly how you would initialize such a constant, however the results areveryimplementation specific. If the given address isn't one explicitly documented as valid, you'll likely invokeundefined behavior. You also can't really make it any more concise than this. Conversions between integers and pointers requires a cast.
This question already has answers here:How do I determine the size of my array in C?(25 answers)Closed3 years ago. For example a code like: ``` int arr[5] = {1, 2, 3, 4, 5} ``` Is there anyway to get the 5 in arr[5]? I haven't learnt C++ before.
You can get it by getting the array size and divide it by the size of a single element: ``` int arr[5] = {1, 2, 3, 4, 5}; size_t lengthOfArr = sizeof(arr)/sizeof(arr[0]) ; ```
I am making an application where there are lots of communications back and forth from C and C#, and I was wondering if there is any way to import C directly instead of exporting the c file to a DLL and importing that in my C# code. Example: (C) ``` void myFunction() { } ``` (C#) ``` #include "myFile.c" ... myFunction(); ``` Thanks!
You have two options: Host the C code in the same process as your C# code. This will require a DLL, either managed or unmanaged.Host the C code in an external process. This will involve inter process communication, for instance COM. Of these two, the former is surely much simpler.
Suppose I want to mark a non-inline function with[[gnu::cold]];should the attribute be placed in the declaration in the header, or should it go with the definition in a source file? Assume that I will not be using LTO and simply want that specific function to be optimized for binary size and not execution speed. header example: ``` [[gnu::cold]] void rarely_called_func(); ``` source file example: ``` [[gnu::cold]] void rarely_called_func() { ... } ``` Also, which position in the declaration/definition should it be: ``` /* A */ int /* B */ func () /* C */; ```
Unless the attribute is seen by the compiler, it cannot use the attribute in its optimisation. If you don't put the attribute in the declaration, then the compiler cannot see the attribute. Conclusion: In order for the compiler to use the attribute for optimisation, you must put the attribute to the declaration of the function (in the header file).
``` const char* strrep(listing list) { //https://stackoverflow.com/q/4836534/9295513 char* retVal = //... return retVal; } ``` I have a struct type calledlisting. Is there a way to format elements as if by callingprintfwith("%d %d %s...", list->elem_one, list->elem_two, list->elem_three...)but write the output to an array ofcharinstead of to standard output?
The function you want issnprintf. It creates a formatted string and writes it to the givenchar *argument with a given size instead of to stdout. For example: ``` int len = snprintf(NULL, 0, "%d %d %s...", list->elem_one, list->elem_two, list->elem_three...); char *retVal = malloc(len+1); snprintf(retval, len+1, "%d %d %s...", list->elem_one, list->elem_two, list->elem_three...); ``` The first call is used to figure out how much space is needed. Then you can allocate the proper amount of space and callsnprintfagain to create the formatted string.
This question already has answers here:Correct format specifier to print pointer or address?(6 answers)Closed3 years ago. I tried to print anunsigned int*in C. I used%Xbut the compiler said: " format%xexpects argument of typeunsigned int, but argument 3 has typeunsigned int*". I also used"%u"but I got the same error again. Can anybody help me?
If you want to print a pointer, you need to use%pformat specifier and cast the argument tovoid *. Something like ``` printf ("%p", (void *)x); ``` wherexis of typeunsigned int*. However, if you want to print the value stored atx, you need to dereference that, like ``` printf ("%u", *x); ```
Suppose I want to mark a non-inline function with[[gnu::cold]];should the attribute be placed in the declaration in the header, or should it go with the definition in a source file? Assume that I will not be using LTO and simply want that specific function to be optimized for binary size and not execution speed. header example: ``` [[gnu::cold]] void rarely_called_func(); ``` source file example: ``` [[gnu::cold]] void rarely_called_func() { ... } ``` Also, which position in the declaration/definition should it be: ``` /* A */ int /* B */ func () /* C */; ```
Unless the attribute is seen by the compiler, it cannot use the attribute in its optimisation. If you don't put the attribute in the declaration, then the compiler cannot see the attribute. Conclusion: In order for the compiler to use the attribute for optimisation, you must put the attribute to the declaration of the function (in the header file).
``` const char* strrep(listing list) { //https://stackoverflow.com/q/4836534/9295513 char* retVal = //... return retVal; } ``` I have a struct type calledlisting. Is there a way to format elements as if by callingprintfwith("%d %d %s...", list->elem_one, list->elem_two, list->elem_three...)but write the output to an array ofcharinstead of to standard output?
The function you want issnprintf. It creates a formatted string and writes it to the givenchar *argument with a given size instead of to stdout. For example: ``` int len = snprintf(NULL, 0, "%d %d %s...", list->elem_one, list->elem_two, list->elem_three...); char *retVal = malloc(len+1); snprintf(retval, len+1, "%d %d %s...", list->elem_one, list->elem_two, list->elem_three...); ``` The first call is used to figure out how much space is needed. Then you can allocate the proper amount of space and callsnprintfagain to create the formatted string.
This question already has answers here:Correct format specifier to print pointer or address?(6 answers)Closed3 years ago. I tried to print anunsigned int*in C. I used%Xbut the compiler said: " format%xexpects argument of typeunsigned int, but argument 3 has typeunsigned int*". I also used"%u"but I got the same error again. Can anybody help me?
If you want to print a pointer, you need to use%pformat specifier and cast the argument tovoid *. Something like ``` printf ("%p", (void *)x); ``` wherexis of typeunsigned int*. However, if you want to print the value stored atx, you need to dereference that, like ``` printf ("%u", *x); ```
What is the difference between these declarations? Which one of the following is correct and why is that method correct? ``` int val; int *ptr = val; // first method int *ptr_2 = &val; // second method ```
``` int *ptr_2 = &val; ``` is correct. The first part (int *ptr_2) creates a pointer to anint. The second part (&val) returns the address of the variableval. ``` int *ptr = val; ``` would assign thevalueofvaltoptr2. Technically, the first one may work (the compiler might shows a warning or a casting error, see the comments). If an address is stored as an integer inval, that address could be used that way but it would make little to no sense to store an address in anint. Also note thatvalwill contain a random value(actually what was in that point of the RAM) if you don't initialize it.
I want this code to print each word backwards, but is not printing the last word, I guess I'm missing something very basic here. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int l; printf("lenght: "); scanf("%i",&l); char str[l][100]; int lenght[l]; for(int i=0; i<l; i++) { printf("%i : ",i); scanf("%s",str[i]); lenght[i] = strlen(str[i]); } for(int i=l-1; i>0; i--) { for(int j=lenght[i-1]; j>=0; j--) { printf("%c",str[i][j]); } printf("\n"); } return 0; } ```
i > 0andlenght[i - 1]are causing the problem. Also consider usingputcharto print a singlecharandsize_tto represent size of a string: ``` for (size_t i = l; i--;) { for (size_t j = lenght[i]; j--;) { putchar(str[i][j]); } putchar('\n'); } ```
What is the difference between these declarations? Which one of the following is correct and why is that method correct? ``` int val; int *ptr = val; // first method int *ptr_2 = &val; // second method ```
``` int *ptr_2 = &val; ``` is correct. The first part (int *ptr_2) creates a pointer to anint. The second part (&val) returns the address of the variableval. ``` int *ptr = val; ``` would assign thevalueofvaltoptr2. Technically, the first one may work (the compiler might shows a warning or a casting error, see the comments). If an address is stored as an integer inval, that address could be used that way but it would make little to no sense to store an address in anint. Also note thatvalwill contain a random value(actually what was in that point of the RAM) if you don't initialize it.
I want this code to print each word backwards, but is not printing the last word, I guess I'm missing something very basic here. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int l; printf("lenght: "); scanf("%i",&l); char str[l][100]; int lenght[l]; for(int i=0; i<l; i++) { printf("%i : ",i); scanf("%s",str[i]); lenght[i] = strlen(str[i]); } for(int i=l-1; i>0; i--) { for(int j=lenght[i-1]; j>=0; j--) { printf("%c",str[i][j]); } printf("\n"); } return 0; } ```
i > 0andlenght[i - 1]are causing the problem. Also consider usingputcharto print a singlecharandsize_tto represent size of a string: ``` for (size_t i = l; i--;) { for (size_t j = lenght[i]; j--;) { putchar(str[i][j]); } putchar('\n'); } ```
Here's the function in question. Why does x not change, despite having ptr reference it's memory address? Similarly why doesn't y change? ``` #include <stdio.h> int func (int a, int *b) { int *ptr = &a; *ptr += 5; ptr = b; *ptr -= 3; return a; } int main () { int x = 2; int y = 8; int ret = func (x, &y); printf ("x: %d\n", x); printf ("y: %d\n", y); printf ("ret: %d\n", ret); return 0; } ``` Edit: yes y does change. Sorry.
``` int func (int a, int *b) ``` 'a' is passed by value. Inside func() a has its own memory allocated, so anything you do to it does not affect the variable that was passed in. 'b' is a pointer to an int so changing the data at that address is still visible outside the scope of func(). Hence, x doesn't change, but y does.
I am just trying to open and write something in file but when visual studio tries to execute fprintf program crashes here is my code ``` #include<stdlib.h> int main() { FILE* fPointer; fPointer = fopen_s(&fPointer,"‪C:\\asd.txt","w"); fprintf(fPointer, "If ı can read this then ı can create for loop"); fclose(fPointer); return 0; } ``` here is the error message :Access violation writing location 0x0000003A.
fopen_sreturn value is an error number and you overwrite your file pointer with that which you should not do.
If I'm not mistaken, the following code should print outdifferentaddresses every time it's run. However, it always displays the same address forisupper(for example). Code: ``` #include <stdio.h> #include <dlfcn.h> int main(int argc, char *argv[]) { printf("isspace @ %p\n", dlsym(RTLD_DEFAULT, "isspace")); return 0; } ``` Output: ``` $ ./libc-simple isspace @ 0x7fff76b63035 $ ./libc-simple isspace @ 0x7fff76b63035 $ ./libc-simple isspace @ 0x7fff76b63035 $ ./libc-simple isspace @ 0x7fff76b63035 ``` (I'm running macOS 10.14.6, but I tested the same code on another computer running macOS 10.15 with the same result.) What am I missing?
As an optimization, macOS uses a shared mapping for a lot of the system libraries. They are loaded once at boot and used by all processes. For a given boot, the address is constant across all such processes. However, the address is randomized each boot for security.
Just wondered what happens to the memory of local vars in a C program? I have a console application that runs 24hrs a day and want to make sure I free up memory safely. Thanks Pete
If you do not use dynamic memory allocations, nothing to worry about. Local variables are created on the stack. Stack is a preallocated memory region, you can think this way: local variables are mapped to stack. In some cases, it makes sense to nullify local variables for security reasons. You can also runMemory Sanitizerto check if memory leaks exist in the program.
I used strtok to split my string. say it returns a char* "abc", is there a way I can separate each character (so a,b,c)? I am trying to do so, so I can add each character separately into a different array.
``` #include <string.h> #define LARGE_LENGTH 50 int main() { char *s="abc"; // here memory allocation is done on stack something called as stringpool // look here for more info in context of 'C' Programming //https://stackoverflow.com/questions/11399682/c-optimisation-of-string-literals char d[LARGE_LENGTH]; for(int i-0;i<=strlen(s);i++) { d[i]=*s; s++; // incremented memory address } //printf("whatever"); return 0; } ```
I am looking for a Python function that will mimic the behavior of rand() (and srand()) in c with the following requirements: I can provide the same epoch time into the Python equivalent of srand() to seed the functionThe equivalent of rand()%256 should result in the same char value as in c if both were provided the same seed. So far, I have considered both the random library and numpy's random library. Instead of providing a random number from 0 to 32767 as C does though both yield a floating point number from 0 to 1 on their random functions. When attempting random.randint(0,32767), I yielded different results than when in my C function. TL;DR Is there an existing function/libary in Python that follows the same random sequence as C?
You can accomplish this withCDLLfromhttps://docs.python.org/3/library/ctypes.html ``` from ctypes import CDLL libc = CDLL("libc.so.6") libc.srand(42) print(libc.rand() % 32768) ```
Let's say you have the following struct: ``` typedef struct { int age; } Child; typedef struct { int age; Child firstChild; } Parent; int main() { Parent p1 = {5, {3}}; Parent p2 = p1; } ``` When you copyp1top2, are you performing a shallow copy on both fields or only theChildfield? My guess is thatageis copied by value, butfirstChildis shallow copied.
Everything will be copied except (perhaps) alignment bits. When you have pointers, then thevalueof the pointer will be copied (the address), not what they point to. This is what you could call "shallow".
The descriptions seem virtually identical. Are there any nuances between the two that should be noted? Why would someone use one over the other? This question may be imposed as well forTcl_Alloc()andmalloc().
They're used because Tcl supports being built on Windows with one tool chain, and loading a DLL built with a different toolchain. A key feature of that scenario is that it is fairly common for different toolchains to have their own implementations of the C library, and that meansdifferent implementations ofmalloc(). Youmustmatchmalloc()andfree()to the same library or you get some truly weird failures (crashes, memory leaks, etc.) By providingTcl_AllocandTcl_Free(which are usually very thin wrappers) it makes it possible for user code to match up the allocations and releases correctly.
Let's say you have the following struct: ``` typedef struct { int age; } Child; typedef struct { int age; Child firstChild; } Parent; int main() { Parent p1 = {5, {3}}; Parent p2 = p1; } ``` When you copyp1top2, are you performing a shallow copy on both fields or only theChildfield? My guess is thatageis copied by value, butfirstChildis shallow copied.
Everything will be copied except (perhaps) alignment bits. When you have pointers, then thevalueof the pointer will be copied (the address), not what they point to. This is what you could call "shallow".
The descriptions seem virtually identical. Are there any nuances between the two that should be noted? Why would someone use one over the other? This question may be imposed as well forTcl_Alloc()andmalloc().
They're used because Tcl supports being built on Windows with one tool chain, and loading a DLL built with a different toolchain. A key feature of that scenario is that it is fairly common for different toolchains to have their own implementations of the C library, and that meansdifferent implementations ofmalloc(). Youmustmatchmalloc()andfree()to the same library or you get some truly weird failures (crashes, memory leaks, etc.) By providingTcl_AllocandTcl_Free(which are usually very thin wrappers) it makes it possible for user code to match up the allocations and releases correctly.
I need to pass a double pointer from one function to a second to a third. For instance: ``` char *text = "some text"; func2(&text); void func2(char **text){ func3(&text); } void func3(char **text) ... ``` Is this valid? Is there a better way to ensure that all these functions can edit this variable (without it being global)?
There's no need to use&textinfunc2().textis already a pointer to the original variable, you can just pass it as it is. You also need to specify the type that the pointer points to in the function signatures. ``` void func2(char **text){ func3(text); } void func3(char **text) ... ```
``` ... do { printf("A:"); scanf(" %d", &cm); printf(" %d od x\n", 100*(Info20-Info10)/cm); } while (cm != 0); int V; for(V = 0; V <=100; V += 8) { printf("V: %d.\n", V); } ... ``` The problem is the transition from thedo-whileloop to theforloop below, the exit key is 0 and after getting that input, the program ends instead of proceeding to the code below.
Because, if you insert 0, you do a division for 0. ``` printf(" %d od x\n", 100*(Info20-Info10)/cm); ``` raises an error
Need a solution to get input string start with spaces? I know a method to include space in input ``` scanf("%[^\n]s", s); ``` But its working only for space between words. I need a solution for string starts with spaces. And I also need the starting spaces in the variable
To get alineof user input, usefgets(). ``` #define S_MAX_LENGTH char s[S_MAX_LENGTH + 2]; if (fgets(s, sizeof s, stdin)) { s[strcspn(s, "\n")] = '\0'; // Should code want to lop off a potential trailing \n .... ``` Do not usescanf("%[^\n]s", s);norgets(s);. They suffer from buffer overflow and other issues.
In C++, Isn`t there string function likestrncmp()in C ??? for example ``` string str1 = "abc"; string str2 = "ab"; str2.compare(0,1,str1) == 0 ``` is it possible??
You can comparestd::stringdirectly: ``` if (str1 == str2) ``` To compare up to length 2, usecompare: ``` if (str2.compare(0, 2, str1) == 0) ``` You can also use C functions in C++ if you include the corresponding C header, for example to usestring.h, include<cstring>.
What is the difference betweenif(a == (1,2))andif(a == 1,2)? ``` #include<stdio.h> int main() { int a = 2; if(a == (1,2)) printf("Hello"); if(a == 1,2) printf("World"); return 0; } ```
a == 1,2is equivalent to(a == 1),2due tooperator precedence And because of howthe comma operatorworks,(a == 1),2will result in2. Anda == (1,2)will be the same asa == 2. So in effect your two conditions are like ``` if (a == 2) printf("Hello"); if(2) printf("World"); ``` The first condition will be true only ifais equal to2. The second condition willalwaysbe true (only zero is false).
I'm programming in C and I want to pass an array to a function; this function cannot modify the elements of the array. What is the correct syntax for the arguments of the function? ``` void func(const Foo array_in[]) ``` or ``` void func(Foo const array_in[]) ``` or maybe they are the same? Thank you.
You should usepointer to constantin order to handle that: ``` #include<stdio.h> void fun(const int *ptr)//pointer to constant - array boils down to pointer when passed to function { ptr[0]=9; //ERROR: Read-Only } int main(void) { int arr[]={1,2,3,4}; fun(arr); return 0; } ``` NOTE: Do not confuse it withconstant pointer
``` ... do { printf("A:"); scanf(" %d", &cm); printf(" %d od x\n", 100*(Info20-Info10)/cm); } while (cm != 0); int V; for(V = 0; V <=100; V += 8) { printf("V: %d.\n", V); } ... ``` The problem is the transition from thedo-whileloop to theforloop below, the exit key is 0 and after getting that input, the program ends instead of proceeding to the code below.
Because, if you insert 0, you do a division for 0. ``` printf(" %d od x\n", 100*(Info20-Info10)/cm); ``` raises an error
Need a solution to get input string start with spaces? I know a method to include space in input ``` scanf("%[^\n]s", s); ``` But its working only for space between words. I need a solution for string starts with spaces. And I also need the starting spaces in the variable
To get alineof user input, usefgets(). ``` #define S_MAX_LENGTH char s[S_MAX_LENGTH + 2]; if (fgets(s, sizeof s, stdin)) { s[strcspn(s, "\n")] = '\0'; // Should code want to lop off a potential trailing \n .... ``` Do not usescanf("%[^\n]s", s);norgets(s);. They suffer from buffer overflow and other issues.
In C++, Isn`t there string function likestrncmp()in C ??? for example ``` string str1 = "abc"; string str2 = "ab"; str2.compare(0,1,str1) == 0 ``` is it possible??
You can comparestd::stringdirectly: ``` if (str1 == str2) ``` To compare up to length 2, usecompare: ``` if (str2.compare(0, 2, str1) == 0) ``` You can also use C functions in C++ if you include the corresponding C header, for example to usestring.h, include<cstring>.
What is the difference betweenif(a == (1,2))andif(a == 1,2)? ``` #include<stdio.h> int main() { int a = 2; if(a == (1,2)) printf("Hello"); if(a == 1,2) printf("World"); return 0; } ```
a == 1,2is equivalent to(a == 1),2due tooperator precedence And because of howthe comma operatorworks,(a == 1),2will result in2. Anda == (1,2)will be the same asa == 2. So in effect your two conditions are like ``` if (a == 2) printf("Hello"); if(2) printf("World"); ``` The first condition will be true only ifais equal to2. The second condition willalwaysbe true (only zero is false).
I'm programming in C and I want to pass an array to a function; this function cannot modify the elements of the array. What is the correct syntax for the arguments of the function? ``` void func(const Foo array_in[]) ``` or ``` void func(Foo const array_in[]) ``` or maybe they are the same? Thank you.
You should usepointer to constantin order to handle that: ``` #include<stdio.h> void fun(const int *ptr)//pointer to constant - array boils down to pointer when passed to function { ptr[0]=9; //ERROR: Read-Only } int main(void) { int arr[]={1,2,3,4}; fun(arr); return 0; } ``` NOTE: Do not confuse it withconstant pointer