question
stringlengths
25
894
answer
stringlengths
4
863
This question already has answers here:Confused by squaring macro SQR in c [duplicate](3 answers)The need for parentheses in macros in C [duplicate](8 answers)Closedlast year. what would be the output of this program ? ``` #include <stdio.h> #define s(x)x*x int main() { printf("%d",s(5+1)); return 0; } ``` the output of this code is 11 how?
It is because5 + 1 * 5 + 1is11. The multiplication comes first,1 * 5, so you're left with5 + 5 + 1=>11. To get36, change your macro to: ``` #define s(x) ((x)*(x)) ``` Which will then become((5 + 1) * (5 + 1))=>(6 * 6)=>(36)
I have a code ``` void(*updateFunc)(EW_Window*) = ((GlfwWindow*)wnd->wndData)->updateCallback; if (updateFunc) updateFunc(wnd); ``` Andif (updateFunc)always passes evenupdateFuncis0xcdcdcd(null in debugger). What's going wrong and how I can fix it?
0xcdcdcdis not null-pointer, it is a pattern used to mark unitialized memory. That value is considered as atruevalue in C. The problem is that((GlfwWindow*)wnd->wndData)->updateCallbackhas a wrong value...
Edit: I realized I can simplify the problem to just the following chunk of code: ``` unsigned char arr[20][50]; for(int i = 0; i<=20;i++){ strcpy(arr[i],""); } for(int i = 0; i<=20; i++){ for(int j = 0; j<5;j++){ strcat(arr[i],"0"); } } ``` Anytime I am usingstrcat()orstrcpy(), I get the following warning message in Clion: ``` Passing 'unsigned char [50]' to parameter of type 'char *' converts between pointers to integer types where one is of the unique plain 'char' type and the other is not ``` I am unsure how to address this. Thanks in advance for any help.
It is perfectly fine to passunsigned char *to C standard library string function likestrcpy(),strcat()etc. To get rid of warning message, you can simply cast theunsigned char *argument tochar *while passing it to C standard library string functions, like this: ``` strcpy((char *)arr[i], ""); ```
This question already has answers here:For vs. while in C programming?(19 answers)Closedlast year. Is it true that, in C, we can do anything usingwhileloop which can be done usingforloop and vice versa?
Yes, except for definition of variables insidefor ``` for (init; cond; incr) { body; } ``` Ifbodydoes not contain acontinuestatement, theforstatement above is completely equivalent to thewhileloop below. ``` init; while (cond) { body; incr; } ``` If you add an extra set of curly braces, even the definition of variables can be converted fromfortowhile ``` for (int i = 0; i < 100; i++) { printf("%d\n", i); } ``` is the same as ``` { int i = 0; while (i < 100) { printf("%d\n", i); i++; } } ```
I'm pretty newbie in C language and I have this little code in which I want to do some test in the main code. ``` struct ListNode { int val; struct ListNode *next; }; ``` I want to create some examples (For example: 4 -> 9 -> 1) in the main code, but I don't really know how to initialize them. Thank you in advance.
I would do something like this: ``` struct ListNode* addnode(struct ListNode *head,int val) { struct ListNode* newnode = malloc(sizeof(*this)); newnode->val = val; newnode->next = NULL; if (!head) head = newnode; else { struct ListNode *this = head; while(this->next) this = this->next; this->next = newnode; } return head; } int main(void) { struct ListNode *head = NULL; head = addnode(head,4); addnode(head,9); addnode(head,1); return 0; } ```
``` "0123456789abcdef"[num % base] ``` Puttingnum%base = 0 ``` "0123456789abcdef"[0] ``` It gives 48 but how. When i use 0 as index than it should give me 0.
"0123456789abcdef"is a string literal, which defines an array filled with those characters (plus a terminating null character).[num % base]is a subscript operator with the subscriptnum % base. So"0123456789abcdef"[num % base]selects one of the characters from the array. It is intended to select the character for the last digit ofnumwhen it is represented as a numeral in basebase. Whennum % baseis zero, it selects the “0” character. Your C implementation uses ASCII codes for some characters. The ASCII code for “0” is 48.
In JavaScript you can call a function if a certain Boolean variable is true: ``` booleanVariable && functionToExecute(); ``` Is it possible to do the same thing in C? Thank you
Yes, you can: ``` #include <stdio.h> int functionToExecute() { printf("ran function"); return 1; } int main() { int booleanVariable = 1; booleanVariable && functionToExecute(); return 0; } ``` https://www.mycompiler.io/view/HIbRP3W1uil
In JavaScript you can call a function if a certain Boolean variable is true: ``` booleanVariable && functionToExecute(); ``` Is it possible to do the same thing in C? Thank you
Yes, you can: ``` #include <stdio.h> int functionToExecute() { printf("ran function"); return 1; } int main() { int booleanVariable = 1; booleanVariable && functionToExecute(); return 0; } ``` https://www.mycompiler.io/view/HIbRP3W1uil
How do I Bold my PrintF? .. ( I am new in C) ``` #include <stdio.h> int main() { int i; for (i=1; i<=5; i++) { printf("Md.Mehedi hasan"); } return 0; } ```
If your terminal supports ANSI Escape Sequences, you can do this: ``` #include <stdio.h> int main(void) { for(int i = 1; i <= 5; i++) printf("\e[1mMd.Mehedi hasan\e[m"); return 0; } ``` The\eis the ESC character (ASCII 27 or 0x1B), andESC [ 1 msets bold, andESC [ mresets the display attributes, which resets bold.
I want to pass int to sysfs_store What I tried userspace ``` int tid = 5234; // can be negative as well char buf[5]; sprintf(buf, "%d\n", tid); write (fd, buf, 1); ``` driver sysfs_store ``` int v; kstrtoint(buf,10,&v); pr_info("%d\n",v); // printing only first digit 5. Should print 5234 ```
Sincesprintf()returns bytes copied count; use it Also switch tosnprintf()to avoid buffer overflows. ``` int data_len = snprintf(buf, sizeof(buf), "%d\n", tid); write (fd, buf, data_len); ``` It's always better to have bigger buffers to cover all your scenarios.
I create a table with 3 columns:int8,doubleandbytea. When query a row of data, I use PQgetvalue to get each column value in a row. But PQgetvalue return a char*, I have to convert text value to corresponding type, like atoi or strtod etc. Is there is a more efficient way to get actual data, avoid converting data every time?
There is not much overhead in converting achar *to a number. But you can use binary mode by callingPQexecParamswith 1 as the last argument. To retrieve binary data, you have to usePQgetlengthandPQgetisnullto get size and NULLness of the datum. Also, the data will be in the binary format used by the database server, so the representation of adoublecould be different if both machines have a different hardware architecture (although IEEE is used pretty much everywhere).
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closedlast year.Improve this question I have come across this virtual Keyword in C programming, but actually how it will helpful for the programmers.
Since your question is tagged with the C language, maybe you're confused. The wordvirtualisnota keyword in C. Itisa keyword in C++, but it is not part of the C language at all -- not even a reserved word. You can use it as an identifier if you like. But don't, because you will limit your program's ability to be ported to C++. In C++ it is used to declare a class member function that is polymorphic.
OK so I have the base address ofntoskrnl.exeand want to locate the address of an internal function that is neither exported or imported. How can this be done in kernel mode ?
You can pattern scan for the function, or it has a static RVA. There are many ways, but the easiest is by creating a signature (for example with SigMaker in IDA Pro) and scanning for it inside your module. For exported routines this is much easier: https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-mmgetsystemroutineaddress For within a specific module, you can manually walk the EAT (Export Address Table).
I’ve studied C, and now I’ve decided to switch to C++. So, in C, I used#ifndef#endifin my header files. Should I use the same commands in C++? Or are there some alternatives?
Yes, the preprocessor works(mostly)the same way, so you should still use preprocessor directives to guard against including the same code more than once. Any differences in functionality between the preprocessor in C and C++ are likely to be edge cases that are unlikely to be relevant at your current learning level.
If you have a function that takes the pointer of an array, would there be any use in using pointers to each element in the array, or is it redundant? For example: ``` int sum(int(*arr)[3]) { int i,j, sum = 0; for (i =0; i < ROW ; i ++) { for (j =0; j < COL ; j ++) { sum = sum + *(*( arr +i )+j); } } } ``` Would using arr[i][j] be the same in this case?
arr[i]is required by the standard to be equivalent to*(arr + i)so no, there is no point in not usingarr[i]which is more readable. Speeding up 2d array access is a complex topic. There are some techniques for performance improvement, but those take hardware architecture (e.g. cache) into account are are related to access patterns rather than access syntax.
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 when I did something like this: ``` int arr[]={11, 12, 13, 14, 15}; int *p=arr; *(p++) += 100; ``` The result of arr[1] was still 12,why?
You are adding100to the first element of the arrayarr[0]and then movingpto the next elementarr[1]. This expression: ``` *(p++) += 100; ``` Is actually translated into this: ``` *p += 100; ++p; ```
Do c/c++ preprocessors process all lines that begin with #? Does is errors out when encountering unknown macros or will it just ignore them? for an example, ``` #include <stdio.h> #hello int main(){ printf("Hello World!"); return 0; } ``` what happens in this situation?will it produce an error or will it work (ignoring #hello line)?
The language grammar specifies all pre-processor directives that exist in the language. If you use any other name for the directive, then that is a "conditionally-supported-directive". If the conditionally supported directive isn't supported, then the the language implementation is required to issue a diagnostic message and is free to refuse to proceed.
I am trying to dovery simpleinterrupt code in STM32F401RE where I press the button and LED2 should turn on based on external interrupt triggered by the button. I am using the user button(blue button) in nucleo board F401 which corresponds to PC13 according to the board datasheet pinout. I tried different options but LED2 is still off, here is the code i am using: ``` int main(void) { sysconfig(); Interrupt_config(); while(1) { if(flag) { GPIOA->ODR |= (1<<5); } } } ``` I used polling method (without interrupt) and the LED2 turns on fine when the button is pressed using only LED_initialize(); Button_init();
Haven't checked your IRQ setup code, but the handler you need for PC13 isEXTI15_10_IRQHandler. Edit: Another issue: EXTICR is 4 words long. This is incorrect:SYSCFG->EXTICR[4] |=(1<<5);.
I've learned about wild pointers and how to avoid them. I've heard that they point to a random value in memory and I was wondering if they actually have a random and completely irrelevant value or if they point to a certain value that's probably implementation dependent. Which is it?
These dangling pointers are not random in the "mathematical" sense. They point to an implementation dependent location (based on hardware arch, runtime sequence, etc), that your program isn't supposed to have access to & the content of the pointed location is undefined from your program's point of view. The operating system is free to re-allocate & write whatever whenever so your pointer to that memory is deemed "random" in its value.
I have the following code : ``` typedef unsigned short u16; struct S { struct { u16 a: 9; u16 b: 1; u16 c: 1; u16 d: 1; } __attribute__((packed)); u16 e: 4; } __attribute__((packed)); ``` when I checksizeof(S), it returns 3. is it possible to somehow instruct gcc to merge bitfields across anonymous structs so thatsizeof(S)returns 2.
The result you are looking for can be obtained by making the structureunioninstead, with two bit-fields overlapping. The bits "used" by the first bitfield will be marked as "reserved" in the second one: ``` union S { struct { u16 a: 9; u16 b: 1; u16 c: 1; u16 d: 1; } ; struct { u16 reserved: 12; // Number of bits used in the first struct u16 e: 4; }; }; ``` Demo
I try to control USB camera with libuvc on Ubuntu 20.04. when the ctrl value = 0x400 and the unit value = 0x200, I can calluvc_set_ctrl(device_handle, 0x4, 0x2, output_buffer, buffer_length), and it's successful to set value to specify register. But how can I offer value touvc_set_ctrl()when the unit value =0x303?
These are library-specific functions -- different implementations of UVC (for example on Windows) won't have these, so I think your question would be better suited to thelibuvcforum. For what it's worth, I tried looking at the libuvc documentation to read aboutuvc_set_ctrl, but the URL for the documentation on the README page isn't valid anymore:https://int80k.com/libuvc/doc/
I want to write a program like this to let sprintf() accept the function parameter ``` int x (char z) { //z is a character array float y = 10.254; sprintf (z, "%2.1f", y); printf ("%c", &z); } ``` However when I enter the array as a parameter, nothing happens. How can I let sprintf accept an external parameter
char zis just a single character. nothing more char* zis usually understood to be a string or a buffer capable of holding a string (or more precisely, a pointer to a character) %cis the format specifier for a single char.%sis for a null terminated char array (or char*) This is closer to what you want: ``` int x (char* z) { float y = 10.254; sprintf (z, "%2.1f", y); printf ("%s", z); } ``` Then invoke: ``` char buffer[100]; // big enough x(buffer); ```
I've been bitten in the ass a few times where I would write to an array out of scope. I have been working on a particular firmware for over 2 years and suspect an overflow which by now is close to impossible to find - for example: ``` uint8_t example[50]; uint8_t example2[100]; for(uint8_t i = 0; i < sizeof(example2); i++) example[i] = i; ``` I understand that the above code example is primitive. It's only an example of what I am trying to describe. Is there a package or function available that can detect these "leaks"?
Recent versions of GCC with the flag-Wallwill detect simple errors like the problem in your example, and print a warning. The tool Valgrind is more advanced, but also more work to configure and use correctly. There is no tool in the universe that can detect every possible mistake, so start with the easiest to use.
I am using emcc to compile c++ to wasm on Debian 11.It is successfully done.So I think emcc knows the path. But VS Code shows error squiggle under#include <emscripten/bind.h>because it doesn't know the path to the header file. Where is the header file? I'm not familiar to c++ and I install emsdk via git (I just follow the official tutorial herehttps://emscripten.org/docs/getting_started/downloads.html).
found at./emsdk/upstream/emscripten/bind.h https://github.com/emscripten-core/emscripten/blob/main/system/include/emscripten/bind.h
I know that the main function is just a "special" function, but can it be declared and then defined like any other function or not? This is also correct : ``` int main(void); int main(void) { } ``` or just this is correct : ``` int main(void) { } ``` ? P.S. I know that when a function is defined is automatically declared, but I didn't know how to formulate this question better.
It's fine to create a declaration for themainfunction (provided it matches the definition). It just won't be of any use because nothing else in your program callsmain, or at least it shouldn't.
I am trying to debug a C executable compiled for arm64 on an Apple M1 MacBook Pro, running macOS Monterey. However, when I try to run the program inlldb, I receive the following error: ``` (lldb) run error: process exited with status -1 (attach failed ((os/kern) invalid argument)) ```
To debug an arm64 executable on a system running Rosetta, you need to explicitly runlldbwithin the arm64 architecture. To do this: ``` arch -arm64 lldb ./your-program ```
Is a function without a storage class specified in its declaration and definition : ``` void func(void); // declaration void func(void) { // implementation } ``` be equivalent to the function with extern storage class in its declaration and definition? : ``` extern void func(void); // declaration extern void func(void) { // implementation } ```
From the C Standard (6.2.2 Linkages of identifiers) 5 If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.
how can i solve this warning? Code: ``` void socket_dontroute(socket_t s) { int set; if (setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (const char *) &set, sizeof(int)) < 0) { sys_err("setsockopt: dontroute: %s", strerror(errno)); socket_close(s); return; } } ``` int set; I know it's because of the statement, but I don't know how to solve it.
You are passingsetas a pointer tosetsockopt, but are only declaring the variable and not initializing it. That means that the content of set could be anything that is present at its memory address, and the compiler is warning you of it. As the comments rightfully stated, choose a value for set according to your functions requirement.
I am new to C and would like to create a N x N matrix of zeros (i.e., every element is zero). N is an integer. Using MATLAB I managed to generate such an array using the code:Array = zeros(N); However, in C, how would we generate such an array with minimal lines of code? Thanks in advance.
Just write ``` T matrix[N][N] = { 0 }; ``` whereTis some type specifier as for exampleint. Such an initialization is allowed if N is an integer constant expression. Otherwise you need to write ``` #include <string.h> //... T matrix[N][N]; memset( matrix, 0, sizeof( matrix ) ); ```
As far as I understand when we includestdio.hthe entire file is copied into the text of our program.(basically we prepend it) Then when we do a function call forprintf()why does it have to be linked first? Is it thatstdio.hcontains just the definitions of those functions and the compiler finds the compiled executable object file for the function that we invoke for exampleprintf(). I've read about this in a few places but still kinda not clear.
Header files like stdio.h generally just contain a declaration that defines the name of the function, the types of its arguments, and its return value. This is enough for the compiler to generate calls to the function, but it is not a definition. The actual code that implements the function is going to be in a library (with an extension like.aor.oor.lib).
I was testing some C code and ran into an error that threw me for a loop. I ended up creating the following code as a test and the results surprised me. It appears as though the ~ operator is somehow changing the interpretation of the value (i.e. Its type), because unless type casted the test fails. Any insight as to what is going on is appreciated. Code: ``` int main() { unsigned short one=1, two=1, three=1; one=~one; printf("One: %hu Two: %hu\n",one,two); printf("Test: %s\n",(one==~three)? "Pass": "Fail"); printf("Test: %s\n",(one==(unsigned short)~three)? "Pass": "Fail"); printf("Test: %s\n",(one==~(unsigned short)three)? "Pass": "Fail"); return 0; } ``` Output: ``` One: 65534 Two: 1 Test: Fail Test: Pass Test: Fail ```
``` unsigned int one = 1; ~one; // This expression has type int. So it's likely to be 0xFFFFFFFE ```
I have a very simple programprog.c: ``` int main(int argc, char ** argv) { char * file_path = argv[2]; FILE * fp = fopen(file_path, "-rb"); if (fp == NULL) { perror("\nerror"); } } ``` I compile the program withgcc -o prog prog.c -lrtand run with./prog --file Tiny.txt andprogandTiny.txtare both directly under thesrcdirectory (both are at the same level). I cannot see whyfopenis giving me an invalid argument error. I am running on Ubuntu 20.04.3
Sorry, I just realized I used a-in-rb. It should simply berb.
I get this error: format specifies type 'int' but the argument has type 'int *' [-Werror,-Wformat] ``` #include <stdio.h> int main(void) { int arr[5] = {0}; for(int i = 1; i < 5; i++) { arr[i] = i + 1; } printf("%i", arr); } ```
In C, whenever you pass an array to a function, only a pointer to the first element of said array is passed into the function (this is called"array to pointer decay"). In order to print every element inside an array, you have to access every single one of them and print them individually, using the[]operator. Like this: ``` for(int i = 0; i < 5; i++){ printf("%i", arr[i]); } ``` Also, remember that arrays are 0 based, meaningarr[0]is the first element, butarr[5]is not a valid element, as it's out of bounds.
I just started with C, i cant find out how to print all values from an array with for loop, wether it is array of strings or integers? ``` #include <stdio.h> #include <string.h> int main() { int array[3][20] = {10, 15, 20}; for (int i = 0; i < array; i++) { printf("%d", array[i]); } return 0; } ``` What mistake do i make here?
Since you have a 2-dimensional array, you should use nested loops for each dimension, and access the elements using 2 indexes. To get the number of elements in an array usesizeof array / sizeof array[0]. ``` for (int i = 0; i < sizeof array / sizeof array[0]; i++) { for (int j = 0; j < sizeof array[i] / sizeof array[i][0]; j++) { printf("%d ", array[i][j]); } printf("\n"); } ```
I'm trying to create a counter that counts the amount of characters in a string before "?". I have issues with using strcmp to terminate the while-loop and end up with a segmentation fault. Here's what I have: ``` void printAmount(const char *s) { int i = 0; while ( strcmp(&s[i], "?") != 0 ) { i++; } printf("%i", i); } ```
Don't usestrcmpfor this. Just use the subscript operator onsdirectly. Example: ``` #include <stdio.h> void printAmount(const char *s) { int i = 0; while (s[i] != '?' && s[i] != '\0') { i++; } printf("%d", i); } int main() { printAmount("Hello?world"); // prints 5 } ``` Or usestrchr ``` #include <string.h> void printAmount(const char *s) { char *f = strchr(s, '?'); if (f) { printf("%td", f - s); } } ```
#include "stdio.h"#include "file_created_by_me.h" In the first include there is a library file, in the second include there is a header file, or both can be called as libraries or headers because library and header are synonymous?
Both are header files. The first header file provides declarations of some of the functions provided by the C standard library. Therefore, one could say that it is part of the C standard library. The second header file probably provides declarations of functions that are defined in other parts of your program. Therefore, it is not part of alibrary. A library generally provides header files so that you can#includethem in your program, so that thecompilerhas the necessary function declarations in order to call the functions in the library. However, the main part of the library, which consists of the actual function definitions, is not imported by the compiler, but rather by thelinker.
#include "stdio.h"#include "file_created_by_me.h" In the first include there is a library file, in the second include there is a header file, or both can be called as libraries or headers because library and header are synonymous?
Both are header files. The first header file provides declarations of some of the functions provided by the C standard library. Therefore, one could say that it is part of the C standard library. The second header file probably provides declarations of functions that are defined in other parts of your program. Therefore, it is not part of alibrary. A library generally provides header files so that you can#includethem in your program, so that thecompilerhas the necessary function declarations in order to call the functions in the library. However, the main part of the library, which consists of the actual function definitions, is not imported by the compiler, but rather by thelinker.
I faced a wired problem, it is a big and commercial project so I can't put the original code here. but the logic is like this: ``` struct sample_t { int inta; int * p_intb; }; sample_t sample ={0}; sample.inta = 0; sample.p_intb = NULL; // crashed, why? ``` run into crash due to the pointer operation, but forintathere was no problem. however, if I usememset(&sample.p_intb, 0, 4)to replace above equal, it worked. What is the reason of this? How to solve this problem? This is a screenshot of the code
this problem was caused by pointer start address(must be times of 4) I am not sure about the exact reason, but should be related to the chip (ecu).
To write into a log file, some pointer list (in C language), i would like to convert my int * into a character array before to write it, in the log file. I know that to convert a decimal to a char buffer we could use something like below but my values could be higher than 9 and this didn't work for that. ``` int data = 5; char cData = data + '0'; ``` Have you any solutions ? Best Regards.
Well, you can't store a decimal more than 9 in achar. I would recommend you to use achar arrayto store decimal greater than 9 usingsprintf()defined in<stdlib.h>like this. ``` int data = 224; char arr[10]; sprintf(arr, "%d", data); ```
I am making a emacs mode for my own language, and my language has python like comments, example ``` func hello_world() printh("Hello, World") # this prints hello world end ``` In this example, I want everything that is after the # to change in color, like a comment. right now, I am able to figure out how to do c/c++ type of comment highlighting in emacs, but I am not able to understand how to do for python type of comments ``` // this comment will be highlighted # but I want this type of comment to be highlighted ```
Use the following in your syntax highlighting definition: ``` ("#.*" . font-lock-comment-face) ```
I have searched online, but I haven't found anything because I don't know the correct keywords to express what I need. I am in a thebuild/directory of a repository; if I runccmake ../there is a list of "flags (?)" that I can turn ON/OFF in order to decide what stuff do I want to build. If I want to turn ON the BUILD_THIS: ``` ccmake ../ #press Enter to turn that flag ON #press c to configure #press e to exit #press g to generate cmake --build . --target install ``` I am in a computer that has only cmake, and no ccmake. How can I do the same with cmake? Turn ON/OFF these flags, configure, and generate?
ccmakeis a graphical interface around cmake. With access to command line, you just type what options you want to set. You do not need to have ccmake. ``` cmake ../ -DBUILD_THIS=ON ```
Can someone explain how i can define this array of strings? ais a pointer and its points to a array of chars. So it has to bechar *a[3]?
The array is defined as an array of pointers to string literals like ``` char * a[3] = { "A", "B", "C" }; ``` where instead of "A", "B", "C" you can use your own string literals. To declare a pointer to the first element of such an array you can write ``` char **p = a; ``` Here is a demonstration program. ``` #include <stdio.h> int main( void ) { char * a[] = { "A", "B", "C" }; const size_t N = sizeof( a ) / sizeof( *a ); char **p = a; for ( size_t i = 0; i < N; i++ ) { printf( "%s ", a[i] ); } putchar( '\n' ); for ( size_t i = 0; i < N; i++ ) { printf( "%s ", p[i] ); } putchar( '\n' ); } ```
``` #include <stdio.h> int main() { printf("%d", "123456"[1]); return 0; } ``` The expected output is 123456, but it actually outputs 50. Why is that?
"123456"[1]gives the character'2'. That character's ascii value is50. To print the full number do:printf ("%d", 123456);orprintf ("%s", "123456");
I am trying to remove a route in Contiki if attack is detected. I am usingstruct route_entry *e; route_remove(e); But I am getting the following error:undefined reference to 'route_remove'.
route_removeis a Rime network stack function. By default, Contiki is built with uIP (IPv6) network stack, which does not have this function. To remove a route when the IPv6 network stack is used,call this function: void uip_ds6_route_rm (uip_ds6_route_t *route).
I have been coding in English so far but now it is necessary to code in my native language which is Estonian. We have letters like Õ, Ä, Ö and Ü but VS code does not seem to like them that much. Here is an example code and also output: ``` #include <stdio.h> int main() { printf("Tegu on sõna äraarvamise mänguga\n"); } ``` The output would in my case be: ``` Tegu on s├Ána ├ñraarvamise m├ñnguga ``` What can I do to fix this?
There actually was a super easy fix for this... ``` #include <windows.h> SetConsoleOutputCP(65001); //Set console encoding to utf8 ``` Using the next code you can find out what is the encoding of your console and if it is wrong then it can be changed with SetConsoleOutputCP(.....): ``` #include <windows.h> unsigned cp = GetConsoleOutputCP(); ``` And it needs to be matched - mine was not :)
I have been coding in English so far but now it is necessary to code in my native language which is Estonian. We have letters like Õ, Ä, Ö and Ü but VS code does not seem to like them that much. Here is an example code and also output: ``` #include <stdio.h> int main() { printf("Tegu on sõna äraarvamise mänguga\n"); } ``` The output would in my case be: ``` Tegu on s├Ána ├ñraarvamise m├ñnguga ``` What can I do to fix this?
There actually was a super easy fix for this... ``` #include <windows.h> SetConsoleOutputCP(65001); //Set console encoding to utf8 ``` Using the next code you can find out what is the encoding of your console and if it is wrong then it can be changed with SetConsoleOutputCP(.....): ``` #include <windows.h> unsigned cp = GetConsoleOutputCP(); ``` And it needs to be matched - mine was not :)
I'm trying to use switch case with char[2] in C, but it only supports integers. ``` int main() { char c[2] = "h"; switch (c) { case "h": printf("done!"); } return 1; } ``` For better understanding, what I'm trying to do is: ``` if "h" in ")($+#&@+)#" ``` Basically I want to make a condition that matches a character with a group of characters,but efficiently, the first thing that came to mind is to use switch case but it only supports int. But when I use(int)cwhich is recommended in other stackoverflow answers, it doesn't return the ascii value.
Using the switch statement in this case does not make a sense. Just use the standard functionstrchrdeclared in<string.h>. ``` #include <string.h> //... if ( strchr( c, 'h' ) != NULL ) puts( "done!" ); ```
I'm having some trouble making a print statement that includes quotes and a new line escape sequence. I tried to use \n for a new line and backslash before open quote and before closing quotes to tell my program to include the quotations. I don't know where I went wrong and I keep getting an error in my int main(void) line (sorry if I'm not using correct terminology, I'm in an intro c MOOC). ``` #include <stdio.h> int main(void){ printf("Dennis Ritchie said:\n\"The only way to learn a new programming language is by writing programs in it.\"); return 0; } ```
You're only missing closing"and\nfor readability: ``` printf("Dennis Ritchie said:\n\"The only way to learn a new programming language is by writing programs in it.\"\n"); ```
Code snippet ``` ```c #include <stdio.h> int main(void) { short int a; scanf("%hd", &a); while (a != 5) { printf("%hd\n", a); a++; } return 0; } ``` The output of this code is: Code snippet ``` 1 1 2 3 4 ``` I am expecting the output to be: Code snippet ``` 1 2 3 4 5 ``` But why is the output different from what I am expecting? I have tried the following: I have checked the syntax of the code. It is correct.I have run the code on different compilers. The output is the same on all compilers.I have tried different values fora. The output is the same for all values ofa.
I think the first "1" is your input.I tried to run the same code and that is what I observed the first "1" is the input I gave and then the code prints from 1 to 4.
Code snippet ``` ```c #include <stdio.h> int main(void) { short int a; scanf("%hd", &a); while (a != 5) { printf("%hd\n", a); a++; } return 0; } ``` The output of this code is: Code snippet ``` 1 1 2 3 4 ``` I am expecting the output to be: Code snippet ``` 1 2 3 4 5 ``` But why is the output different from what I am expecting? I have tried the following: I have checked the syntax of the code. It is correct.I have run the code on different compilers. The output is the same on all compilers.I have tried different values fora. The output is the same for all values ofa.
I think the first "1" is your input.I tried to run the same code and that is what I observed the first "1" is the input I gave and then the code prints from 1 to 4.
Basically the title. I've been reading the manual pages and can't seem to make it work. Help would be much appreciated.
Usegetopt_long()for function names. A detailed explanation is givenhere. Thanks @Barmar for the suggestion!
I am currently planning a complicated networking project on Windows IoT Enterprise. Basically, I will have a C program keeping alive a special network interface. This C program should receive tasks in some way from other programs on the same host, which will generally be written in all sorts of languages (e.g. node.js). I have never did such cooperation between tasks. Do you have any advice on how a node.js server can pass information to an already running C program, and preferably receive a success code or an error message? It is very important for me that this process is as fast as possible, as this solution will handle multiple thousand requests per second.
In one of the comments I was pointed towards zeroMQ, and I am now using it successfully in my application, thank you for the help!
I heard that '%d' prints decimal, but if I import printf("%d",'a'), it prints out a ASCII code of 'a'. I cannot understand why %d which only can print out decimal also prints ASCII code. is ASCII code a decimal?
Computers do not know anything about "decimals". Compueters knownumbers. Generally everything is a number in computers. Characters, strings - even machine code instructions. Humans need numbers to be displayed in an understandable form. We are used to use base 10 numbers called by you "decimals". Characters are numbers too. We (humans) have invented encodings to know what number represents a particular character. Very popular is ASCII system. When youprintf("%d\n", 'A');then you simple print number representing character'A'using the base 10 representation.
I am currently planning a complicated networking project on Windows IoT Enterprise. Basically, I will have a C program keeping alive a special network interface. This C program should receive tasks in some way from other programs on the same host, which will generally be written in all sorts of languages (e.g. node.js). I have never did such cooperation between tasks. Do you have any advice on how a node.js server can pass information to an already running C program, and preferably receive a success code or an error message? It is very important for me that this process is as fast as possible, as this solution will handle multiple thousand requests per second.
In one of the comments I was pointed towards zeroMQ, and I am now using it successfully in my application, thank you for the help!
I heard that '%d' prints decimal, but if I import printf("%d",'a'), it prints out a ASCII code of 'a'. I cannot understand why %d which only can print out decimal also prints ASCII code. is ASCII code a decimal?
Computers do not know anything about "decimals". Compueters knownumbers. Generally everything is a number in computers. Characters, strings - even machine code instructions. Humans need numbers to be displayed in an understandable form. We are used to use base 10 numbers called by you "decimals". Characters are numbers too. We (humans) have invented encodings to know what number represents a particular character. Very popular is ASCII system. When youprintf("%d\n", 'A');then you simple print number representing character'A'using the base 10 representation.
My code shows me a wrong output by showing the area to be zero: ``` #include <stdio.h> double calc(float rad); void main(void) { float rad; printf("Enter the circle radius: \n"); scanf("%f",&rad); printf("You entered: %f\n",rad); printf("Area is %d\n",calc(rad)); if(calc(rad)>1000){ printf("Area is > 1000"); } else{ printf("Area is < 1000"); } } double calc(float rad){ double area=3.14*rad*rad; return area; } ``` Output: ``` Enter the circle radius : 20 you entered 20.000000 area is 0 area > 1000 ``` Desired output: ``` Enter the circle radius : 20 you entered 20.000000 area is 1256.000000 area > 1000 ```
The erroneous output is as a result of using%dinstead of%lffor double or%ffor float in yourprintfstatement. Turning on compiler warning-Wformatwill highlight this during compilation
for example I have generated a "zone" of 1s and 0s in a 2x2 2d array . But i need to store 9 of these zones to access whenever from another 3x3 2d array "map". The zone arrays are randomly generated and need to stay the same once added to the 2d map array, so that I could "leave" a zone and come back and itd be the same. Kinda like an ASCII game such that ``` int zone[2][2]; // fill zone array int map[3][3]; map[0][0] = zone; ```
I think to make it simple you can usestructin c. It will be easier to manage and modify it withstruct ``` #include <stdio.h> struct Zone { int zone[2][2]; }; int main() { struct Zone map[3][3]; struct Zone zone1; int i, j; for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { zone1.zone[i][j] = i + j; // putting some values for example } } map[0][0] = zone1; } ```
I have a C program that output values to stdout from measure. I useprintfto display them and the format allows me to change the precision ``` printf("Scan=%d S_0=%.5f S_1=%.5f S_2=%.5f S_3=%.5f", scanId, S0, S1, S2, S3); ``` My issue is that I have a lot of printing like this one and if I want to change the precision quickly I have to get on each one and change it. I was wondering if it was possible to use something like a#defineto have it on a precise location and it will apply on eachprintfat compilation. I know it is not possible easily without recompile but I'm ok with that. I know something similar as I ask here in python is: ``` f"{s_0:.{prec}f}" ```
One way would be to do a#define(as you guessed) like this: ``` #define PFLT "%.5f" printf("Scan=%d S_0=" PFLT " S_1=" PFLT " S_2=" PFLT " S_3=" PFLT, scanId, S0, S1, S2, S3); ``` Then to change the precision you just need to alter the#defineand recompile.
``` #include <stdio.h> int main() { int i = 1024; for (; i; i >>= 1) printf("Hi"); return 0; } ``` Why does the for loop print Hi 11 times? I don't understand.
The expressioni >>= 1is equivalent toi = i / 2 So if initiallyiis equal to1024then the body of the loop will be executed for the values ``` 1024 512 256 128 64 32 16 8 4 2 1 ``` that is 11 times. The value of the expression1 / 2is equal to0due to the integer arithmetic. You could check that by changing the call of printf like ``` #include <stdio.h> int main( void ) { int i = 1024; for (; i; i >>= 1) printf( "%d ", i ); putchar( '\n' ); } ```
Basically, I want to write a program that shows in a small window the color of the pixel currently pointed by the mouse cursor. Of course, I could poll the mouse cursor position once in a while, but I would like to opt to a mechanism that calls my code when the mouse cursor has moved, regardless whether it's pointing the current window or not. Is there some WinAPI trickery that could achieve that functionality?
After some search, I found this: ``` HHOOK mouseHook = SetWindowsHookExA( WH_MOUSE_LL, LowLevelMouseProc, hInstance, 0); ... LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) { if (wParam == WM_MOUSEMOVE) { // Notify me. } return 0; } ```
I am playing ebpf code and got a sample like so: ``` int tc_ingress(struct __sk_buff *skb) { void *data = (void *)(long)skb->data; struct ethhdr *eth = data, eth_copy; # what is this line doing? } ``` AS I am new to C and kernel, got stuck on many smaller things. Can some tell me what is this line mean? ``` struct ethhdr *eth = data, eth_copy; ```
``` struct ethhdr *eth = data, eth_copy; ``` Is nothing special, it is a more compact version of ``` struct ethhdr *eth = data; struct ethhdr *eth_copy; ``` So we declare two variables of the same type, but we initialize just the first one.
I am playing ebpf code and got a sample like so: ``` int tc_ingress(struct __sk_buff *skb) { void *data = (void *)(long)skb->data; struct ethhdr *eth = data, eth_copy; # what is this line doing? } ``` AS I am new to C and kernel, got stuck on many smaller things. Can some tell me what is this line mean? ``` struct ethhdr *eth = data, eth_copy; ```
``` struct ethhdr *eth = data, eth_copy; ``` Is nothing special, it is a more compact version of ``` struct ethhdr *eth = data; struct ethhdr *eth_copy; ``` So we declare two variables of the same type, but we initialize just the first one.
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closedlast year. I wrote this text code ``` int b=5; int main() { b=b++; printf("b = %d\n",b); return 0; } ``` and I expected it to print "b = 6"; however, the result is "b = 5", i.e. b is not incremented. I know b=b++ is not a good practice but just to understand it, can anyone explain why it is not incrementing b please? What am I missing?
b++means incrementing the value after it is used so for your case it should be++b. When b is incrementing to 6 byb++it is overwritten by assignment ofbwhen it is 5. Just write it ``` int b=5; int main() { // b=b++; b++; // or ++b; printf("b = %d\n",b); return 0; } ```
I want to initialize an array of strings such that the object is the type **char. I know that I can do this via: ``` char **my_array = malloc( 3 * sizeof(char*)); for (int i = 0; i < (3); i++) { my_array[i] = malloc(10 * sizeof(char)); } sprintf(my_array[0], "first"); sprintf(my_array[1], "second"); sprintf(my_array[2], "third"); ``` But it seems really cumbersome, especially because the strings are set before I compile. Is there a way to get (specifically a char ** type) with syntax more like: ``` char ** my_array = {"first", "second", "third"}; ``` So that I have the property:printf(my_array[0]);returnsfirst?
Assuming the strings are fixed, you want an array ofconst char *: ``` const char *my_array[] = {"first", "second", "third"}; ```
What is the meaning of the first line in the functionsecret? What is the output ofreturn secret(3,argv)? ``` #include <stdio.h> int secret(int argc, char **argv) { *argv && secret(0, argv + 1) && argc == 0 && printf("%s\n", *argv); return argc == 0; } int main() { char *argv[] = {"hello", "XYZ", "123", "ABC", NULL}; return (secret(3,argv)); } ```
This ``` *argv && secret(0, argv + 1) && argc == 0 && printf("%s\n", *argv); ``` is a tricky (and harder to read, I think) way to write ``` if ( *argv && secret(0, argv + 1) && argc == 0 ) { printf("%s\n", *argv); } ```
I'm trying to pass something like this to a string but it does not work. I don't understand very well this function so I was hoping someone would explain to me what I'm doing wrong. ``` strcat(string,("%d;%d;%d;%d;%d;%s;%s;%s;%s;%s", x->n1, x->n2, x->n3, x->n4, x->n5, x->s1, x->s2, x->s3, x->s4, x->s5, x->s6)); ```
It seems what you are trying to do is the following ``` sprintf( string + strlen( string ), "%d;%d;%d;%d;%d;%s;%s;%s;%s;%s", x->n1, x->n2, x->n3, x->n4, x->n5, x->s1, x->s2, x->s3, x->s4, x->s5 ); ``` Also instead ofsprintfyou can usesnprintfthat is safer. The character arraystringmust contain a (possibly empty) string and be large enough to accommodate appended strings.
In the functionread, I need to access the values of integeraand integerbfrom themainfunction without declaring them in the prototype of the functionread, using pointers. Pointerxshould point to integera, and pointeryshould point to integerb. ``` #include <stdio.h> void read(int zzz[], int n) { int *arr = zzz, *x=a,*y=b; } int main() { int a, b; scanf("%d", &a); scanf("%d", &b); return 0; } ``` How this could be implemented?
There are two ways that thereadfunction can read the values or addresses ofaandb: Pass them as parametersMakeaandbglobal So if you don't want to make them parameters, you need to move them outside of themainfunction and before thereadfunction. Also,readis the name of a system function, so you should name it something else so you don't conflict with it.
This function replaces values ​​of two integer variables using two pointers. I need to make function which will make p1 point to b and p2 point to a. ``` #include <stdio.h> void swap(int *p1, int *p2) { int temp = *p1; *p1 = *p2; *p2 = temp; } int main() { int a, b; scanf("%d %d", &a, &b); swap(&a, &b); printf("%d, %d", a, b); return 0; } ``` How could I modify this to make p1 point on b, and p2 point on a?
It seems you mean something like the following ``` #include <stdio.h> void swap(int **p1, int **p2) { int *temp = *p1; *p1 = *p2; *p2 = temp; } int main() { int a, b; scanf("%d %d", &a, &b); int *p1 = &a; int *p2 = &b; printf("%d, %d\n", *p1, *p2); swap(&p1, &p2); printf("%d, %d\n", *p1, *p2); return 0; } ```
This is not strictly a programming question but more of a design question. Working with some strucs from the WinAPI I noticed that many of them contain a field calleddwSizethat simpally stores their size e.gTHREADENTRY32orBLUETOOTH_DEVICE_SEARCH_PARAMS ``` typedef struct tagTHREADENTRY32 { DWORD dwSize; DWORD cntUsage; DWORD th32ThreadID; DWORD th32OwnerProcessID; LONG tpBasePri; LONG tpDeltaPri; DWORD dwFlags; } THREADENTRY32; ``` Thinking about this design i find it intriguing why can't the code that using those structures usesizeof? What is the actual thinking behind this?
This is to support future versions of that structure that might have new fields added to it.
How do I read in theEnterkey as an input in C? I'd like some program like this: ``` "Please enter a key to go to next line" ``` How do I add this type of option in C? I am new to programming.
You can use thegetcfunction instdio.hto wait until a key is pressed. This C code will wait for the enter key to be pressed then output "Continued!": ``` #include <stdio.h> int main(){ printf("Press any key to continue"); getc(stdin); printf("Continued!"); return 0; } ```
Currently if I writeint * ptr;then auto-formatting would convert it toint* ptr;which I don't want. After googling a bit, I foundherethe fix for that. I have to usePointerAlignment: PAS_Middle. But I don't know where to add that. In vscode settings, I tried to add it inC_Cpp: Clang_format_fallback_styleandC_Cpp: Clang_format_style. Neither didn't work. There was no save/apply button in settings, so I hope it would automatically update settings as soon as change it. But nonetheless, whenever I format my C code using Shift+Alt+F, it puts asterisk near to the type!
I solved it in this way: Tools > Options > Text Editor > C/C++ > Code Style > Formatting > Spacing. At the end of the list from the right window there is a "Pointer/reference alignment" section, select there the option you like.
Currently if I writeint * ptr;then auto-formatting would convert it toint* ptr;which I don't want. After googling a bit, I foundherethe fix for that. I have to usePointerAlignment: PAS_Middle. But I don't know where to add that. In vscode settings, I tried to add it inC_Cpp: Clang_format_fallback_styleandC_Cpp: Clang_format_style. Neither didn't work. There was no save/apply button in settings, so I hope it would automatically update settings as soon as change it. But nonetheless, whenever I format my C code using Shift+Alt+F, it puts asterisk near to the type!
I solved it in this way: Tools > Options > Text Editor > C/C++ > Code Style > Formatting > Spacing. At the end of the list from the right window there is a "Pointer/reference alignment" section, select there the option you like.
I am developing on an ARM Cortex M3. My IDE generates a C source file which includes an ISR vector table written in C as a struct of function pointers for ISR. By default they all have a weak alias which is the default hander. I want to override the weak alias with an ASM function. Can I do this? I don't want to mess with the premade table, I just want to provide an ASM function to fill the name instead of using a C function, so load the ASM functions address of a given name.
Sure, just write the functions in assembly using the same symbol as the desired ISR. When a global symbol with the same name as a weak symbol exists, it replaces the weak symbol.
When I print a string withprintflike in the following: ``` #include <stdio.h> void main(void) { printf("Foo"); } ``` In the output, I get the following: As seen in this picture, there is a highlighted percent sign placed after the output ofprintf. What's causing this? How do I get rid of it?
That's your shell's prompt. You're not printing a newline after the string "Foo", so the prompt appears immediately after it. Add a newline to the string to print so the shell prompt appears on a separate line. ``` printf("Foo\n"); ```
I need to explain for the MACRO define and if else conditions. When I using the below function I get CHANGE value to 5 ``` #include <stdio.h> #define CHANGE var int var; int main() { var = 5; printf("%d",CHANGE); } ``` Output:5 But if I use like this: ``` #include <stdio.h> #define CHANGABLE_VALUE var int var; int main() { var = 5; #if CHANGABLE_VALUE == 5 printf("%d",CHANGABLE_VALUE); #else printf("There is no value"); #endif } ``` Output:There is no value Why the #if statements not working ?
Preprocessor definitions (akaMacros) are resolved duringpre-compilationtime, not during compilation time, and most certainly not during runtime, which seems to be what you're expecting. Hence#if CHANGABLE_VALUE == 5is replaced with#if var == 5and then resolved as something which is false, so the actual code inside it is not even compiled (let alone executed).
``` #include <stdio.h> int main() { int num1; int *p; p=&num1; printf("Give a value\n"); scanf("%d", &num1); printf("\n%d", num1); f2(&num1); printf("%d", *p); return 0; } void f2(int *p) { *p *= *p; } ``` A call by reference program just to return the square of a value Well, the problem is that if I do not use printf the expected output is correct (e.g. 2*2=4) However, if I include: ``` printf("\n%d", num1); ``` and run the programm I will take a non expected value (e.g. 2*2=24)
These two calls of printf result of outputting two values in the same line without a space. ``` printf("\n%d", num1); f2(&num1); printf("%d", *p); ``` If you want to make the output less confusing then for example write ``` printf("\n%d", num1); f2(&num1); printf("\n%d\n", *p); ```
The following code snippet causes the code to bail out prematurely. My question is why my system still showsProgram finished with exit code 0. ``` #include <stdio.h> int main(void) { int divisor = 0; int dividend = 0; int quotient = 0; printf("BEGIN\n"); quotient = dividend / divisor; printf("END\n"); // This statement does not execute return 0; } ```
This isundefined behavior. The compiler is free to do whatever it feels is right in this situation, for example terminating with exit code 0.
The following code snippet causes the code to bail out prematurely. My question is why my system still showsProgram finished with exit code 0. ``` #include <stdio.h> int main(void) { int divisor = 0; int dividend = 0; int quotient = 0; printf("BEGIN\n"); quotient = dividend / divisor; printf("END\n"); // This statement does not execute return 0; } ```
This isundefined behavior. The compiler is free to do whatever it feels is right in this situation, for example terminating with exit code 0.
I am trying to swap 2 values in a matrix - the value in the 1st row, 2nd column(5)and the value in the 4th row, 3rd column(2). Once compiled, the program terminates due to a segmentation error when I try to assign the value of*temp. I have the code attached below. ``` void swap(float *y) { float *temp; *temp=*(y+1); *(y+1)=*(y+11); *(y+11)=*temp; } void main() { float a[5][3]={{7,5,4},{2,7,4},{7,5,2},{8,4,2},{9,5,2}}, *aptr=&a[0][0]; swap(aptr); } ``` I am sorry for any glaring mistakes in my code, I am new to C and I'm trying to grasp the concept of pointers.
The pointer temp is uninitialized. So dereferencing the pointer results in undefined behavior. Instead you need to use an object of the type float. ``` void swap(float *y) { float temp; temp=*(y+1); *(y+1)=*(y+11); *(y+11)=temp; } ```
Hey I am kinda new to C and I wanted to ask why this prints out4instead of260? ``` #include <stdio.h> int main() { unsigned char x = 130; x *= 2; printf("%d\n", x); } ```
The*=operator is calledmultiplication assignment operatorand is shorthand for multiplying the operand to the left with the operand to the right and assigning the result to the operand to the left. In this case, it's the same as: ``` x = x * 2; ``` Hereinteger promotionfirst takes place and the result ofx * 2is indeed260. However, anunsigned charcan usually only carry values between 0 and 255 (inclusive) so the result overflows (wraps around) when you try assigning values above 255 and 260 % 256 == 4.
I am trying to swap 2 values in a matrix - the value in the 1st row, 2nd column(5)and the value in the 4th row, 3rd column(2). Once compiled, the program terminates due to a segmentation error when I try to assign the value of*temp. I have the code attached below. ``` void swap(float *y) { float *temp; *temp=*(y+1); *(y+1)=*(y+11); *(y+11)=*temp; } void main() { float a[5][3]={{7,5,4},{2,7,4},{7,5,2},{8,4,2},{9,5,2}}, *aptr=&a[0][0]; swap(aptr); } ``` I am sorry for any glaring mistakes in my code, I am new to C and I'm trying to grasp the concept of pointers.
The pointer temp is uninitialized. So dereferencing the pointer results in undefined behavior. Instead you need to use an object of the type float. ``` void swap(float *y) { float temp; temp=*(y+1); *(y+1)=*(y+11); *(y+11)=temp; } ```
Hey I am kinda new to C and I wanted to ask why this prints out4instead of260? ``` #include <stdio.h> int main() { unsigned char x = 130; x *= 2; printf("%d\n", x); } ```
The*=operator is calledmultiplication assignment operatorand is shorthand for multiplying the operand to the left with the operand to the right and assigning the result to the operand to the left. In this case, it's the same as: ``` x = x * 2; ``` Hereinteger promotionfirst takes place and the result ofx * 2is indeed260. However, anunsigned charcan usually only carry values between 0 and 255 (inclusive) so the result overflows (wraps around) when you try assigning values above 255 and 260 % 256 == 4.
How does the bitwise operator compare the binary? ``` long num1 = 22; //00010110 long num2 = 21; //00010101 if ((num1 ^ num2) == 0) { printf("its equal\n"); printf("%li\n", num1); printf("%li\n", num2); } else { printf("not equal\n"); } //$> not equal ``` Does^XOR operator do a for loop for each bit?
It really depends on the implementation but most processors have aXOR(akaEOR) instruction. Even 8-bit CPUs have one. So no it doesn't loop on each bit at compiler level. Machine code instructions can process all bits in one call (also true for bitwiseor,andandnotoperators). The compilercouldhave to create a loop if the data type is wider than the register type though (if 32 bit register machine is processing 64 bit integers for instance 2 calls toXORinstruction will be issued, probably not worth a loop though)
In the code attached, how do I modify it to remove Remove the trailing '+' signs. ``` int i,j,sum; sum=1; for(i=2; i<=10; i++) { for(j=1; j<(i+1); j++) { sum = sum + 1; printf("%d + ",j); } printf(" = %d", sum); printf("\n"); } return EXIT_SUCCESS; ``` } Here is the output: ``` 1 + 2 + = 3 1 + 2 + 3 + = 6 1 + 2 + 3 + 4 + = 10 1 + 2 + 3 + 4 + 5 + = 15 1 + 2 + 3 + 4 + 5 + 6 + = 21 1 + 2 + 3 + 4 + 5 + 6 + 7 + = 28 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + = 36 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + = 45 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + = 55 ```
For example you can do it the following way ``` for(j=1; j<(i+1); j++) { sum = sum + 1; if ( j != 1 ) printf( " + " ); printf("%d",j); } ```
I'm trying to make a makefile that doesn't recompile my program if I delete my object files...because my .c files are up to date, how can I do this? I try to do this but it doesn't work ``` SRC = main.c file.c file1.c OBJ = $(SRC:c=o) %.o: %.c gcc -c $< -o $@ name = program all: $(NAME) $(NAME): $(SRC) ; $(OBJ) gcc $(OBJ) -o $(NAME) ```
Thank! To solve my problem i'm must add special target .INTERMEDIATE or .SECONDARY like this: More details on this issue can be found at the linkChains of Implicit Rulesprovided by Henry. ``` SRC = main.c file.c file1.c OBJ = $(SRC:c=o) %.o: %.c gcc -c $< -o $@ NAME = program all: $(NAME) $(NAME): $(SRC) ; $(OBJ) gcc $(OBJ) -o $(NAME) .SECONDARY: $(OBJ) ```
This question already has answers here:C macros and use of arguments in parentheses(2 answers)Closedlast year. Why doesn't the code below print 16 ,0? ``` #define SUM 1+3 int main(void) { printf("%d %d\n", SUM*SUM, 4-SUM); return 0; } ```
Because c treats that like x+y, not the result of that addition. (if you want it to treat it like the result, simply put parentheses before and after the expression) ``` #define SUM (1+3) int main() { printf("%d %d\n", SUM*SUM, 4-SUM); return 0; } ```
In C you can declare a variable that points to an array like this: ``` int int_arr[4] = {1,2,3,4}; int (*ptr_to_arr)[4] = &int_arr; ``` Although practically it is the same as just declaring a pointer to int: ``` int *ptr_to_arr2 = int_arr; ``` But syntactically it is something different. Now, how would a function look like, that returns such a pointer to an array (of int e.g.) ?
A declaration ofintisint foo;. A declaration of an array of 4intisint foo[4];. A declaration of a pointer to an array of 4intisint (*foo)[4];. A declaration of a function returning a pointer to an array of 4intisint (*foo())[4];. The()may be filled in with parameter declarations.
I'm a bit lost, how can I convert the output ofsys_inf.uptime(seconds) into days? ``` #include <stdio.h> #include <sys/sysinfo.h> int main(void) { struct sysinfo sys_inf; // for system information sysinfo(&sys_inf); // to get system information int days = sys_inf.uptime; float totalDays = days / 86400; printf("Latest reboot was : %.2ld seconds ago (%.2f)", sys_inf.uptime, totalDays); return 0; } ```
You're doing integer division here: ``` int days = sys_inf.uptime; float totalDays = days / 86400; ``` Add.0to make it a floating point division: ``` int days = sys_inf.uptime; float totalDays = days / 86400.0; ```
I'm trying to make a makefile that doesn't recompile my program if I delete my object files...because my .c files are up to date, how can I do this? I try to do this but it doesn't work ``` SRC = main.c file.c file1.c OBJ = $(SRC:c=o) %.o: %.c gcc -c $< -o $@ name = program all: $(NAME) $(NAME): $(SRC) ; $(OBJ) gcc $(OBJ) -o $(NAME) ```
Thank! To solve my problem i'm must add special target .INTERMEDIATE or .SECONDARY like this: More details on this issue can be found at the linkChains of Implicit Rulesprovided by Henry. ``` SRC = main.c file.c file1.c OBJ = $(SRC:c=o) %.o: %.c gcc -c $< -o $@ NAME = program all: $(NAME) $(NAME): $(SRC) ; $(OBJ) gcc $(OBJ) -o $(NAME) .SECONDARY: $(OBJ) ```
This question already has answers here:C macros and use of arguments in parentheses(2 answers)Closedlast year. Why doesn't the code below print 16 ,0? ``` #define SUM 1+3 int main(void) { printf("%d %d\n", SUM*SUM, 4-SUM); return 0; } ```
Because c treats that like x+y, not the result of that addition. (if you want it to treat it like the result, simply put parentheses before and after the expression) ``` #define SUM (1+3) int main() { printf("%d %d\n", SUM*SUM, 4-SUM); return 0; } ```
In C you can declare a variable that points to an array like this: ``` int int_arr[4] = {1,2,3,4}; int (*ptr_to_arr)[4] = &int_arr; ``` Although practically it is the same as just declaring a pointer to int: ``` int *ptr_to_arr2 = int_arr; ``` But syntactically it is something different. Now, how would a function look like, that returns such a pointer to an array (of int e.g.) ?
A declaration ofintisint foo;. A declaration of an array of 4intisint foo[4];. A declaration of a pointer to an array of 4intisint (*foo)[4];. A declaration of a function returning a pointer to an array of 4intisint (*foo())[4];. The()may be filled in with parameter declarations.
I'm a bit lost, how can I convert the output ofsys_inf.uptime(seconds) into days? ``` #include <stdio.h> #include <sys/sysinfo.h> int main(void) { struct sysinfo sys_inf; // for system information sysinfo(&sys_inf); // to get system information int days = sys_inf.uptime; float totalDays = days / 86400; printf("Latest reboot was : %.2ld seconds ago (%.2f)", sys_inf.uptime, totalDays); return 0; } ```
You're doing integer division here: ``` int days = sys_inf.uptime; float totalDays = days / 86400; ``` Add.0to make it a floating point division: ``` int days = sys_inf.uptime; float totalDays = days / 86400.0; ```
I have a QT application written in C++, but at one point it makes a call to a function in a C library. I would like the C function to display to the output for debugging purposes. HoweverqDebug()can't be called in C. Is there an alternative toqDebug()that can be used in C? I've triedprintf()but it doesn't seem to display anything. ``` printf("Test output"); ``` IDE is QT Creator and I'd like the output to be displayed in the "Application Output" pane.
After callingprintf, add a call tofflush(stdout). That should fix the problem.
I've been trying to execute the "type" command with execve funtion in C ``` char *arg[] ={ "type", "type", NULL }; execvp("type", arg); ``` Here is the code that i've been using but it returns me -1 I've tried approximatively the same code for echo command , it working perfectly Any help please?
This is normal and expected behavior:typeis a shell builtin, not an external command; only external commands can be invoked withexecv-family syscalls. You could invoke a shell, and havethat shellruntype: ``` /* cmd should be the command you want to check 'type' output for */ char *args[] = { "bash", "-c", "type $@", "bash", cmd, NULL }; ``` ...or you could usewhichinstead (which is generally less capable, but the extra capabilitiestypeadds in bash are things that intrinsically require a shell).
I want to know if you can Allocate memory without using malloc or calloc, on a char pointer. as an example: ``` char *p; ``` and now i want to do this ``` *(p+1) = 'd' printf("%c", *(p+1)); ``` and the output is 'd'. i want this to work without malloc or calloc
You need to assign the pointer with the reference to the object of a suitable type and size. mallocreturns the reference to the suitable block of memory. You can also assign the statically (or automatically if used in the block context) allocated object. ``` char data[2]; char *p; /* ... */ p = data; *(p+1) = 'd' printf("%c", *(p+1)); ``` So basically the pointer has to reference the valid object.
How do I use fgets or getline if I don't have a stream but a file descriptor ? According to manpage offgets It is not advisable to mix calls to input functions from the stdio library with low-level calls to read(2) for the file descriptor associated with the input stream; the results will be undefined and very probably not what you want.
you can use read() function to read from file descriptor and it's very clear, from man page: read(int fd, void *buf, size_t count); read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.
I want to know if you can Allocate memory without using malloc or calloc, on a char pointer. as an example: ``` char *p; ``` and now i want to do this ``` *(p+1) = 'd' printf("%c", *(p+1)); ``` and the output is 'd'. i want this to work without malloc or calloc
You need to assign the pointer with the reference to the object of a suitable type and size. mallocreturns the reference to the suitable block of memory. You can also assign the statically (or automatically if used in the block context) allocated object. ``` char data[2]; char *p; /* ... */ p = data; *(p+1) = 'd' printf("%c", *(p+1)); ``` So basically the pointer has to reference the valid object.
How do I use fgets or getline if I don't have a stream but a file descriptor ? According to manpage offgets It is not advisable to mix calls to input functions from the stdio library with low-level calls to read(2) for the file descriptor associated with the input stream; the results will be undefined and very probably not what you want.
you can use read() function to read from file descriptor and it's very clear, from man page: read(int fd, void *buf, size_t count); read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.
I'm often using C code to take some input and manipulate it; for example, I want to scan a full phrase like "hello world" but as it contains a space, I find myself forced to use "gets" to include the spaces or even tabs sometimes.
you cant usescanf()orfgets, just remember use thestdinas input stream
I was playing with VS code settings (I wanted to explore VS Code) and suddenly the code editing got changed. Previously the code was more colourful and there were different colours for different keywords. Now my code is mostly white. Please help me to get back to default code formatting settings.
To revert the settings completely, open the settings JSON file by bringing up the command palette (Ctrl+Shift+P) and running the commandPreferences: Open Settings (JSON). Delete everything in there and save the file. However, you might just have switched to a different theme by accident. To check that, open the theme chooser (Ctrl+K,T) and try the other themes.