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 warning go away?
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++) { checksum += *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 2 10 4 5
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 call, not just calldo{uppercase_x}(). It must be done at compile time. And thexparameter must be a string. Thanks!
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 expand todoAanddo(b)would expand todoB. Update: As paddy mentioned,dois a reserved keyword in C, so you should pick a different name for your macro.
``` #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][1]; ptr[1][0]; ptr[1][1]; return 0; } ``` I have declared the array of pointers to function pointers. But with this code, functions are not getting called. Kindly let me know what is going wrong here.
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 to byptr[0][0].
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 spawned all at once?
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 top of this which can tell you the maximum number of processes that the user is allowed to create. SeeFreeBSD-specific documentation,Linux-specific documentation.
``` #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 explain this.
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 <stdio.h> void square(int *n); int main(){ int number;printf("Enter number : "); scanf("%d", &number); square(&number); return 0; } void square(int *n){ *n=(*n)*(*n); printf("Square : %d\n", *n); } ```
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 new thread. Geeks for Geeks says:
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 } that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified. The return value for any other function is user-defined.
``` 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 variable namea[1]and the comparison was madec==a[0]then the variable name would implicitly decay into *a(0) which is a pointer to the first element in the array. But without a variable name how is the string literal"a"read as a pointer. Does the compiler itself assign a pointer to this string to execute the comparison?
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 the global variable. I do realise that pointers can be used to solve this problem, but I am unable to figure out how. Please help me out.
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 +---------+ +---------+ +---------+ | ------->| ------->| | +---------+ +---------+ +---------+ :? :? :? :? ``` As you can see,int(*)[]is closer toint*than toint**. ``` 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 the global variable. I do realise that pointers can be used to solve this problem, but I am unable to figure out how. Please help me out.
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 +---------+ +---------+ +---------+ | ------->| ------->| | +---------+ +---------+ +---------+ :? :? :? :? ``` As you can see,int(*)[]is closer toint*than toint**. ``` 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 diagnostic message from Neovim's LSP
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 are written one per line. A samplecompile_flags.txtlooks like this: ``` -Wall -std=c++11 -L/usr/local/lib -I/usr/local/include -lfmt ```
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; } database; int main() { struct database database = {-481}; printf("%x", database.organization); return 0; } ``` expected result: fffffffffffffe1f result recieved: fffffe1f
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 = {-481}; printf("%"PRIX64, database.organization); return 0; } ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closedlast year.Improve this question Hi! So I was playing with command line arguments to get used to work with them. I tried to make the program to say valid if the argument I would write is the same as the one saved in the variable. Any ideas why this doesn't work?
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 different. { printf("Invalid\n"); } ```
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 (expression) statement1; ```
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. Creating c programming IDE is possible with flutter or not?
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 emulating the terminal you can use Xterm:https://pub.dev/packages/xterm
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 entry that matches those same details, then you will have the state from that entry. Have a look at the following enumeration functions: TCP: GetTcpTable()/GetTcpTable2()(IPv4 only)GetTcp6Table()/GetTcp6Table2()(IPv6 only)GetExtendedTcpTable()(both IPv4 and IPv6) UDP: GetUdpTable()(IPv4 only)GetUdp6Table()(IPv6 only)GetExtendedUdpTable()(both IPv4 and IPv6)
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 difference between these handles and the PID shown in the Task Manager. The spawn function only ever returns very low values, like "248" and not what actually shows in Task Manager. Can I use the return value of _spawn to kill a process and if so, how?
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()should be called before write() or after write() call. I've read couple of books on the topic, looked on the internal as well but couldn't find a satisfactory answer.
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__; # define arch_exception_stack (&__stackheap_end__) #endif ``` I know##is used for string concatenation but I've never seen this double$$sign. Not knowing what that is, I can't search for the right term. How is this$$used in C?
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 the Arm platform.
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 sticking more closely to the language standard. It warns for some uses of language extensions that the compiler otherwise considers normal but that can make the program non-portable to other compilers.
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) { printf("<%s> not found.\n"); } else { ptrdiff_t offset = needle - haystack; int precision = (int) strlen(target); printf("<%.*s> found at offset %td.\n", precision, needle, offset); } ```
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[] = {'H', 'e', 'l', 'l', 'o'}; printf("len = %d\n", strlen(a)); printf("len = %d", strlen(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 zero to the array ```
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 address with pointer additionchange the pointer on that address to point to new address ``` int *ptr[5]; void *change_addr = ptr[0]; void *p = change_ptr + sizeof(int*); *p = (void*)(uintptr_t)(new address); ```
``` 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 struct : typedef struct { int z; char c[10]; } y_t; typedef struct { y_t y; } x_t; int main() { x_t x = get_x(); printf("c: %s", x.y.c); return 0; } ``` Will you please help me know, How can I do that?
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 main(){ int distance; int noOfLiters; printf("Enter The distance:"); scanf("%d",&distance); printf("Enter The Fuel Spent:"); scanf("%d",&noOfLiters); float avgFuelConsumption = noOfLiters/distance; printf("Average Fuel Consumption : %f", avgFuelConsumption); } ``` Output ``` Enter The distance:50 Enter The Fuel Spent:5 Average Fuel Consumption : 0.000000 ``` The Average Fuel Consumption should be0.1, but I got 0, Why?
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 Given Number : %d" , xS); } ``` after entering the value120, nothing is happening! I am using Clion. What do I have to Do?
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(extension for ThreadX), but it should format the NOR Flash first to work
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 my code I found thatsubhook_unprotect(void*, unsigned long)is not even in my code.
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 value to$false. For reasons explained inthis answer, it is better to use$LASTEXITCODEdirectly for console applications ($LASTEXITCODE -eq 0to test for success) , because in PowerShell versions prior to 7.2,$?can yield false negatives.
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 works fine. However, the extension doesn't think so and red-squiggles the second curly brace with a "semicolon expected" error. The extension allows you to choose IntelliSense mode which I set to "windows-gcc-x64", however it doesn't seem to work. This issue exists since 2017. Is there a fix or a workaround?
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, what are ways you can use the %?
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 learn something useful.
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 = arr[i]; arr[i] = arr[j]; arr[j] = 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 /tmp/ ./myprog ``` fopen() works perfectly.
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.bininstead, and that presumably doesn't exist. (Note: a program can change its own directory with something likechdir(). But by default it just inherits the working directory of whatever ran it, which in this case is going to the shell thatsshdlaunched.)
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 3 and5. THe second result is in contradiction with the first result. Thus ,I try to find how to implement strlen(). ``` int strlen(char a[]) { int i; for(i=0;a[i]!='\0';i++); return i; } ``` Based on this code ,I can understand the first result,but really can't understand the second one. Why is the sceond result not 4 but 5?Thanks in advance.
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 change in the value of the struct field 'age') { // do the following; } } ``` I am struggling to write an if statement condition for that. Help would be much appreciated.
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 memory but it has the advantage that it's blindly working unless you have pointers inside yourstruct.
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(void){ a(); } int main(void){ a(); return 0; } ``` I want to ask why is not a compile-error generated in the first place, and also why this leads to aSegmentation fault. Thanks for reaching out.
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 or buffer allocation) extra zero after the binary data, thenstrstrwill happily go beyond the data and cause Undefined Behavior via buffer overflow. Or, to the point:strstrcan't be used if the data is not strings.memmemdoesn't have this limitation.
``` # 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 {3,4} and 3?
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 get to see all the results too but at a certain point if I scroll in the console app window the first half of the results are no longer visible . so out of 2836 results the first 1813 results get truncated in the c console app window .
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(inputString[length] != '\0') length++; // Reverse String int x; printf("%d\n", length+1); for(x = length-1; x >= 0; x--) { printf("%c", inputString[x]); } return 0; } ``` TBH, there are many errors in that code, but i don't know how to fix it. What can i do in this situation?
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 message or returnNULL(or other appropriate return value) and try to allocate memory again?
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 I could see trying to allocate but not using memory was in a program where you were just testing to see how much you could allocate on a system under a given load. Anyway I think 1 or 3 are probably most cases.
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 syntactically what I expect for a function parameter/pointer. I don't understand the syntax where "signal" is declared, and the trailing (int). I was wondering if someone could clarify this. -Thanks
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(42, foo); return 0; } ```
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 and the variable is define. My question is what is the difference between both of them and will it cause problem when I will cross-compile my project ? Thank you for all answer!
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 commonly used, or is there more to it?
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 2015 in x86 mode outputs: ``` long: 4 long long: 8 size_t: 4 ``` While compiling in x64 mode outputs: ``` long: 4 long long: 8 size_t: 8 ``` Having a separate size modifier forsize_tensures you're using the correct size.
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. Thanks in advance.
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 process will see its stdout/stderr connected to a non-terminal. Your best bet is to use an argument or environment variable to control whether the output is colored or not.
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:\[...]\EWARM\F041701a_beta000\Obj\Application\User\93c66.o] ``` And also got a warning ``` Warning: implicit declaration of function '__no_operation' is invalid in C99 ``` Is there a way to work around, resolve the issue? I can't find a solution at the moment. I'm using an STM32F0
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' both 8 bit, and 'third' 16-bit) If I have ``` pnt -> second ^= (1<<2) ``` this can be written as ``` pnt -> second = pnt -> second ^ (1<<2) ``` then this is saying that; get the value of 'second' from the structure MyStruct that is being pointed to by pnt. XOR that value with a bit that has been shifted left (i.e. 00000100). Whatever the result, put that back into MyStruct at the member 'second' yes? Thanks.
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 during download, i have usedcurl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, 60L)andcurl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 30L)curl options. Now, i want to retry 5 times after every 60 seconds to retry download (or to connect again to server) after timeout occurs. How we can do that in C ?
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); printf("%lf", Deposit_Amount); // it outputs 1802842372383946000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.00 ``` Isn't the scanf should set the value of Deposit_Amount to 0.00 if I input not a valid double?
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 the device or using another driver to communicate each interface of the device?
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: waveInOpenAbout the Windows Core Audio APIs
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 = temp; } ``` I don’t understand the difference between two methods, and is one method better than the other?
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); } ``` The output should be10, because 2 + 2 + 2 + 2 = 10. But, actually, the output is]0; What am I doing wrong?
``` #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); } ``` Output ``` Success #stdin #stdout 0.01s 5444KB 8 ``` IDEOne Link
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); } return 0; } ``` Seems to work fine on the first iteration but when it moves onto the second one that's where it gives me a segmentation error. The only thing I could find on other resources for similar problems was that I could be incorrectly allocating them.
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 static data needed for program operation to be bundled into the program in a way easy for the program to retrieve at run-time. Other systems have similar mechanisms. Files make sense when the data should be easily changed (such as configuration data), but when the data is needed for the program to operate at all it should be made difficult for a user to change.
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(int argc, char** argv) { void* dlhandle = dlopen("path/to/your/library", RTLD_LAZY); assert(dlhandle != NULL); void (*function_name)(int func_params) = dlsym(dlhandle, "func_name"); // Check for NULL again // Call your function etc return 0 } ``` Technically, you can also dynamically link to it as a system library too. I wouldn't recommend it though for a variety of reasons.
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 functionalities in the backend, kind of like an interpreter, I have the parser working amazingly in python but some of the backend capabilities I feel would do great on c. I have looked into CPython but I don't seem to understand how to do it if it's even possible at all. I'm just a beginner, if someone could guide that will be very helpful.
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 * 10); } ```
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 value50because it is less than 256 and you are using alittle-endianmachine.
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 syntax? ``` std::vector<uint64_t> reverseOrder(size + 1, 0); ``` I know thatcalloc()actually goes through the memory and sets them to 0, so I'm wondering if this is the case.
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 getAlwaysBreakAfterReturnTypeto work with__attribute__? This is version 14.0.0.
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 return f; // REPLACE ME WITH YOUR CODE } ``` Expected output: ``` ./sign_flip -42 sign_flip(-42) returned 42 ``` output: ``` ./sign_flip -42 sign_flip(-42) returned 0.10546875 ``` How would I go about fixing this? I am not sure what the issue is
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 autogenerated, stores the field type which means that this information is set in.protofile somehow.
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), ``` because it's my first time to see the "nanopb" project, I'm not 100% sure whether it will work or not.
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 after compilation. I've seen some code where they added ($PRODUCT) to the "Execute" option, but it didn't work for me. Any help is much appreciated!
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 your header file you can hide it either by setting theEXCLUDE_SYMBOLSto your struct symbol/definiton name(s) or as an alternative to theEXCLUDE_SYMBOLSoption you can usehideinitializercommand in the comment section of your struct type in the source code.
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 will stop the loop You loop will check the current node if it null it will stop, else it will point to the next node Check this useful answer also for more information:What is the difference between NULL, '\0' and 0?
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 crash if there is not a null terminator. I ran this in my code and it returned 6, so does this mean that assigning a string to a char pointer initializes with a null terminator or am I misunderstanding what's happening?
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 transfer the compiled app to the machine. Once I tried to run it, I found that it did not have execute permissions, and the compromised user account did not have permission to use chmod, however it did have permission to use GCC. I was wondering if I uploaded the code directly to the machine and compiled it natively, would the app have execute permissions?
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 ncurses! ``` wget https://ftp.gnu.org/pub/gnu/ncurses/ncurses-6.2.tar.gz tar xvzf ncurses-6.2.tar.gz cd ... ./configure --with-shared --with-normal --with-debug --enable-overwrite make sudo make install ```
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 getshell.c is as following: ``` #include <stdio.h> unsigned char shellcode[] = \ "\x48\x31\xf6\x56\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x57\x54\x5f\x6a\x3b\x58\x99\x0f\x05"; int main() { int (*ret)() = (int(*)())shellcode; ret(); } ``` Edit: I found this piece of codehere
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 example update the compiler to a different version or compile with a different optimization level. If you want the behavior to be well-defined, so that you can rely on a specific behavior, then you should only use valid conversion specifiers. You can use the%%conversion specification to print a literal%.
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: ``` gcc-11 -fopenmp jacobi2d1.c -o1 out/jacobi2d1 ``` But I am getting the following error: How do I do this? Any advice would be appreciated
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: both classes internally use an internal class calledGtkTreeDataListwhich implements this. The fact that it also knows about thiseGTypes is also the reason why you don't need to explicitlystrdup()your strings when passing them one for example: that's also something the subclass will lookup from the respective column types.
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", "strings" }; const int ARR_LEN = sizeof(s_array) / sizeof(s_array[0]); while (i < ARR_LEN) { printf("%s ", s_array[i]); i++; } printf("\n"); return (0); } ```
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 exit color&rem restored now ``` Also, don't forget to useSetConsoleCtrlHandlerto restore the color on Ctrl+C.
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 when it can't allocate enough space
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 this question ``` #include<studio.h> int main() { int a=5,i; i!=a>10; printf("i=%d",i); return 0; } ``` This code should print i=1 but it is printing i=0 Why is it so?
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 when it can't allocate enough space
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 this question ``` #include<studio.h> int main() { int a=5,i; i!=a>10; printf("i=%d",i); return 0; } ``` This code should print i=1 but it is printing i=0 Why is it so?
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_log.logI only get this ``` CLIENT_TRAFFIC_SECRET_0 af391f5fa21ca10ac61262e4<REDACTED>4 ``` trying to use this log file to decrypt the captured traffic in wireshark does not help and all packets are still encrypted, what am I doing wrong this is how I set the call back function ``` SSL_library_init(); ctx = init_ctx(); SSL_CTX_set_keylog_callback(ctx, SSL_CTX_keylog_cb_func_cb); ```
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 encountered the following problem while attempting to make a program which prints out all numbers with rational square roots (well, all numbers up to the point of overflowing, I guess). ``` 14:19: error: invalid operands to binary expression ('double' and 'int') while(sqrt(i) % 1 == 0) { ``` The problem seems to be in the%operator? Is it not supported inifstatements? What's the solution?
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. EDIT: realized I forgot to write #include <string.h> ... smh
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 program?
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 breaks either way. case (2): break; default: break; } break; // is this outer break still necessary? default: break; } ``` I hope someone can help me to understand the logic more deeply and accurately.
// is this outter break still neccessary? Yes. Alternatively you could show the nestedswitchinside a function andreturninstead ofbreak. Likely far more readable.