question
stringlengths
25
894
answer
stringlengths
4
863
Is it possible in C language, to convert a non integer number to integer number (closest greater integer) in the pre-processor directive only? Inside the loop the the Ceil function generally does the job, but I have to define vector(constant size). ``` #define Lenght_of_box 52.5 #define Vector_size ceil(Lenght_of_bo...
One way is to use ``` #define f_ 55.1 #define n_ ((int)f_ + !!(f_ - (int)f_)) ``` wheren_is evaluated by the preprocessor, and isf_rounded up. The!!implements the rounding up. Test program: ``` int main() { char n[n_]; // might be a VLA, so runtime `n_` would be permitted ... switch (n_){ case n_: // ....
i want this password code in star form. anyone can help. ``` /*password*/ LOGINP: clrscr(); printf("\n\n\n\n\nUsername: its_vishuuuu"); gotoxy(x,y); printf("Login\n\n\t\t\tPassword: "); fflush(stdin);//covert char to int screen gets(pass1);//enter string check=strcmp(pass1,password...
In Linux you can usegetpass()function. And for alternative seethis.
Is it possible in C language, to convert a non integer number to integer number (closest greater integer) in the pre-processor directive only? Inside the loop the the Ceil function generally does the job, but I have to define vector(constant size). ``` #define Lenght_of_box 52.5 #define Vector_size ceil(Lenght_of_bo...
One way is to use ``` #define f_ 55.1 #define n_ ((int)f_ + !!(f_ - (int)f_)) ``` wheren_is evaluated by the preprocessor, and isf_rounded up. The!!implements the rounding up. Test program: ``` int main() { char n[n_]; // might be a VLA, so runtime `n_` would be permitted ... switch (n_){ case n_: // ....
i want this password code in star form. anyone can help. ``` /*password*/ LOGINP: clrscr(); printf("\n\n\n\n\nUsername: its_vishuuuu"); gotoxy(x,y); printf("Login\n\n\t\t\tPassword: "); fflush(stdin);//covert char to int screen gets(pass1);//enter string check=strcmp(pass1,password...
In Linux you can usegetpass()function. And for alternative seethis.
There is a sequence of squares: 149162536 (1 4 9 16 25 36 ...) How do I get a digit that has a n-number? Example:n = 5, answer 6. n = 2, answer 4. n = 9, answer 6.
The solution seems rather easy with a brute force approach: start withi = 0.computei*iand convert to a string withsnprintf. Letlenbe the length of this string.ifn >= lenincrementi, subtractlenfromnand continue at step 2.otherwise, return the character of the string at offsetn. Here is some code: ``` int find_char_i...
I have my problem based on something like below: ``` for(j = 0; j < LenA; j++) for(k = 0; k <= (j - k); k++) // some operation ``` If j = 1; k should run for 2 itrs. 0 and 1 however it exits after 1st iteration alone (k = 0). Why is this the case ?
In the first iteration of the loop when j is equal to 1 you have ``` for(k = 0; 0 <= 1; k++) ``` after that iteration k becomes equal to 1 so the condition in the loop looking like ``` for(k = 0; 1 <= 0; k++) ``` evaluates to false.
My csapp book says that if global and static variables are initialized, than they are contained in .data section in ELF relocatable object file. So my question is that if somefoo.ccode contains ``` int a; int main() { a = 3; }` ``` andexample.ccontains, ``` int b = 3; int main() { ... } ``` is it onlybthat co...
It means exactly what it says. Initialized static storage duration objects will have their init values set before the main function is called. Not initialized will be zeroed. The second part of the statement is actually implementation dependant, and implementation has the full freedom of the way it will be archived. ...
``` typedef struct cellule { int numero; int poids; struct cellule *suivant; }Celulle, *LISTE; LISTE graphe[TAILLE]; ``` I do not understand what is the meaning of*LISTE?
There is already a lot of info about this. Basically is an alias to a pointer to the struct you defined. ``` typedef struct cellule { int numero; int poids; struct cellule *suivant; }Celulle, *LISTE; ``` could be split in: ``` struct cellule { int numero; int poids; struct cellule *suivant;...
Can the C library libc be moved from one system to another by just re-compiling it?
No, you cannot movelibcby just recompiling. The core part of the operating system (called the kernel), manages things like threads, processes, memory management, drivers, thermal sensors, and other vital things.glibcuses the Linux kernel for parts of the standard that require system calls. You'd need to modify it fo...
Is it possible to use LLVM to read in C code and make it faster? I've seen many discussions on using LLVM to transform C++ to (unreadable) C code but I'm wondering if LLVM can read in C code, and produce a file (code, not an executable) with the same functionality that is faster.
No. There is a C backend for LLVM, so you can compile C via LLVM IR to C and apply optimisation passes on the way, but what you are asking about is neither a design goal of that backend nor of LLVM as a whole. If it works in any particular case, then that is just a happy coincidence. One of LLVM's goals is producing...
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed3 years ago.Improve this question I'm writing a C program that accesses a database. I use a SELECT statement and printf to display the data i...
You can handle null values like this SELECT ISNULL(column,'YOUR_NULL_VALUES')
I am passing functions topthread_createfunction. I am getting a warning that complains about incompatible type of function passed as an argument: ``` void * _Nullable (* _Nonnull)(void * _Nullable) ``` I managed to fix it by declaring my function as: ``` void *incFunc(void *ptr){ for (long i = 0; i < COUNT; ++i...
That means: it has to be not NULL function pointer takingvoid *parameter which can be NULL and returningvoid *. The return value can be NULL.
I'm trying this: ``` int M,N,K; printf("Enter (m,k,n) : "); scanf("%d %d %d ", &M, &K, &N); printf("\nDone?"); ``` This is inside the main function. I need the program to read the three integers but when I run it, it just reads the three but doesn't go past the scanf, i.e. "Done?" isn't executed, as if i...
If I remove the space after the last %d, it works fine. But why is that so? " "in"%d %d %d "directsscanf()to read, and not save, any number of whites-spaces including'\n'. scanf()keeps consuming white-spaces until some non-white-space in encountered.@user3121023 "%d %d %d "obligesscanf()to not return until some non...
I was wondering how Linux detects the end of a text file. Do all text files end in a NULL byte, and Linux takes advantage of this?
Modern operating systems, such as Linux, do not use the file contents to detect the end of the file, they store the file length in the file system and keep track of the file position to determine if more contents are available to read. In fact, text files are not supposed to contain null bytes at all. They usually en...
I am trying to read a file like: mother mama, father papa, apple mar, ... And I would like to store those words in an array of chars A[10][2][12] so the words : "mother" will be in A[0][0] "father" in A[1][0] but the second column : "mama" in A[0][0] "papa" in A[0][1] ... I can change the format of the words in the ...
regarding; "mother" will be in A[0][0] "father" in A[1][0] but the second column : "mama" in A[0][0] "papa" in A[0][1] That will not work. Suggest: "mother" will be in A[0][0] "father" in A[1][0]. "mama" in A[0][1] "papa" in A[1][1]
I have a file where I have saved C float arrays as binary data. Is it possible to load this binary data into a Python list now?
It's possible to do that using Numpy.memmap. Something like this: ``` import numpy as np arr = np.memmap("filename", dtype="int32", mode="r") ``` Replace "filename" with the path to your array file and "int32" with the type you used in your C array.
I am going through the isoMDS calculation in theMASS package. IsoMDS calls the c function VR_mds_dovm in src/MASS.c, then vmmin() is called at line 269 but I can't find the definition of that function. I tried searching "vmmin" on the whole repo but the only result was the line where it is called. I tried googling "R...
Since the function is not fromMASS, it has to come from one of the linked libraries. Indeed,vmminis a function from R's C API used for optimization; here thedeclarationanddefinition.
I have a file where I have saved C float arrays as binary data. Is it possible to load this binary data into a Python list now?
It's possible to do that using Numpy.memmap. Something like this: ``` import numpy as np arr = np.memmap("filename", dtype="int32", mode="r") ``` Replace "filename" with the path to your array file and "int32" with the type you used in your C array.
I am going through the isoMDS calculation in theMASS package. IsoMDS calls the c function VR_mds_dovm in src/MASS.c, then vmmin() is called at line 269 but I can't find the definition of that function. I tried searching "vmmin" on the whole repo but the only result was the line where it is called. I tried googling "R...
Since the function is not fromMASS, it has to come from one of the linked libraries. Indeed,vmminis a function from R's C API used for optimization; here thedeclarationanddefinition.
``` #include <stdio.h> #include <stdlib.h> int f(int a, int b) { int a1 = a, b1 = b; while (a1 != b1) if (a1 < b1) a1 += a; else b1 += b; return a1; } int main() { printf("%d\n", f(12, 18)); return 0; } ``` Hi, I don't understand why the result is 36, can someone explain me ?
Let's step it through: ``` f(12, 18) -> a = 12, b = 18 int a1 = a, b1 = b; -> a1 = 12, b1 = 18 while (a1 != b1) -> not equal -> do the loop if (a1 < b1) a1 += a; -> a1 = 24 while (a1 != b1) -> not equal -> do the loop if (a1 < b1) ... else b1 += b; -> b1 = 36 while (a1 != b1) -> not equal -> do the loop if (a1 < b1) ...
Fixed point conversion macros for 16-bit numbers, with max and min values: ``` #define SCALEFACTOR_16(N) ( 1U << N ) #define Q_MAX16 ( SCALEFACTOR_16(16-1) - 1U ) #define Q_MIN16 ( -SCALEFACTOR_16(16-1) ) ``` Casting min value to 64 bits: ``` int64_t x = (int64_t)Q_MIN16; ``` gives:x == 0x0000 0000 ffff 8000...
Your system has 32 bit (unsigned)int. All the work you're performing is with 32 bit values, and you castafterdoing the work. When you cast fromunsigned inttoint64_t, it doesn't change the value (it doesn't interpret the high bit of anunsignedas a sign bit to be extended), so it gets zero filled.
This question already has answers here:Is this way is prefered to swap two variable without temp in c?(5 answers)Closed3 years ago. So I need to switch between A and B without using another integer. I was able to do this easily with a third integer (tmp). Is there any way to do this without it? ``` int a = 53, b = ...
The most common mentioned method is: ``` y ^= x; x ^= y; y ^= x; ``` An alternative is to use addition and subtraction instead of XOR; but that's messy due to the risk of overflows. Note: To be precise; XOR causes undefined behavior for negative values (but that can be prevented with simple casts to unsigned and ba...
I go through some examples: ``` char *ptr = malloc(2); // in c , here variable 2 is created without name int *ptr1 = new int[2]; // in c++ , here 3 int arrays is created without name ``` Does this mean the variable is created without name ? then how is this possible?
In the Cstandard, the wordvariableis used to refer to amutable object with name. So in that regard it is not possible. However, all variables areobjects.malloc(andnewin C++) return pointers tounnamed objects. Naturally people can use whatever incorrect term they want for whatever concept...
``` #include <stdio.h> #include <stdlib.h> int f(int a, int b) { int a1 = a, b1 = b; while (a1 != b1) if (a1 < b1) a1 += a; else b1 += b; return a1; } int main() { printf("%d\n", f(12, 18)); return 0; } ``` Hi, I don't understand why the result is 36, can someone explain me ?
Let's step it through: ``` f(12, 18) -> a = 12, b = 18 int a1 = a, b1 = b; -> a1 = 12, b1 = 18 while (a1 != b1) -> not equal -> do the loop if (a1 < b1) a1 += a; -> a1 = 24 while (a1 != b1) -> not equal -> do the loop if (a1 < b1) ... else b1 += b; -> b1 = 36 while (a1 != b1) -> not equal -> do the loop if (a1 < b1) ...
Fixed point conversion macros for 16-bit numbers, with max and min values: ``` #define SCALEFACTOR_16(N) ( 1U << N ) #define Q_MAX16 ( SCALEFACTOR_16(16-1) - 1U ) #define Q_MIN16 ( -SCALEFACTOR_16(16-1) ) ``` Casting min value to 64 bits: ``` int64_t x = (int64_t)Q_MIN16; ``` gives:x == 0x0000 0000 ffff 8000...
Your system has 32 bit (unsigned)int. All the work you're performing is with 32 bit values, and you castafterdoing the work. When you cast fromunsigned inttoint64_t, it doesn't change the value (it doesn't interpret the high bit of anunsignedas a sign bit to be extended), so it gets zero filled.
I have to save data in a file for a project (in C language). So i would like to usefopento usefprintfto output my strings values on a file. So, I do : ``` FILE * file; file = fopen("./tmp.txt","w+"); outputData(); //my fonction to fprintf in the file fclose(file); ``` But when i do that, this is not in the current ...
You can try using full path, as on linux: ``` FILE * file; file = fopen("/home/toto/tmp.txt","w+"); ``` You can also check file access usingaccess
``` int x = 0x76543210; char *c = (char*) &x; Big endian format: ------------------ Byte address | 0x01 | 0x02 | 0x03 | 0x04 | +++++++++++++++++++++++++++++ Byte content | 0x76 | 0x54 | 0x32 | 0x10 | ``` why does the byte address ox01 stores only 0x76 not 0x765?
A byte is 8 bits, and in hex that goes from 0x00 --> 0xFF (0 -> 255). 0x765 - which is hex - cannot possibly fit in 8 bits.
Here a print message "Do you want to run again?" is asked, if we enter "y" then program will repeat. I tried this code ``` #include<stdio.h> int main() { int a, b, c; char ch; ch = 'y'; printf("enter 1st and 2nd no."); scanf("%d%d", &a, &b); { c = a + b; printf("%d", c); ...
``` #include<stdio.h> int main() { int a,b,c; char ch; do { printf("enter 1st and 2nd no."); scanf("%d%d",&a,&b); c = a + b; printf("%d",c); printf("Do you want to run again?"); scanf(" %c",&ch); } while(ch == 'y'); return 0; } ```
Given a socket port how do you find the process ID (process name) of the process on Windows 10 that uses this port? I am aware ofnetstatcommand but I would like to do it with C code only.
How about there, it appears there's a way: the IP Helper library. Ref:https://learn.microsoft.com/en-us/windows/win32/iphlp/ip-helper-start-page I haven't used it for this, but it's clearly going down the right road by providing everything you need to basically roll your ownnetstat.exe. The low-level object that co...
I am using multiplication (with the addition of other operations) as a substitution for integer division. My solution eventually requires me to multiply 2 32-bit numbers together and take the top 32 bits (just like the mulhi function), but AVX2 does not offer a 32-bit variant of _mm256_mulhi_epu16 (Ex: there's no '_mm...
This can be done by doing the following: ``` __m256i t1 = _mm256_mul_epu32(m, n); t1 = _mm256_srli_epi64(t1, 32); ```
This question already has answers here:Return void type in C and C++(5 answers)Closed3 years ago. How doesreturnwork exactly? I found the below code and am confused how it works. You can see in theif (n==1)statement thereturnhas no value next to it. ``` void bubbleSort(int arr[], int n) { // Base case if (...
returnmeans to stop execution of the current function and return to the caller. If the function is defined as to return something, then the return statement must have an expression denoting the thing to return. Your function is correct, except the lastreturnstatement. Instead of ``` return bubbleSort(arr,n-1); ```...
In C or C++, modifying loop variables inside the for-loops is a source of nasty bugs: ``` int main() { std::vector<int> v (30); std::iota(v.begin(), v.end(), 0); int j = 0; for (size_t i = 0; i < v.size(); i++) { std::cout << v[i] << ' ' << i << '\n'; i++; // oops, I mean j++ } ...
If you use a C++ ranged-for, you can make the loop variableconst. e.g. ``` for (const size_t i : boost::irange<size_t>(0, v.size())) { std::cout << v[i] << ' ' << i << '\n'; // i++; // error, can't modify const } ```
I have a file which contains "hello world". I have converted it to hex file "68656c6c6f20776f726c640a". Now I want it to convert the hex file to its original content. How can I do it? I tried getting a char from the hex file and converting it to its equivalent character, but every time it is picking up one char 6 inst...
You should read two digits as a hex value, this will convert them back to a character: like: ``` int tmp; while ( fscanf(fp,"%2x",&tmp) > 0 ) { fputc(tmp, fptr); } ```
This question already has answers here:Do I cast the result of malloc?(29 answers)Closed3 years ago. This question is regardingmallocin C associated with structs or arrays. I noticed there are 2 ways to allocate memory and I cannot tell the difference between them. ``` char* arr = (char*) malloc(capacity * sizeof(c...
In C++ you need to do the(char*)cast, but when compiled for C, void* will freely convert to any other pointer type. If the code is potentially shared between the languages, then putting the cast in costs nothing.
This question already has answers here:Return void type in C and C++(5 answers)Closed3 years ago. How doesreturnwork exactly? I found the below code and am confused how it works. You can see in theif (n==1)statement thereturnhas no value next to it. ``` void bubbleSort(int arr[], int n) { // Base case if (...
returnmeans to stop execution of the current function and return to the caller. If the function is defined as to return something, then the return statement must have an expression denoting the thing to return. Your function is correct, except the lastreturnstatement. Instead of ``` return bubbleSort(arr,n-1); ```...
In C or C++, modifying loop variables inside the for-loops is a source of nasty bugs: ``` int main() { std::vector<int> v (30); std::iota(v.begin(), v.end(), 0); int j = 0; for (size_t i = 0; i < v.size(); i++) { std::cout << v[i] << ' ' << i << '\n'; i++; // oops, I mean j++ } ...
If you use a C++ ranged-for, you can make the loop variableconst. e.g. ``` for (const size_t i : boost::irange<size_t>(0, v.size())) { std::cout << v[i] << ' ' << i << '\n'; // i++; // error, can't modify const } ```
I need some help in my task. The question is " Write a small program, sleepy, that gets a loop count from the command line: sleepy n where n is the number of seconds for which the program should run. Implement this timing by putting a loop n times of sleep(1) - this will put the program to sleep for one second n times...
The loop is executed once per each arguments from the command line (argc), whereas the requirement is to parse the the number of iterations from the (first) command line arguments (argv[1]) You also want to change the sleep to 1 seconds, as per requirement. ``` int count = atoi(argv[1]) ; for (counter = 0; counter<c...
This question already has answers here:How do function pointers in C work?(12 answers)Closed3 years ago. While browsing the sqlite documentation for C I've found this as a parameter to a function, what does it mean? ``` int (*callback)(void*,int,char**,char**); ```
This is the prototype of afunction pointerto acallback function. Because it is used as an argument in another function, it implies that that actual function needs to be declared and defined somewhere in your code before it is used in the function as an argument. I.e. something like this: ``` //declaration - possibl...
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 Whats the meaning of[i]in the following example? ``` #include <stdio.h> int main() { int values[5]; ...
ihere is a variable. In your code,[i]acts as the index ofvaluesand is used to access the element in arrayvalues. Edit: Since there is a//HEREcomment in your code, im going to assume you would also want what [i] does there. The expression&value[i]basically gives the address ofvalue[i],i.e, the "ith" element of the a...
I need to remove all the commas from my user input. The code is working but it's giving the warning "assignment to ‘char’ from ‘char *’ makes integer from pointer without a cast". I need to get rid of this warning. ``` removeCommas(argv[1]); printf("%s", argv[1]); return 0; for(i=0; i<strlen(num); i++) {...
``` *(num + i) = ""; ``` I'm not sure what you are trying to assign here, but double quotes ("") denoteschar *. If you wanted to remove,(ASCII 44) from the string it is not the way to do it. You need to shift all the chars after,until\0and terminate the string properly.
Is there a way to know inNF_INET_POST_ROUTINGif the packet is generated via RAW socket: ``` #include <sys/socket.h> #include <netinet/in.h> raw_socket = socket(AF_INET, SOCK_RAW, int protocol); ``` Any help is greatly appreciated!
Yep, you can use thetypefield ofstruct socket. F.e.: ``` static unsigned int nfh_handler(...) { struct iphdr *ip_header = ip_hdr(skb); if(ip_header->protocol == IPPROTO_TCP) { struct tcphdr *tcp_header = tcp_hdr(skb); if(skb->sk && skb->sk->sk_socket && skb->sk->sk_socket->type ==...
Does re-declaring the same variable over and over again affect the performance of the code? ``` int i,a; for(i=0;i<10;i++) { // Some operations with a } ``` V/S ``` int i; for(i=0;i<10;i++) { int a; // Some operations with a } ```
Normally "stack variables", what are really local variables, are zero-cost. The only price you'd pay is if there's initialization of some sort. The compiler may or may not reserve memory for that value. In the second case you don't actually useaso it will probably be eliminated by the optimization pass, making it tru...
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed3 years ago.Improve...
Try to use != instead of =! The comparison should be !=
Lets say i used the fread function to read data from a file to a struct. How exactly is data read to the struct? Lets say my struct has the following: ``` Int x; Char c; ``` Will the first 4 bytes read go into x and the next byte go into c? And if i read in more bytes than the elements in my struct can hold what's g...
Will the first 4 bytes read go into x and the next byte go into c? Yes, unless your compiler has extremely strange padding rules (e.g. every member must be 8 byte aligned). And assumingIntis 4 bytes andCharis 1 byte. And if i read in more bytes than the elements in my struct can hold what's gonna happen? That's un...
Since C is a loosely typed language andstdint.hdefines justtypedefs(I assume), how can the widths of ints be guaranteed? What I am asking is about the implementation rather than the library usage.
How can<stdint.h>types guarantee bit width? C can't and C does not require it. C does requireminimumwidths. The below, individuality, are required only on systems that support them, without padding and 2's complement for sign types. ``` (u)int8_t, (u)int16_t, (u)int32_t, (u)int64_t ``` An implementation may op...
Does re-declaring the same variable over and over again affect the performance of the code? ``` int i,a; for(i=0;i<10;i++) { // Some operations with a } ``` V/S ``` int i; for(i=0;i<10;i++) { int a; // Some operations with a } ```
Normally "stack variables", what are really local variables, are zero-cost. The only price you'd pay is if there's initialization of some sort. The compiler may or may not reserve memory for that value. In the second case you don't actually useaso it will probably be eliminated by the optimization pass, making it tru...
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed3 years ago.Improve...
Try to use != instead of =! The comparison should be !=
Lets say i used the fread function to read data from a file to a struct. How exactly is data read to the struct? Lets say my struct has the following: ``` Int x; Char c; ``` Will the first 4 bytes read go into x and the next byte go into c? And if i read in more bytes than the elements in my struct can hold what's g...
Will the first 4 bytes read go into x and the next byte go into c? Yes, unless your compiler has extremely strange padding rules (e.g. every member must be 8 byte aligned). And assumingIntis 4 bytes andCharis 1 byte. And if i read in more bytes than the elements in my struct can hold what's gonna happen? That's un...
In my project, I first compileaa_1.c,aa_2.c... from folderA, then compilebb_1.cbb_2.c... from folderB. Then I usegcc-arto generatelibapps.a. At last, I link with other static libraries. Now I want to calculatetext,rodata,dataandbsssection of folderA. My method is to executegcc-nm -S --size-sort folder/*.o, and accum...
As perGet list of static libraries used in an executable, the library names are discarded during the linking process. You can add-Xlinker -Map=file.mapto the link command, and then try to extract information from the 'file.map'.
Let's say x=29 and y=13. What does this line of code actually do: ``` x%=y-3; ``` I just don't really know what does this mean?
Modulo operator gives you remainder from division. a % bis the remainder of division a by b x %= y - 3is equal tox = x % (y - 3)and gives you remainder from division x by (y - 3) expression.
I saw this code: ``` char *str; // Some code if (! str || ! *str) return str; ``` Why need to check! *str? Isn'tif (! str)enough?
It depend on what you want to check: The!strcheck is str is NULL.The!*strchecks that the first char instris NUL byte ('\0') Combined, they will return 's' if s is NULL, or s point to a NUL char
Very basic practice problem that is massively confusing me for some reason. I have the number 0x55555555 that I want to get in C using only the bit-wise operators | and <<. You can also use any number less then 0xFF as part of shift/or. Lastly less then 6 operators have to be used, so I can't just spam shifts one at a...
``` uint32_t _55 = 0x55; uint32_t _5555 = (_55 << 8) | _55; uint32_t _55555555 = (_5555 << 16) | _5555; ```
I am debugging with GDB at work. When I input "info symbol 0xABCD", I get the following result, ``` sample_function + 123 in section init ``` I know the EXACT LOCATION is near sample_function(), and have an offset 123, but how do I locate it in the C code? I have not found any resource from internet that talks about...
how do I locate it in the C code? You can do: ``` (gdb) disas/m 0xABCD ``` From "help disas": ``` With a /m modifier, source lines are included (if available). ``` Alternatively, this command:addr2line -fe /path/to/binary 0xABCD(run outside of GDB) should print source location (if the binary has debug line info)....
I saw this code: ``` char *str; // Some code if (! str || ! *str) return str; ``` Why need to check! *str? Isn'tif (! str)enough?
It depend on what you want to check: The!strcheck is str is NULL.The!*strchecks that the first char instris NUL byte ('\0') Combined, they will return 's' if s is NULL, or s point to a NUL char
Very basic practice problem that is massively confusing me for some reason. I have the number 0x55555555 that I want to get in C using only the bit-wise operators | and <<. You can also use any number less then 0xFF as part of shift/or. Lastly less then 6 operators have to be used, so I can't just spam shifts one at a...
``` uint32_t _55 = 0x55; uint32_t _5555 = (_55 << 8) | _55; uint32_t _55555555 = (_5555 << 16) | _5555; ```
I am debugging with GDB at work. When I input "info symbol 0xABCD", I get the following result, ``` sample_function + 123 in section init ``` I know the EXACT LOCATION is near sample_function(), and have an offset 123, but how do I locate it in the C code? I have not found any resource from internet that talks about...
how do I locate it in the C code? You can do: ``` (gdb) disas/m 0xABCD ``` From "help disas": ``` With a /m modifier, source lines are included (if available). ``` Alternatively, this command:addr2line -fe /path/to/binary 0xABCD(run outside of GDB) should print source location (if the binary has debug line info)....
I am debugging with GDB at work. When I input "info symbol 0xABCD", I get the following result, ``` sample_function + 123 in section init ``` I know the EXACT LOCATION is near sample_function(), and have an offset 123, but how do I locate it in the C code? I have not found any resource from internet that talks about...
how do I locate it in the C code? You can do: ``` (gdb) disas/m 0xABCD ``` From "help disas": ``` With a /m modifier, source lines are included (if available). ``` Alternatively, this command:addr2line -fe /path/to/binary 0xABCD(run outside of GDB) should print source location (if the binary has debug line info)....
Esentially I need to constantly load in a character and a number until '-' is entered. But instead of breaking immediatly after entering '-', the loop asks for the input again, and then breaks. ``` while (c != '-') { scanf(" %c", &c); scanf("%d", &n); } ```
You're testing the character that was enteredbeforethe last number. You need to test the character first, and then ask for the number. ``` while (true) { scanf(" %c", &c); if (c == '-') { break; } scanf("%d", &n); } ```
Let's assume somebody is writing some text. My program has to scan that text and then print all the characters under each other. However, it should only read the input until * appears. So when the input is "Hello*darling", it should only read "Hello". I used the * as an argument in while loop, but my program scans "He...
You should look atgetchar() ``` #include <stdio.h> int main() { int c1; while ((c1=getchar())!=EOF && c1!='*'){ printf("c1: %c \n", c1); } return 0; } ``` EDIT: and this way, there is no undefined behavior, becausec1is always initialized (see @Blaze answer) :)
Just a simple ask: The(gdb) info localscommand gives the list of local variables and their values. Are these values initialized values or point in time of execution of that frame? Can you provide any documentation around this?
Are these values initialized values or point in time of execution of that frame? The latter.Documentationsays: "These are all variables (declared either static or automatic) accessible at thepoint of executionof the selected frame."
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 copy all characters from one character array to another without using strcpy function. ``` char s1[80],s2[...
Instead of scanf, using gets function for getting input with spaces. ``` #include<stdio.h> int main() { char s1[80],s2[80]; int i; printf("input s2"); // scanf("%c",&s2); gets(s2); printf("%d",strlen(s2)); for(i=0;i<strlen(s2);i++) { s1[i]=s2[i]; } printf("s1:%s",s1); } ```
Very basic question that is tripping me up: Write a function that produces the same thing as this: ``` int mult_3_div_4(int x){return (x*3)/4;} ``` But only using ! ~ & + << >> bitwise operators Divide by 4 is of course << 2 So I tried something like: int test(int x) {return ((x<<1 + x) >> 2);} But I can't seem t...
The bitwise shifts<<>>have lower precedence that binary operators+-. So the line should be... ``` int test(int x) {return ((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. Consider the following code: ``` #include <stdio.h> int main(void){ char *p="A for Apple"; char q[15]="B for Ball"; printf("x=%c y=%c\n",*(p+10)-2,*(&q[4]-2)); printf("u=%c v=%c w=...
a[x]is shorthand for*(a + x). Consequently,a[x]is equivalent to the expressionx[a]. (same holds for8[p]andp[8]of course ;))
I am stuck on the line of codepid = fork();, I understand prior to that there are 2 child process created, but would some please clarify once it reaches to the linepid=fork();, does the previous child being wiped and pid will start forking from 0 again or does it just keep forking with the 2 child ? ``` void main() {...
if fork() is successful it returns 0 to the child and the process id to the parent. So for the parent, pid != 0 and for the children it is. After the first if, before the ``` pid = fork() ``` line. There is 3 processes. These 3 processes then create one new child each, which then in turn creates another child.Finall...
I have the following code: ``` int s[4096]; unsigned char o = 0; int main(void) { int *n; return ((char *) (s + o)) == 0 ? *n : 0; } ``` When I run the Clang Static Analyzer on that code, it warns me that I'm dereferencingnbecause(char *) (s + o)is a null pointer, which it's not (I can even print it and get...
I was testing with the Clang Static Analyzer version 8. Version 10 no longer reports the warning.
For this code: ``` typedef struct book_s{ char name[50]; char author[50]; int price; } book_t; ``` I'm going to declare 2 variables of this structure: ``` struct book_s first_book; book_t second_book; ``` Arefirst_bookandsecond_bookthe same type? If so, are these 2 lines ``` first_book.name second_book.name ``` ...
The type-namebook_tis analiasforstruct book_s. They're identical types, and can be used interchangeably. Therefore the structureobjects(structure instances) are of identical type as well. The structure objects (instances) are different and distinct, but they have the same type.
The concept is very similar to thisAdd zero-padding to a stringbut it's a question from c# NOT C. While you can add a zero padding in printf like thisprintf("%4d", number) How can I have a zero padding to a string? ex: ``` char *file_frame = "shots"; strcat(file_frame, "%3d", number); // It's my attempt to solve it...
You need to usesprintf ``` sprintf(file_frame, "%04d", 34); ``` The0indicates what you are padding with and the4shows the length of the integer number. Also you should be using mutable array as below. ``` char *file_frame = "shots"; --> char file_frame[100] = "shots"; ```
I am trying to create the functionality of a Single-Linked List in C, but I am having an issue accessing the next node of my Head node. ``` typedef struct node { struct node *next; } Node; int foo(Node **head){ *head = *head->next; } ``` When I run this code, I expect it to change the address of my head node po...
The line inside foo should be ``` *head = (*head)->next ``` because '->' has higher precedence than * You can learn more about operator precedence here (https://en.cppreference.com/w/cpp/language/operator_precedence)
I'm wondering if there's a C function that can be used to get another executable file's data segment size? For example, something that works like thesizeutility in Linux? The output ofsizeincludes the information I'm after, the data segment size; for example, it might look like: ``` text data bss dec he...
Usingelf.hyou have all the data structures you need. Follow the main ELF header to the program headers, then iterate through them. ThePT_LOADheader(s) with write permission is/are the data segment(s).
I'm stuck in a question of decrement the code is as follows ``` #include <stdio.h> int main() { int x = 4, y = 3, z; z = x-- - y; printf("%d %d %d\n",x,y,z); return 0; } ``` according to what i know the output should be 4 3 0 the explanation for the value of z according to me is as follows: first as it's a post de...
The expressionx--evaluates to thecurrentvalue ofxwhich is 4. The value ofyis then subtracted from this value resulting in 1 which is what is assigned toz.xis then decremented as a side effect of the postdecrement. So the output will be 3 3 1.
I noticed something when I used the setvbuf () function to set the file processing buffer. If I don't use a buffer size of 256 or higher, I get strange symbols when I try to print the buffer. However, if I use 256 sizes for the buffer, I get the correct char representation of up to 8 characters. I've done research on ...
The contents of the buffer passed tosetvbufare indeterminate at any time (see7.21.5.6/2 in C11 standardorcppreference page on setvbuf). So you shouldn't expect anything.
I made a program which decompose prime numbers in c : ``` int i = 2; while (n != 1) { while (n % i == 0) { printf("%d ", i); n = n / i; } i++; } ``` and output for 36 would be : ``` 2 2 3 3 ``` How can i make it to be like: ``` 2^2 * 3^2 ```
``` while (n != 1) { int power = 0; int factor = i; while (n % i == 0) { power = power + 1; n = n / i; } i++; if (power == 0) continue; if (power > 1) printf("%d^%d", factor, power); else printf("%d", factor); if (n != 1) printf(" * "); else printf("\n"); } ```
I made a program which decompose prime numbers in c : ``` int i = 2; while (n != 1) { while (n % i == 0) { printf("%d ", i); n = n / i; } i++; } ``` and output for 36 would be : ``` 2 2 3 3 ``` How can i make it to be like: ``` 2^2 * 3^2 ```
``` while (n != 1) { int power = 0; int factor = i; while (n % i == 0) { power = power + 1; n = n / i; } i++; if (power == 0) continue; if (power > 1) printf("%d^%d", factor, power); else printf("%d", factor); if (n != 1) printf(" * "); else printf("\n"); } ```
I don't understand Why don’t we have to print strings in for loop ? In normal cases we need to print arrays in for loop. For example, if we want to print the array of integers. It will be like this: ``` int a[n]; for (i = 0; i < n; i++){ printf("%d", a[i]); } ``` But for strings like: ``` char s[100] = " Hell...
Strings terminate with the empty character'\0', that's how it is possible to know when a string ends even without explicitly passing its length.
I want to shift left only one bit in a specific place leaving its position0, so I do not want to shift the whole variable with<<operator, here is an example: say the variable has the value1100 1010and I want to shift the fourth bit then the result should be1101 0010.
Steps to get there. Pull out bit value from the original number.Left shift the bit value by one.Merge the bit-shifted value back to the original number. ``` // Assuming C++14 or later to be able to use the binary literal integers int a = 0b11001010; int t = a & 0b00001000; // Pull out the 4-th bit. t <<= 1; ...
I'm trying to print the array index using pointers arithmetic. Does anyone have any idea how to do it? in particular "j" I would like you to do it. ``` #include <stdio.h> int main(void) { int b[10] = {2, 8, 4, 7, 1, -45, 120, 78, 90, -6}; int *pb, j = 0; for(pb = &b[0]; pb < &b[10];) { printf("...
Like this: ``` int main(void) { int b[10] = { 2, 8, 4, 7, 1, -45, 120, 78, 90, -6 }; int *pb, j = 0; for (pb = &b[0]; pb < &b[10]; pb++) { printf("[%td] = %d\n", pb-b, *pb); } return 0; } ``` In pointer arithmetic you can get the index difference with subtraction:pb-bis the index of th...
When I try to use parentheses as a delimiter it doesn't seem to work. I'm fairly new to C so go easy on me. ``` char* tempToken = ""; char* delim = { " ,.\n()" }; tempToken = strtok(fileStrings[j], delim); while (tempToken != NULL) { //copy word by word to the words array strcpy(words[i++], tempToken); ...
You have changed the delimiter set on the successive calls(from" ,.\n()"to" ,.\n"), so even if the latter part of the string contains any parentheses,strtok()won't consider those as delimiter. Check your delimiter list if it's ok! ie: (long-lasting)(long-fasting) will be parsed as 1. long-lasting and 2. (long-fasting...
For this problem I am being given a list of movies, their genre, etc. I have to then read that file and put it into an array of structures. I am trying to dynamically allocate the array but I don't know how to do that correctly. I have it as ``` list1 = (list_t *)malloc(n * sizeof(int)); ``` Not sure what is wrong ...
movies = (list_t *)malloc(n * sizeof(int));Allocates one integer for each record, not a record. This means you don't have as much space as you need and so you are reading data into memory you don't own. That is undefined behavior. You needmovies = malloc(n * sizeof(list_t)); You also use theFILE* pointerafter closing...
I searched on Google and I can't find a solution. I just want to create a 2D pointer array that make a reference of an existing python array in order to send it in a C Function thanks to c_types. tab is a existing 1D array, and it worked: ``` arr = (c_int * 1000000)(*tab) Basic.Basic_c.quicksort.restype = POINTER(c_...
Instead of using 2d list, you can use a tuple of tuples. So, after you created your matrix, convert it to a tuple as below. ``` Matrix = [[0 for x in range(8)] for y in range(5)]; Matrix = tuple(map(tuple, Matrix)) arr = ((c_int * 8)*5)(*Matrix) ```
Hello i have a very simple question, i Have a simple socket server/client program in C I would like the server side program to keep accepting new connections forever I want it to be able to accept more connection while it is also performing orther operations So my question is : what is the best way to do that ? -...
The best way is probably usingfd_setandselectwithout having to fork every time you accept a new incoming connection. Here's a good explanation for it:https://www.binarytides.com/multiple-socket-connections-fdset-select-linux/
Here I have a pointerptrto arrayarrof 4 integers.ptrpoints to the whole array.ptr[0]or*ptrpoints to the first element of the array, so adding 1 toptr[0]gives the address of the second element of the array. I can't understand why usingsizeof(ptr[0])gives the size of the whole array, 16 bytes, not the size of only the ...
OP:ptr[0]points to the first element in the array. Type confusion.ptr[0]is an array. ptris apointer to array 4 of int.ptr[0], like*ptrdeferences thepointer to an array.sizeof(ptr[0])is the size of an array. Withsizeof(ptr[0]),ptr[0]does not incur "an expression with type ‘‘pointer to type’’ that points to the ini...
In a function I am building a dynamically allocated 2D array. This array has a variable number of rows and a fixed number of columns (3). I would like to have this function return the array but I can't seem to get the operators precedence for the return type right. The array has been defined as: ``` int (*refined_li...
It's ``` int (*funcName(int arg))[3]; ``` The "thing" you want to declare goes inside the(*).
In a function I am building a dynamically allocated 2D array. This array has a variable number of rows and a fixed number of columns (3). I would like to have this function return the array but I can't seem to get the operators precedence for the return type right. The array has been defined as: ``` int (*refined_li...
It's ``` int (*funcName(int arg))[3]; ``` The "thing" you want to declare goes inside the(*).
This swap function is fully functional except when the input is two arrays with the same values: ``` void permuter(int* a, int* b) { *a = *a + *b; *b = *a - *b; *a = *a - *b; } int main(void) { int i[0]; int j[0]; i[0] = 5; j[0] = 5; permuter(&j[0], &i[0]); return 0; } ``` usingp...
This is a common problem with clever swaps (see also: XOR swap). Do it the straightforward way, with a temporary! ``` int t = *a; *a = *b; *b = t; ``` In practice, you could probably check that the pointers are different to avoidthisproblem, but*a + *bstill has undefined behaviour on overflow and there’s just no rea...
I'm trying to find a way to monitor when the_NET_ACTIVE_WINDOWproperty changes. Right now I'm polling every 1 second to update the current active window. I know that there's a way to get events about this, I've seen references to it, but I can't seem to find any code (that I can understand) that explains how to do it....
If you setPropertyChangemask on root window you'll start gettingPropertyNotifyevents to your code. See example in my answer here:Linux get notification on focused gui window change
when we want to compile a multi file together. Why we need to convert .c file to .o in the makefile instead of just gcc file1.c file2.c -o newfile For example ``` \\ in make file file: file1.c file2.c gcc file1.c file2.c -o combination \\ we can just call make in the terminal \\ i have watch video on youtube...
You don't need to. Go ahead and do it that way; it will work fine for very simple cases. Makefiles are useful when (a) you have a number of compiler flags you have to remember or tell other people about, and/or (b) you start to get enough files that recompiling all of them whenever anything changes takes too long so...
A file called test.cpp in ~/test code is ``` #include <stdio.h> #include "add.h" int main(){ printf("%d\n",add(1,2)); } ``` file add.h is in ~/test/1, which is just a subdirctory code is ``` int add(int a, int b){return a+b;} ``` then i use export ``` export PATH=$PATH:~/test/1 ``` Is there any way to f...
exportis used to create an environment variable for the shell. It has no bearing on where the compiler looks to find your include files. gcc -Itest/1 test.cppshould make it work. The -I argument gives gcc a path to look for include files in. You can use amakefileorcmaketo give these specific instructions to gcc if y...
when we want to compile a multi file together. Why we need to convert .c file to .o in the makefile instead of just gcc file1.c file2.c -o newfile For example ``` \\ in make file file: file1.c file2.c gcc file1.c file2.c -o combination \\ we can just call make in the terminal \\ i have watch video on youtube...
You don't need to. Go ahead and do it that way; it will work fine for very simple cases. Makefiles are useful when (a) you have a number of compiler flags you have to remember or tell other people about, and/or (b) you start to get enough files that recompiling all of them whenever anything changes takes too long so...
I am learning C and came across something I was curious about. For me, calling foo in main like follows does not return anything: ``` int foo(bar){ return bar * 2; } int main(){ foo(10); } ``` Only when I format the output with printf will it return the result from foo to main. Is this intended or am I miss...
The function call foo(10) in ``` int foo(bar){ return bar * 2; } int main(){ foo(10); } ``` indeed returns the value. But you were not capturing it in any variable or printing the returned value. Your second example actually prints the value returned fromfoo(10);
I need to get a user name from a user and open a file with his name if it already exists. if the file doesn't exist I need to create one. now I don't really know how to do it. (in c) is this code line legal? ``` fopen("%s.txt", "r+", username); ``` and if not what alternatives do I have? maybe there is a better way...
Try this: ``` char* ext = ".txt"; char* filename = malloc(strlen(username) + strlen(ext) + 1); sprintf(filename, "%s%s", username, ext); FILE* file = fopen(filename, "r+"); free(filename); ```
i watch some code and i don't know what the meaning ofwhile(~scanf ``` while(~scanf("%s", word+1) !=EOF) { int a= strlen(word+1); ``` i already search google and found nothing on this. Please help
Analyzing the expressionwhile(~scanf("%s", word+1) != EOF): Run as long as the bitwise-inverted return value ofscanfis not equal to the value ofEOF. Analyzing the equivalent expressionwhile(scanf("%s", word+1) != ~EOF): Run as long as the return value ofscanfis not equal to the bitwise-inverted value ofEOF. Assumi...
I was trying to execute a malloc sentence like the following one: ``` TYPODATO *prof=(TYPODATO *)malloc((size_t)H*V*B2*sizeof(TYPODATO)); ``` with beingH*V*B2*sizeof(TYPODATO)equal to 13037160840 B = 13.04 GB. If I execute the commandfree -min the console to obtain the available memory in MB, I get 13486 MB = 13.486...
malloc()does not work this way.malloc() allocates a single contiguous block of memory.You are trying to allocate more memory than contiguously available, hence the error.
I'm creating a wxFrame with the following call: ``` new wxFrame(NULL,wxID_ANY,wxEmptyString,wxDefaultPosition,wxDefaultSize,wxCAPTION|wxSTAY_ON_TOP|wxRESIZE_BORDER|wxMAXIMIZE_BOX|wxFRAME_NO_TASKBAR); ``` But although wxMAXIMIZE_BOX is set, there is no related button shown in the title bar of the frame. What am I doi...
You need to usewxSYSTEM_MENUforwxMAXIMIZE_BOXto have effect under MSW. Arguably, wx might add the former automatically if the latter is specified, just as it already does forwxCLOSE_BOX-- but currently it doesn't.
I have some doubts about the style of C code comments. like this: ``` /* \brief Creates a new shm pcm */ ``` sometimes it like this: ``` /* \!brief Creates a new shm PCM */ ``` What is the difference between the "\brief" and "\!brief"
Those are comments meant forDoxyGen, a system to generate documentation from the source code. For the compiler, there is absolutely no difference at all. DoxyGen expects/*! */and/** */to flag that the comments are meant for it, seethe documentation. As albert mentioned, it looks like that insrc/pcm/pcm.csome years ...
I'm creating a wxFrame with the following call: ``` new wxFrame(NULL,wxID_ANY,wxEmptyString,wxDefaultPosition,wxDefaultSize,wxCAPTION|wxSTAY_ON_TOP|wxRESIZE_BORDER|wxMAXIMIZE_BOX|wxFRAME_NO_TASKBAR); ``` But although wxMAXIMIZE_BOX is set, there is no related button shown in the title bar of the frame. What am I doi...
You need to usewxSYSTEM_MENUforwxMAXIMIZE_BOXto have effect under MSW. Arguably, wx might add the former automatically if the latter is specified, just as it already does forwxCLOSE_BOX-- but currently it doesn't.
I have some doubts about the style of C code comments. like this: ``` /* \brief Creates a new shm pcm */ ``` sometimes it like this: ``` /* \!brief Creates a new shm PCM */ ``` What is the difference between the "\brief" and "\!brief"
Those are comments meant forDoxyGen, a system to generate documentation from the source code. For the compiler, there is absolutely no difference at all. DoxyGen expects/*! */and/** */to flag that the comments are meant for it, seethe documentation. As albert mentioned, it looks like that insrc/pcm/pcm.csome years ...
I am using a loop to delete characters from a string using printf(\b) 1 by 1 and sleep 0.1 seconds in between. But when I run the code it happens simultaneously. I literally tried typing each printf because I thought the loop might be the cause but still, the output was the same ``` #include <stdio.h> #include <unis...
printfoutput is buffered. Usefflush(stdout)to force it to output immediately. Also,\bmoves the cursor left but doesn't erase the character under a cursor. Print"\b \b"to move it back, print a space, and then move it back again. ``` printf("\b \b"); fflush(stdout); ```
For example, in python, you can index strings like this ``` some_string = "hello" substring = some_string[0:3] ``` and substring will be "hel" however, in C, if I have ``` char some_string[] = {'h', 'e', 'l', 'l', 'o'}; ``` Is there a way to get just ``` {'h', 'e', 'l'} ``` There is probably a very simple solut...
Not very simple, primarily because of memory management. You either needsubstringto be an array of sufficiently many characters, or need to allocate the memory dynamically. for example: ``` char *some_string = "hello"; char substring[4]; strncpy(substring,some_string,3); substring[3]='\0'; ``` or: ``` char *substri...
I have 2 files:stack.handstack.c. Both of them have a undefined typeelem_type. So my question is:Can I leave them undefined until I include the stack.h and then give it a definition depended on the need of the calling file ?
You cannot leave undefined type in stack.c in C because when a compiler tries to compile stack.c it won't be able to determine the type. In C++ this is feasible via template.
I am creating a message queue using the POSIX mqueue API: ``` mq_open("/myqueue", O_CREAT | O_WRONLY, O_WRONLY, NULL) ``` I also mount the directory for the message queue objects: ``` su mkdir /dev/mqueue mount -t mqueue none /dev/mqueue exit ``` When I run my program, the message queue appears in /dev/mqueue with...
Your arguments to the function are wrong. You're passingO_WRONLYas themode, but it's a flag, just like the otherO_*. Instead you should do: ``` mq_open("/myqueue", O_CREAT | O_WRONLY, 0600, NULL); ``` or some other file access mode that you want (0600=rw-------).