question
stringlengths
25
894
answer
stringlengths
4
863
I'm making a 16bit checksum of all words in a memory space from 0 to 0x0020000 with: ``` uint16_t checksum = 0; for (uint16_t * word_val = 0; word_val < 0x0020000ul; word_val++) { checksum += *word_val; } ``` I receive the warning "comparison between pointer and integer". How can I make this warn...
word_valis a pointer,0x0020000ulis an integer, and comparing them leads to a warning. To prevent this warning, just cast the integer constant to a uint16_t pointer, in order to compare datas of the same type : ``` uint16_t checksum = 0; for (uint16_t * word_val = 0; word_val < (uint16_t *)0x0020000ul; word_val++) { ...
c program to check odd or even without using modulus operator We can check a number is even or odd without using modulus and division operator in c program The another method is using shift operators number >> 1) <<1==number then it is even number,can someone explaain this?
A right shift by x is essentially a truncating division by 2x. A left shift by x is essentially a multiplication by 2x. 6 ⇒ 3 ⇒ 67 ⇒ 3 ⇒ 6 If this produces the original number, it's even.
This question already has answers here:What does the comma operator , do?(8 answers)Closedlast year. How can an array have an index like [0,1,2]?And why is [0,1,2]=[2]Code: ``` int main(){ int a[]={1,2,3,4,5}; a[0,1,2]=10; for(int i=0;i<5;i++) printf("%d ",a[i]); return 0; } ``` Output: 1 ...
The comma operator (,) evaluates both expressions and returns the second one (see, e.g.,this explanation). I.e.,0,1,2will evaluate to2, soa[0,1,2]=10will result ina[2]=10, which explains the output you get.
Having this code: ``` // Called when x is "a" #define do(x) doA() // Called when x is "b" #define do(x) doB() ``` Is it possible to make the preprocessor interpretdo("a")asdoA()anddo("b")asdoB()and maybe some otherdoUndefined()if unknownxprovided? To clarify: I want to mapxparameter to arbitrary code or function ca...
It can't be done for arguments with spaces. Without spaces, you can define macros for each allowed value. Those macros, in turn, can expand to your desired macros, insulating the argument names from the final macro names. For example: ``` #define do(x) do_##x #define do_a doA #define do_b doB ``` Thendo(a)would ...
``` #include <stdio.h> void test1(){ printf("test1\n"); } void test2(){ printf("test2\n"); } void test3(){ printf("test3\n"); } void test4(){ printf("test4\n"); } void (*hv_ptr[2])() = {test1,test2}; void (*dev_ptr[2])() = {test3,test4}; void (**ptr[2])() = {hv_ptr, dev_ptr}; int main() { ptr[0][0]; ptr[0][...
ptris an array of pointers to pointers to functions, soptr[0]is a pointer to a pointer to a function, soptr[0][0]is a pointer to a function. Thus, in the expression statementptr[0][0];, the expression is just a pointer to a function. It does not contain a function call. ptr[0][0]();is a call to the function pointed ...
I took a job interview and the following algorithm was asked and I didn’t manage to find out it’s purpose. ``` int func(int a, int b) { int c = b; while (c <= a) c <<= 1; int d = a; while (d >= b) { c >>= 1; if (c<= d) d -= c; } return d; } ```
This function returns the modulo (a%b).
When I was running a program that modifies files, and had loaded exactly 1000 files, the program aborted with the message: ``` Process launching failed: Too many open files ``` Where can I find the C constant to use in my code to figure out the maximum number of files that can be open and processes that can be spawn...
On POSIX-compatible systems, you can use thegetrlimitfunctionwith theRLIMIT_NOFILEparameter. ``` #include <sys/resource.h> rlim_t get_open_files_limit() { struct rlimit limit; getrlimit(RLIMIT_NOFILE, &limit); return limit.rlim_cur; } ``` Some systems (Linux, BSD, maybe others?) define anRLIMIT_NPROCon ...
``` #include<stdio.h> void square(int *n); int main(){ int number;printf("Enter number : "); scanf("%d\n", &number); square(&number); return 0; } void square(int *n){ *n=(*n)*(*n); printf("Square : %d\n", *n); } ``` This is my code, Here while running, it taking two inputs to run. I don't why. Can anyone e...
Please try removing the\nfrom your scanf. scanfwill try to consume each of the specifiers you are giving it. You are telling it to expect a 'newline', so it will consume the first newline you supply by hitting 'enter'. Essentially you are telling your program to expect the user to hit Enter twice. ``` #include <stdi...
return 0is a convention that it will execute when there is no error and it will return0. There is also a difference in writing return 0 insidemain()func and outsidemain()func. But what does it actually mean to return a value? It might be copy of some question. But I have read all the answers and then only making a ...
The August 4, 2022 working draft of the C standard, section 5.1.2.2.3 says: If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the }...
``` int main() { int c; c=getchar(); if(c=="a") { printf("fizz"); } else printf("buzz"); return 0; } ``` Output: ``` test.c: In function 'main': test.c:8:8: warning: comparison between pointer and integer if(c=="a") ``` As I understand it, if the string literal"a"was assigned to a vari...
String literals have type "array ofchar". And like any array, when one is used in an expression itdecays(in most cases) to a pointer to its first element. So the comparisonc=="a"is comparing aninton the left and achar *on the right, hence the warning.
I am trying to make a function in which you take in a value and it returns the value increased by 1. For example, ``` int n=5; printf("%d \n", n); increment(n); printf("%d \n", n); ``` should give an OUTPUT of: ``` 5 6 ``` Changing the value by using n++ or n+=1 inside the increment function is not changing ...
If you want to see the result that valuenchanged, you can do it without using pointers ``` int n = 5; printf("%d \n", n); n = increment(n); printf("%d \n", n); ``` And your increment function must return value with typeint
In some c code I inherited, I have seen the following ``` int (*b)[] = (int(*)[])a; ``` What is int(*)[] and how is this different than int**?
As perThe ``Clockwise/Spiral Rule'', int(*)[]is a pointer to an array of int. ``` int(*)[] int[] +---------+ +---------+ | ------->| | +---------+ +---------+ : : ``` int**is a pointer to a pointer to an int. ``` int** int* int +---------+ +----...
I am trying to make a function in which you take in a value and it returns the value increased by 1. For example, ``` int n=5; printf("%d \n", n); increment(n); printf("%d \n", n); ``` should give an OUTPUT of: ``` 5 6 ``` Changing the value by using n++ or n+=1 inside the increment function is not changing ...
If you want to see the result that valuenchanged, you can do it without using pointers ``` int n = 5; printf("%d \n", n); n = increment(n); printf("%d \n", n); ``` And your increment function must return value with typeint
In some c code I inherited, I have seen the following ``` int (*b)[] = (int(*)[])a; ``` What is int(*)[] and how is this different than int**?
As perThe ``Clockwise/Spiral Rule'', int(*)[]is a pointer to an array of int. ``` int(*)[] int[] +---------+ +---------+ | ------->| | +---------+ +---------+ : : ``` int**is a pointer to a pointer to an int. ``` int** int* int +---------+ +----...
I am trying to set up my Neovim for C development however, whenever I use: #include <SDL2/SDL.h> I get an error saying "In included file: 'begin_code.h' file not found". I did some digging and in my include files and I did see 'begin_code.h'. I am just very confused, could be because I am new to C. Screenshot of diag...
So apparently, clangd can not find this headers. clangd needs specific files to find where your header file is. According toclangd documentation, you can either generate acompile_commands.jsonfile for your project or usecompile_flags.txt. For simple project, usingcompile_flags.txtis sufficient. Your compile flags ar...
So I've just started learning C this week and currently practising basic functions. There was a question that required me to print out a long int in hexadecimal, but the printout I got wasn't the same as the sample answer. Here's the code I wrote. Thanks heaps. ``` typedef struct database{ long int organization; ...
long intis non-portable and can have different sizes. Instead use portable types fromstdint.hand in case ofprintfprint them usinginttypes.h: ``` #include <stdint.h> #include <inttypes.h> #include <stdio.h> typedef struct database{ uint64_t organization; } database; int main() { struct database database = {-...
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.Closedlast year.Improve this question Hi! So I was playing...
Usestrcmpto compare strings.In C, you cannot use==and!=to check for string equality. What you want is: ``` if (strcmp(argv[1], pass)) // Use String Compare (strcmp) to test equality. // Returns 0 if strings are equal // Returns non-zero if strings are dif...
With if (i==1) {something}- program will execute something on true what happens with if (i==1)- will it break or do nothing on false? I've seen program with if (id == 0x11)//OK with no {} and don't know if it does something. I think it should use next line as its "insides" but it wouldn't change anything
The next statement will be used as the if block. Opening brace does not necessarily be on the same line with the if, and a single statement if does not need to use opening and closing braces. All of the following are equivalent: ``` if (expression) // OK { statement1; } if (expression) { statement1;} if (expres...
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closedlast year.Improve this question which dependency can help me to run c programming language and show me the result. Cre...
You can use this for syntax highlighting:- https://pub.dev/packages/flutter_highlight For compiling C though you can use Online Compiler APIs like:- https://sphere-engine.com/compilershttps://www.jdoodle.com/compiler-api/https://www.hackerearth.com/docs/wiki/developers/v4/https://github.com/Jaagrav/CodeX-API For e...
You can get a connection state using thenetstatcommand (a connection state is something likeESTABLISHEDorTIME_WAITand so on). But can you get the connection state of a socket programmatically?
You can't query aSOCKETitself for the kind of state you are wanting. But, youcanquery the socket for its type (TCP vs UDP) and IP/Port pairs assigned to it (ie, viagetsockopt()withSO_BSP_STATE, or viagetsockopt(SO_TYPE)+getsockname()+getpeername()), and then you can enumerate Windows' TCP/UDP tables until you find an...
The documentation for the_spawnfamily of functions say they return a HANDLE when called with _P_NOWAIT. I was hoping to use this handle withTerminateProcess(h, 1); (In case the started process misbehaves.) ``` HANDLE h = (HANDLE) _spawnl(_P_NOWAIT, "C:\\temp\\hello.exe", NULL); ``` However, I don't understand the ...
This did the trick: ``` auto process_handle = (HANDLE)_wspawnv(_P_NOWAIT, argv[1], &argv[1]); auto procID = GetProcessId(ID); ``` thankssj95126
I understand the working ofwrite()call wherein it writes the data only to kernel's buffers which is later written to disk by kernel after sorting the data optimally. Callingfsync()on file descriptor makes sure that data is written to disk as soon as it's posted in the kernel's buffer. My question is, whetherfsync()sh...
fsync should be called after the write system call. It flushes the file data buffers and the metadata to the physical device.Alternatively, you can use the O_SYNC flag in the open system call for the file and get the same result for each subsequent write call.
I have a playerchar player = x;and want to overwrite a stringchar string[30];to contain"Player" + player + "won". I tried ``` strcpy_s(string, "Player "); strcat_s(string, player); strcat_s(string, " won\n"); ``` but obviously this doesn't work, becausecharis not compatible withconst char How can I do it instead?
You're looking forsnprintf, your general purpose string-formatting stdlib function. ``` snprintf(string, sizeof(string), "Player %c won\n", player); ``` You can read all about the different%formatting directives available in the above link, but%cis the one you want for characters.
I found in some Arm reference software, in the file, "arch/arm/armv7-m/src/arch_exceptions.c," the following lines: ``` #ifdef __ARMCC_VERSION extern char Image$$ARM_LIB_STACKHEAP$$ZI$$Limit; # define arch_exception_stack (&Image$$ARM_LIB_STACKHEAP$$ZI$$Limit) #else extern char __stackheap_end__; # ...
Whether or not those$$'field-separators' have any specific meaning to the target assembler and/or linker, I can't say, but the GNU C compiler does allowdollar signs in identifier names. So, presumably,Image$$ARM_LIB_STACKHEAP$$ZI$$Limitis the name of anextern charvariable defined in one of the support libraries for t...
Or - who is "stricter"? Fromwhat I've read, both flags add extra warnings, not included in '-Wall', but what distinguish them?
-Wextrais about turning on warnings that may be less useful or more of a nuisance (because they may warn about code that is acceptable to the programmer) than other options. It is generally for use when you want to scour your code for issues and make changes to satisfy these extra warnings. -Wpedanticis about stickin...
I would like to point to a certain part of a character array, i.e: ``` char string[] = "the quick brown fox jumps over the lazy dog"; char * pointer = points to the 'fox' part of string; ``` Is this possible to do without using strncpy or something similar?
strstr()or similar user code can be used to find a sub-string within astring. ``` const char *haystack = "the quick brown fox jumps over the lazy dog"; const char *target = "fox"; char *needle = strstr(haystack, target); ``` Toprinta portion of the string like"fox", use aprecision. ``` if (needle == NULL) { prin...
I am getting inaccurate string length when printing the length of a string using thestrlenfunction. I am getting the output for stringaas 5 (which is correct), but when I am printing the length of stringb, the output comes out to be 10(which should be 5). Here is the code snippet: ``` char a[] = "Yolow"; char b[] =...
Here's the original: ``` char b[] = {'H', 'e', 'l', 'l', 'o'}; ``` and here's a fix that turns an array of characters into a (null terminated) "string": ``` char b[] = {'H', 'e', 'l', 'l', 'o', '\0' }; // add ASCII 'NUL' to the array ``` or, alternatively: ``` char b[] = {'H', 'e', 'l', 'l', 'o', 0 }; // add ze...
Based on C's implicit casting rule, data types are converted to higher type. Nerveless when I try: ``` float a; int b; a = b = 3.4; ``` The output is always an integer number for bothaandb. Can I know the reason behind this? Why is it not convertinginttofloat?
Assignment (=) has right-to-left associativity (seeoperator precedence) sofloat a; int b; a = b = 3.4;is the same as: ``` float a; int b; b = 3.4; // b is now 3 (since it can only hold integer values) a = b; // a is now 3.f ```
How to go to a location with pointer addition and change the pointer at that position to point to a new address?The following code is just an example, I do not want an easy way as just doptr[1] = (new addr)but to change the address with the following method: create a new pointer variablechange_ptrgo to designated add...
``` int *ptr[5]; void *p = &(ptr[1]); &p = (void*)(uintptr_t)(new address); ``` Is this what you are looking for?
I am working on C Structures. I want to #define the struct values as follows. ``` // #define get_x() { .y = { .z = 1, .c = "test" } }; // this is working // But I want to replace the above line with #define get_y() { .z = 1, .c = "test" }; #define get_x() { .y = get_y() }; // this gives error ...
Remove the;, there is no;in initialization. Typically, macros are in upper case. ``` #define GET_Y() { .z = 1, .c = "test" } #define GET_X() { .y = GET_Y() } ```
This question already has answers here:Why dividing two integers doesn't get a float? [duplicate](7 answers)Closedlast year. I am writing a program to calculate an average fuel consumption from the given total distance (integer value) traveled (in km) and spent fuel (in liters). Code ``` #include <stdio.h> int mai...
Change ``` float distance; float noOfLiters; ```
This question already has answers here:What is the effect of trailing white space in a scanf() format string?(4 answers)Closedlast year. ``` #include <stdio.h> #include <math.h> int main(){ int x; printf("Enter The Number :"); scanf(" %d \n" , &x); int xS= sqrt(x); printf("Square Root of The Give...
You should remove whitespace and'\n'from the format string ofscanf. An '\n' or any whitespace character in the format string of scanf consumes an entire sequence of whitespace characters in the input. So the scanf only returns when it encounters the next non-whitespace character, or the end of the input stream.
I am looking for the fastest way to store data(about 50kb) with the applciation code during the flashing process and load it to be use by the application or by the kernel of the RTOS, I am using RTOS called ThreadX in STM32H7, the stored small data will determie how the application behave Note: I tried to use FileX(...
Your question is too vague. What speed do you need? What do you mean by store and load data? How small is "very small?" For volatile data, just store it in the on-chip ram. For non volatile data, you have many options - write to the on-chip flash is probably the fastest.
I have a question. I am learning C programming and while reading and storing user input into a char array I came across this code. Can someone explain to me what the"\r"mean? Thank you ``` arr[strcspn(arr, "\r\n")] = 0; ```
\ris ASCII character 13, called "CR" or "carriage return". Unix traditionally used \n (ASCII character 10, LF, line feed) as the end of a line, but Windows traditionally uses \r followed by \n (note that a lot of Windows functions do convert it to just \n). So to detect both, you can check for both \r and \n.
Error: ``` "subhook_unprotect(void*, unsigned long)", referenced from: _subhook_new in subhook-9679a6.o ld: symbol(s) not found for architecture x86_64 ``` Linking command:g++ -dynamiclib -fPIC -v -o finalcalling.dylib finalversion.cpp /Users/~/Desktop/c/subhook-master/subhook.c -std=c++11 After going through...
If this is your codehttps://github.com/Zeex/subhookthen it seems you are supposed to also include subhook_unix.c in your build. That file does definesubhook_unprotect. So does subhook_windows.c but I'm assuming you are on a unix like platform.
I created a simple test.c code: ``` int main() { int a; return -1; } ``` Compiling with: gcc -o test test.c Later I executed it: .\test.exe Is it possible to see the return value in the terminal? not a log file.
PowerShell reports the process exit code of the most recently executed console application in theautomatic$LASTEXITCODEvariable. The relatedautomatic$?variableis anabstractsuccess indicator, reporting$trueor$false, forallcommands; in the case of console applications, a process exit code of0maps to$true, any other val...
I edit my C code with VS Code (1.17.0) with C/C++ Extension (1.12.0) that provides error checking. I compile my code with GCC compiler that supports nested functions. So if I write this ``` int foo(int x) { int bar(int x) { return x * 2; } return bar(x) + 1; } ``` and compile it with gcc it w...
C/C++ extension for VSCode does not support nested functions yet. There is an issue open in their repo already, which you can trackhere. ... it's been there since 2017 though
This question already has answers here:format string used in printf function in C programming(2 answers)Closedlast year. when you write code such as printf("Average score: %f\n", (score[0] + score[1] + score[2]) / 3.0); what is the point of the %f , is it needed?, i know that sometimes you change the letter after it...
that's aprint formatter. "f" is for floats (decimals). the % is used when you want to put a variable value in a printf statement. So % followed by a letter (f,d,c,s,p, etc) indicates the type.
I'm trying to debug a segfault in my C program. I added a fewprintf(), but it generates a lot of text, so I tried to redirect the output: ``` ./a.out > log ``` It didn't work, it printedSegmentation fault (core dumped)in the terminal and didn't print anything to the log file. Is there some way to fix this?
fflush(stdout)will force output to be written. The much more powerful approach is to ensure your program is compiled with debugging information (gcc -g3) then use a debuggergdb ./a.out core.btwill now tell you were your program crashed. You can often usestrace,ltrace, eBPF (Linux) or similar tracing utilities to lea...
I have written a sorting algorithm. What is the name of this algorithm? ``` void sort(int *arr, size_t len) { int flag = 1, temp; while (flag != 0) { flag = 0; for (int i = 0, j = 1; i < len - 1; i++, j++) { if (arr[i] > arr[j]) { flag = 1; temp ...
This isbubble sort: repeatedly loop over an array swapping adjacent elements and stop when nothing is swapped.
Here is part of my C program: ``` FILE* f; f = fopen("data/file.bin","rb"); ``` when program is running via SSH like this:ssh -t root@xxx.xxx.xxx.xxx /tmp/myprog fopen() always returns null pointer. However, when I'm connecting to the device via SSH and running myprog, like this: ``` ssh root@xxx.xxx.xxx.xxx cd /...
data/file.binis a relative path, so the location it refers to depends on what directory you're in (your "working directory") when you run the program. If youcdto/tmpfirst, it'll resolve to/tmp/data/file.bin. If you don't, logging into root probably puts you someplace like/root, so it'll resolve to/root/data/file.bini...
I am wondering why the size of my char is 4 bit? Shouldn't it be 8 bits by todays standards? ``` #include <stdio.h> #include <limits.h> int main(){ printf("%zu\n", sizeof(CHAR_BIT)); return 0; } ``` I am using a 2015 built Laptop i guess with a x64 processor. Program Output: ``` 4 ```
CHAR_BITis something like ``` #define CHAR_BIT 8 ``` As such, you are printing the size of anint, which is 4 bytes for you. I think you wanted ``` printf( "%d\n", CHAR_BIT ); ```
The function strlen() counts the number of characters in a string up to NUL and it doesn't contain NUL.In ASCII,NUl is equal to '\0'. ``` #include<stdio.h> #include<string.h> int main(void) { char a[]="abc"; char b[]="abcd'\0'def"; printf("%d\n%d",strlen(a),strlen(b)); return 0; } ``` The result is ...
You are getting 5 because you have wrapped theNULcharacter in single quotes, the value 5 is the length of the string "abcd'". If you change the second example to"abcd\0ef"(no single quotes), you get a value of 4.
Here's my function which takes a pointer to an integer. ``` void ft_ft(int *nbr) { *nbr = 42; } ``` Can someone explain me how to write a test for this function?
You could add a call and an assertion (which will only be active in debug builds): ``` #include <assert.h> void ft_ft(int *nbr) { *nbr = 42; } int main(void) { int foo = 0; ft_ft(&foo); // call the function assert(foo == 42); // exit with an error message if foo is not 42 } ```
so lets say I have a function which updates a struct field: ``` struct person { int age; }; ``` ``` void update_struct (int value) { person->age = value; } ``` I want to detect whether the value of the struct field has changed in another function. ``` void another_function () { if (there is a chan...
You can't do this directly, either you keep a flag which you modify when you alter a field or you keep a copy of the struct andmemcmpit, just remember that alignment may place some padding in the struct to you must make sure thatsizeof(type) == sizeof(field1) + sizeof(field2) + .... The latter solution wastes more me...
I thought that calling ainlinefunction inside of itself wouldn't be allowed because it would lead to something like infinite source code when the function's invokations get replaced with its body(if that happends). But, when I test is that allowed, I get aSegmentation fault. Example code: ``` static inline void a(voi...
As @HolyBlackCat mentioned - inline is only a hint for a compiler. Compiler ignores it in a lot of cases. As for your test - your recursive code causes a crash because ofstack overflow error- every function call reserves a memory block on the stack and your program runs out of memory.
this line should get input from the user and stop when he presses enter. here is the line: for (i = 0; (t[i] = getche()) != '\r'; i++); //works for (i = 0; t[i] = getche() != '\r'; i++); //t is getting gibberish values
Order of operations.!=is higher precedence than=. Without parentheses, you get the character, compare it to'\r', and assign either1or0tot[i]depending on the result of the comparison, rather than assigning the character read as intended (and as you do correctly with the parenthesized version).
Is there any use case that can be solved by memmem but not by strstr? I was thinking of able to parse a string raw bytes (needle) inside a bigger string of raw bytes(haystack). Like trying to find a particular raw byte pattern inside a blob of raw bytes read from C's read function.
There is the case you mention: raw binary data. This is because raw binary data may contain zeroes, which are interpreted and string terminator bystrstr, making it ignore the rest of the haystack or needle. Additionally, if the raw binary data contains no zero bytes, and you don't have a valid (inside the same array...
``` # include<stdio.h> int main() { int arr[2][2]; arr[0][0] = 1; arr[0][1] = 2; arr[1][0] = 3; arr[1][1] = 4; printf("%d", arr[1]); printf("%d", arr[1][0]); return 0; } ``` The output for the above code is coming out as unsigned int. Output:64222963 How do I get the output as {...
Your first printf() statement references an array (arr[1]), so it's printing out the address of the array. Your second printf() statement prints an array element, but since you didn't include an endline ("\n") in your first printf(), it just gets added onto the end of the first printf().
Hi I have this small issue where I created a Named pipe in C to execute commands in CMD on windows . The problem is when the following command is executed sc query state= all it returns 2000 results If i open up a normal cmd window I can see all the results but if I run it through my C named pipe console app I g...
I found the answer you just have to adjust the console buffer size in command prompt to 3000 etc to cater for the additional data.
My array works fine if array is above 7 and if below 7 it will stuck at 7 and the remaining array will be filled with random characters ``` int main() { char inputString[1001]; for (int i = 0 ; i < sizeof(inputString) ; ++i) { scanf("%c", &inputString[i]); } int length=0; while(input...
Start by initializing the array: ``` char inputString[1001] = {0}; ```
I've stumbled upon a problem of memory allocation. I am writing a simple application that is supposed to read files and get information from them. It is supposed to be very simple (single threaded) so I was wondering what should I do ifmalloc()orcalloc()fails? Should the functionexit()the program with some error mess...
If malloc fails you basically have 3 options: free some memory and try again.don't allocate and do something else instead.exit the program. assuming you needed the memory to store some data then 2 wouldn't be an option, and in that case you either do 1 or 3. No one can predict all possible programs, but one reason ...
When running a "make" command, fatal errors are returned due to missing linux headers. Example: fatal error: file not found
I resolved this issue by creating aUbuntuvirtual machine (VM) usingVirtualBox. Installed required softwareMounted shared folder The make commands ran successfully in the vm.
``` int main() { // istead of :) i want to have an emoji added to my text. printf("Thank you for looking into my question :) "); return 0; } ```
Youlook upthe unicode code for the emoji of interest, prefix the code with the universal character name\Uwhen printing: ``` #include <stdio.h> int main() { printf("%s", "\U0001f600"); // :-) return 0; } ``` Your terminal must support unicode and the font you use must have a glyph defined for the emoji.
This question already has answers here:Understanding typedefs for function pointers in C(8 answers)Closedlast year. I found this declaration in the APUE book in the chapter on signals: ``` void (*signal(int signo, void (*func)(int)))(int); ``` I don't fully understand the syntax. The declaration of (*func) is synt...
The functionsignalreturns a pointer to a function of typevoid (int), and has two arguments: anintand a pointer to a function of typevoid (int). So something like this should work ``` void foo(int); void (*signal(int signo, void (*func)(int)))(int) { return func; } int main(int argc, char *argv[]) { signal(...
In my code i am using the variable PATH_MAX for a buffer size. I had a problem when i was including the library who is supposed to define it#include <limits.h>. When i use this library my IDE doesn't recognize the variable as being define but when I include the library like#include <linux/limits.h>there is no problem ...
The limits.h header is a standard header that all implementations are required to supply. This contains numerical limits such asINT_MINandINT_MAXamong others.PATH_MAXisnotpart of this file. The linux/limits.h header is specific to Linux. It is here thatPATH_MAXis defined.
What is the difference between%zuand%luin string formatting in C?%luis used forunsigned longvalues and%zuis used forsize_tvalues, but in practice,size_tis just anunsigned long. CppCheck complains about it, but both work for both types in my experience. Is%zujust a standardized way of formattingsize_tbecausesize_tis c...
but in practice,size_tis just anunsigned long Not necessarily. There are systems with a 32 bitlongand a 64 bitsize_t. MSVC is one of them. Given the following: ``` printf("long: %zu\n", sizeof(long)); printf("long long: %zu\n", sizeof(long long)); printf("size_t: %zu\n", sizeof(size_t)); ``` Compiling under MSVC...
During the execution of a C compiled program in a terminal,isatty(fileno(stderr))as well asisatty(0)returns 0 in my code when I use thempirunormpiexeccommands. Why ? and How do I know if stdout is a terminal or redirected while using MPI ? I'm actually printing colored stuff, but this makes the output parsing harder...
mpirun/mpiexec starts all processes with stdout/stderr connected to a pipe or socket that leads back to the mpirun process. The mpirun process collects everything from all of these pipes/sockets and copies it to its stdout. So only mpirun itself still has stdout/stderr still connected to a terminal. Any other proce...
I've an old code that perfectly works in IAR IAR 7.60 I would like to port it to IAR 9.20.4. The only issue while compiling is that I got a__no_operation();line of code that generates an error while compiling IAR reports the error as ``` Error[Li005]: no definition for "__no_operation" [referenced from C:\[...]\EWA...
you need to add to your program: ``` #include "intrinsics.h" ``` Which defines this inline function.
I'm trying to understand the correct use of the -> operator in C. I think I have the understanding, but need to have that validated. so... if i have an 32 bit data structure (eg. MyStruct) to store some status data (1s or 0s) which is pointed to by pnt. there are 3 members of that data structure ('first', 'second' bo...
pnt->secondis a shorthand for(*pnt).secondwhich means "take the struct pointed to bypntand from that struct, get the elementsecond".
I have wrote a code that will download file with multiple curl handles in parallel from server in multipart and then it will merge the downloaded file parts. I am usingcurl_multi_performandcurl_multi_add_handlefor this purpose. To give time out error after 60 seconds, if download operation get interuppted in between d...
Store the attempt counter in the private pointerCURLOPT_PRIVATE ``` void *private; curl_easy_getinfo(curl, CURLINFO_PRIVATE, &private); long counter = (long)(intptr_t)private; counter++; if (counter < 5) { curl_easy_setopt(curl, CURLOPT_PRIVATE, (intptr_t)private); curl_multi_add_handle(multi_handle, curl); } ```...
``` scanf("%lf", &Deposit_Amount); ``` This statement returns garbage value instead of 0.00 when I enter a character. Here's my code ``` double Deposit_Amount; StartDepositInput:; system("cls"); printf("Enter amount to deposit: "); scanf("%lf", &Deposit_Amount); // when I enter 'g' fflush(stdin); ...
you need to check scanf return value ``` if(scanf("%lf", &Deposit_Amount) != 1) { Deposit_amount = 0.0; /* some other error handling */ } ``` You should not flushstdin
In my project, ı need to write a program that can access an external soundcard and take discrete input sound data. The device uses isochronous data transfer and Usbccgp.sys driver. In that case, I can not use WinUsb and LibUsb functions. What should be my solution path in that situation? Writing a new driver to access...
Your sound card probably already has drivers, assuming it is a real product made by a company who wants its users to actually be able to use it. So you don't need to write drivers. Just use the appropriate Windows sound API. I'm not sure which one is the best, but here are some links to start off your research: wa...
i have encountered two methods of swapping two integer values and I’m confused about the difference. Method1(temp is a pointer): ``` void Swap(int *a, int *b) { int *temp = a; *a = *b; *b = *temp; } ``` Method2(temp is not a pointer): ``` void Swap(int *a, int *b) { int temp = *a; *a = *b; *b = ...
The first method does not work, because the former contents of theintpointed to byais not saved. The initializationtemp = acopies only thepointer. You might want to learnhow to debug small programsto see what happens.
I'm trying to make an addition (+) with the numbers of a string. I have tried to do this: ``` void add_numbers(string z) { char result = 0; for (int i = 0; i < strlen(z); i++) { result = result + z[i]; } printf("%c", result); } int main(void) { string z = "2222"; add_numbers(z); }...
``` #include <stdio.h> typedef char* string; void add_numbers(string z) { int result = 0; while(*z) { result +=*z++-'0'; // I love the symbol sequence here: +=*z++-'0'; } printf("%d", result); } int main(void) { string z = "2222"; // Correct answer is 8 add_numbers(z); } ``` Ou...
i have a sensor The datasheet says you can divide the data from the sensor by 100 to get the data you want. And for example, 0xff97 is -1.05km/h How does 0xff97 become -1.05 km/h?
0xFF97is-105in 16-bittwo's complement integer representation. If you divide that number by100, then you get-1.05 km/h.
Structure ``` struct products{ int id; char* name; int buy; int sell; int q; }; ``` Within my main I've delcared a vector ofproductsand have a for loop to assign the pointernamea value as such ``` int main(){ struct products arr[5]; for(int i=0; i<5; i++){ scanf("%s", arr[i].name...
scanf %sexpects a pointer to space to which it can write a string. arr[i].namewas never initialized. It's junk. It's not a (valid) pointer. You need to initializearr[i].nameso that it points to space to whichscanfcan write a string.
C23 will be supporting#embedallowing embedding data into an executable to be easier. My question is, however, why would one want to do that? Why not just read it from a file?
If the data should not change after the program is created it makes sense to bundle it with the executable. An example of this is windows resources (which don't use the new #embed mechanism because it long predates #embed). The resource mechanism allows data such as bitmaps, icons, menus, dialog layout and other stat...
I used Cython recently and discovered that it outputs a .so file. Can I use the .so file in my C program and if so, how do I implement that?
Yes, assuming that the SO file exports its internal functions to the dynamic linking scope, where a linker/library can find its functions (Seedlfcn.h). From there, you can call the functions that you have in the SO file. A very simple C code would look like this: ``` #include <dlfcn.h> #include <assert.h> int main(...
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.Closedlast year.Improve this question I'm Working on a program that takes in text from the user and then implements functionaliti...
CPythonis just an implementation of Python in the C programming language. If you want to incorporate C code, you can write extension modules documentedhere. Check outthisStackOverflow post as well. Alternatively, write a C program, compile it, and then call it via the subprocess module documentedhere.
I was trying to understand write function and its capabilities, I tried to write a function that gives the output of 5 since 5*10 is 50 but I could only write 1 byte I assumed that the output would be 5. Why is it 2? ``` #include <unistd.h> void ft_putchar(int c){ write(1, &c, 1); } int main(){ ft_putchar...
5 * 10is50. The character code50corresponds to the character2in ASCII. Therefore the output is2when interpreted as ASCII (or character code compatible to ASCII, such as UTF-8). Also note thatinthas typically 4 (or 2) bytes. It looks like the first byte, which is written via thewritefunction, contained the value50beca...
There is some code that exists in C which usescalloc()to create what effectively is a vector. It looks like this: ``` uint64_t *reverseOrder = (uint64_t *)calloc((size + 1), sizeof(uint64_t)); ``` I want to mimic this behavior with C++ syntax and vectors so that it works the same de-facto. Can I use the following sy...
You can just write ``` #include <vector> #include <cstdint> //... std::vector<uint64_t> reverseOrder( size + 1 ); ``` and all elements of the vector will be zero-initialized.
I have the following option set in my.clang-format: ``` AlwaysBreakAfterReturnType: All ``` However, if I have a function of the form ``` int __attribute__((deprecated)) someFunc(void); ``` it gets reformatted to ``` int __attribute__((deprecated)) someFunc(void); ``` Is there a way to get clang-format to getAlw...
It appears as though ``` int someFunc(void) __attribute__((deprecated)); ``` is equally valid and works just fine with clang-format.
This is the code I have so far ``` // given the 32 bits of a float return it with its sign flipped uint32_t sign_flip(uint32_t f) { int mask = 1; f = ~f; // 1's Complement while (mask > 0 && (mask & f)) { f ^= mask; mask <<= 1; } f ^= mask; // 2's complment retur...
IEEE 754 floating-point format is not 2's complement. Just flip most-significant bit: ``` float f = 42; *(uint32_t*)&f ^= (1 << 31); printf("%f\n", f); ```
How do I set aint32to use a fixed size for encoding? In theAPI, it says ``` PB_LTYPE_FIXED32 0x04 32-bit integer or floating point. ``` But what option do I set in the.protofile to encode aint32as aPB_LTYPE_FIXED32as opposed to aPB_LTYPE_VARINT? In the functionencode_basic_fieldthefieldsstructure, which is a...
I think you should try "int32_t" instead of int32. please check the "nanopb" project, in the file "nanopb_generator.py", there is a dictionary called "datatypes", here is some code: ``` FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32', 4, 4), FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32', 4, 4), ``` ...
When I allocate memory on the heap withmalloc(), there might be garbage in that memory unless I usecalloc()ormemset()to zero it out. Is this the same situation for the stack, or can I safely assume anything I allocate on the stack won't have garbage in it? Also, does this differ on different systems or OSes?
It is the same situation on the stack. Unless you explicitly initialize the values of variables to zero or some other value, variables withautomatic storage durationwill haveindeterminate values.
I'm using Matlab to generate some C code and MinGW is the compiler. This is how the toolchain is configured: Once the build process is finished I get an executable file that I can run, and it works fine (it's just a simple Windows console program). However, I can't find the options to run it automatically right af...
Following the advice from here: https://www.reddit.com/r/vim/comments/r6dthv/make_with_makefile_and_run_exe_from_same_command/ I added&& start C:\...\test.exe(where...is the full path) to the "Make Tool" option (bottom line) and it worked.
I've got the problem that doxygen will auto document all typedef structs from header files which are included in the configurations. They are listed as "Data structures" in the HTML documentation on the sidebar. Which option is needed to deactivate the auto documentation from structs? Thanks!
Since your struct definiton goes in the header file doxygen will document it automatically unless you define your structure in related C file; in this case it'd be private and could be prevented to output by setting the following options toNO: EXTRACT_ALLEXTRACT_PRIVATEEXTRACT_STATIC But since the definition resides...
In the below code a pointer (ptr) is used as the condition of a while loop. Can you tell me how that loop is working? ``` struct Node* ptr = head; while (ptr) { printf("%d -> ", ptr->data); ptr = ptr->next; } printf("null\n"); ```
In c there is no boolean type but Zero is interpreted as false and anything non-zero is interpreted as true. for example this if body will be executed ``` if (3) { printf("true"); } ``` also in CNULLis a constants with value 0 as(void *)type so in your loop any ifptris null the condition will be likewhile (0)so it...
For example in this code: ``` char *ptr = "string"; ``` Is there a null terminator in the stored in theptr[6]address? When I test this and print a string, it prints "string", and if I print theptr[6]char I get ''. I wanted to test this further so I did some research and found someone saying that strlen will always ...
Yes. String literals used as pointers will always end in aNULbyte. String literals used as array initializers will too, unless you specify a length that's too small for it to (e.g.,char arr[] = "string";andchar arr[7] = "string";both will, butchar arr[6] = "string";won't).
I am currently learning penetration testing as part of a cybersecurity career path. I was working on a vulnhub machine that required me writing some malware to exploit a buffer overflow bug. I decided to write it in C for the sake of practicing OpSec. I used code::blocks on my machine to write the code and used tcp to...
From my experience,rsyncwould be able to retain file permission when transferring between machines, maybe give it a try? From local machine:rsync -aP source_path remote_machine:destination_path -ais archive mode, preserves file properties -Pshows progress
I wanna learn something from ncurses, so that I can use assembly to write some simple functions to draw graphics. For example, when I step intoinitscr, then I'm right here/lib/x86_64-linux-gnu/libncurses.so.6, I can't see any c code. Do you have some any ways to solve this problem? I use below commands to install nc...
You need linkerlibncurses_g.a gcc -g ... -o ... /usr/lib/libncurses_g.a
I am trying to run this code to get a shell but I am getting a segmentation fault even with ASLR disabled. I am running this code on my AMD Ryzen 3 computer with Ubuntu 20.04 64bit version. I am compiling with the following command: ``` $ gcc -O0 -fno-stack-protector -z execstack getshell.c -o getshell ``` File get...
unsigned char __attribute__((section(".text#"))) shellcode[] works for me (mind the#) #is a trick - it comments part of the emitted assembly code by gcc.
This is the code I have so far? But its not working.. ``` uint64_t bit_swap(uint64_t value) { return ((value & 0xAAAAAAAA) >> 1) | ((value & 0x55555555) << 1); } ``` bit_swap(0x1111111111111111) should return 0x2222222222222222 but is returning 0x0000000022222222 instead
``` value & 0xAAAAAAAA ``` That is equivalent to :value & 0x00000000AAAAAAAA And since we know that anything anded with 0 will give 0 hence the top 32 bits will always be 0. Change to: ``` return ((value & 0xAAAAAAAAAAAAAAAA) >> 1) | ((value & 0x5555555555555555) << 1); ```
I try to rewrite printf function and i found a strange result when use format specifier (%) with ! or K. I want to understand why i get this result. ``` printf("%!"); printf("%K") ``` I get output ! and K. Thank for all response
According to§7.21.6.1 ¶9 of the ISO C11 standard, using an invalid conversion specification will result inundefined behavior. Therefore, you cannot rely on any specific behavior. Anything may happen. On different compilers, the behavior may be different. Even on the same compiler the behavior may change, if you for e...
I have to complete a project for university where I need to be able to optimise using compiler optimisation levels. I am using OpenMP and as a result I have got the gcc-11 compiler from brew. I have watched this videohttps://www.youtube.com/watch?v=U161zVjv1rsand tried the same thing but I am getting an error: ``` gc...
Optimization levels are specified with-O1etc, using capital letter O, not lower-case letter o. Lower-case-o1specifies that the output file should be1, and thenout/jacobi2d1is an input file to be linked, but it is an existing executable and you can't link one executable into another — hence the error from the linker.
I am reading the documentation forglib's CLI option parserand I'm very confused about one of theiroption flags. G_OPTION_FLAG_REVERSEFor options of theG_OPTION_ARG_NONEkind, this flag indicates that the sense of the option is reversed. What does this mean? What is the "sense" of an option"?
If an option does not take an argument, it can be considered boolean. The option is usually considered 'true' if present, or 'false' if absent. Those interpretations can be reversed, and that changes the sense of the option.
The functiongtk_tree_store_clear()does what the documentation says it does: the store is cleared and all lines inside the associated tree view disappear. Does this function also free the memory that the store used? For example, if the store had 1,000 lines ofgchar *, is all that memory freed?
Yes, otherwise everyone usingGtkTreeStore(orGtkListStorefor that matter) that would be dealing with a major memory leak. :-) That's also the reason why you have to pass a list ofGTypes to the constructors of those classes: GTK uses them to lookup on how to free them. If you want to know the implementation details: bo...
I've seen some videos where a 2D array is created to store the strings, but I wanted to know if it is possible to make a 1D array of strings.
NOTE:In C, a string is an array of characters. ``` //string char *s = "string"; //array of strings char *s_array[] = { "array", "of", "strings" }; ``` Example ``` #include <stdio.h> int main(void) { int i = 0; char *s_array[] = { "array", "of", "str...
I'm trying to print out the size of various data types I have in an array as strings, like so: ``` printf("%lu", sizeof(list_of_datatypes[i])) ``` A string for example would be "char", or "unsigned int". Is there a way I could get sizeof to see them as the reserved words they are in c?
You can't do that. Thesizeofoperator takes expressions or type names as an argument, and the result is evaluated at compile time (except for variably-modified types). It does not treat a string such as”char”as a type name. Is there any way to explicitly convert it? No.
I'm looking for a way to use SetConsoleTextAttribute() to reset the output color of the windows console, doing what\033[0mdoes on Mac and Linux. Is there any way of doing this? I'm looking to avoid external libraries and instead just use windows.h
I don't think there is a reset function, you just have to save the attributes when your program starts. To determine the current color attributes of a screen buffer, call the GetConsoleScreenBufferInfo function. cmd.exe works the same way: ``` color 09 cmd /k color&rem still blue because this instance started blue ...
Let's say I have the following code ``` m_box=gtk_box_new(GTK_ORIENTATION_HORIZONTAL,4); gtk_widget_set_halign (m_box, GTK_ALIGN_START); gtk_widget_set_valign (m_box, GTK_ALIGN_START); ``` Now I am adding multiple widgets and running out of horizontal space. How can I make it responsive? NOTE:- I am using gtk4
This is not something aGtkBoxcan do. It's quite "dumb" in that it doesn't care about reflowing or anything like that. It does one thing and one thing only: putting child widgets next to each other in a specific orientation. For your use case, you might be more interested inGtk.FlowBox, which rearranges its children w...
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.Closedlast year.Improve t...
That's because you don't do anything to i. Your "i!=a>10" evaluates to false, but the result is not stored into a variable. As it is mentioned in the comments, you need something like this: ``` int a = 5; int i = !(a > 10); ``` The != is mostly used in if-clauses, like ``` if (a != 0) {...} ``` I hope this helps. ...
Let's say I have the following code ``` m_box=gtk_box_new(GTK_ORIENTATION_HORIZONTAL,4); gtk_widget_set_halign (m_box, GTK_ALIGN_START); gtk_widget_set_valign (m_box, GTK_ALIGN_START); ``` Now I am adding multiple widgets and running out of horizontal space. How can I make it responsive? NOTE:- I am using gtk4
This is not something aGtkBoxcan do. It's quite "dumb" in that it doesn't care about reflowing or anything like that. It does one thing and one thing only: putting child widgets next to each other in a specific orientation. For your use case, you might be more interested inGtk.FlowBox, which rearranges its children w...
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.Closedlast year.Improve t...
That's because you don't do anything to i. Your "i!=a>10" evaluates to false, but the result is not stored into a variable. As it is mentioned in the comments, you need something like this: ``` int a = 5; int i = !(a > 10); ``` The != is mostly used in if-clauses, like ``` if (a != 0) {...} ``` I hope this helps. ...
I created this callback function to log the secret key ``` void SSL_CTX_keylog_cb_func_cb(const SSL *ssl, const char *line){ FILE * fp; fp = fopen("key_log.log", "w"); if (fp == NULL) { printf("Failed to create log file\n"); } fprintf(fp, "%s\n", line); fclose(fp); } ``` inkey_lo...
Using"w"mode, the previous contents of the file to open is erased to overwrite. Use"a"mode to append data to file.
``` #include <stdio.h> #include <cs50.h> #include <unistd.h> #include <math.h> void rationalSquareRoots(void); int main(void) { rationalSquareRoots(); } void rationalSquareRoots(void) { for(float i = 0; ; i++) { if(sqrt(i) % 1 == 0) { printf("%f\n", i); } sleep(1); } } ``` I've enco...
The%operator is only for divisions between integers. To calculate remainders of floating-point divisions, you should usefmod()function. Using this function, the condition should befmod(sqrt(i), 1) == 0.
Say I run the following in my command line $./(file name) abcd efg hijkl How would I best find the length of argv[1],argv[2], etc. In this example, I would like to hold argv[1], or "abcd", as an integer with a value of 4, argv[2], or "efg", as an integer value of 3, and argv[3], or "hijkl", as an integer value of 5...
strlenis used to find the length of strings. ``` #include <string.h> #include <stdio.h> int main(int argc, char *argv[]) { int i; for (i = 0; i < argc; i++) printf("%zu\n", strlen(argv[i])); } ```
I'm attempting to use ptrace to manipulate registers on aarch64. Looking at sys/user.h in my aarch64 toolchain (android-ndk-r10e), I see ``` #elif defined(__aarch64__) // There are no user structures for 64 bit arm. #else ``` Perhaps I'm missing something obvious but how do I get/set registers for an aarch64 prog...
struct user_pt_regsis defined in asm/ptrace.h which is (eventually) included by sys/ptrace.h.
In languages that haveswitch, usually abreak;statement is needed. What if aswitchwithin aswitchstatement? Is it necessary to put abreak;statement in the outerswitchwhen the innerswitchhas abreak;? e.g.: ``` // outer switch switch (a) { case 1: // inner switch switch (b) { // this inner switch brea...
// is this outter break still neccessary? Yes. Alternatively you could show the nestedswitchinside a function andreturninstead ofbreak. Likely far more readable.