question
stringlengths
25
894
answer
stringlengths
4
863
I am working on a project where half my code is in c and half is in c++. Now I want to include the cprogram.c in my cppprogram.cpp. When including a c file inside a c program you can use ``` #include "cprogram.c" ``` Anyways to do that in c++ for including a c program.
Besides from that you normallydon't include.cfiles, but.hfiles instead, and that the following isbad practice, you can include C files into.cpp/.hppfiles by wrapping the include into anextern "C": cppprogram.cpp ``` extern "C" { #include "cprogram.c" } ``` Seeherefor some examples.
I found out after reading online that if i use "%c "(with a trailing space) that scanf would read newline character but on trying it out its asking me for input thrice rather than just twice . Please tell me where i went wrong and why I am getting the answer that i am getting now ``` main() { double e = 5.32 ; int strlen , strlen1 ; char Test_string , Test_string2 ; scanf("%c " , &Test_string ) ; scanf("%c " , &Test_string2 ) ; printf("\n%c" , Test_string) ; printf("\n%c" , Test_string2) ; printf("Success") ; return 0 ; } ``` Output- ``` P A U P ASuccess ```
scanf("%c ")is going to attempt to consume one character and then all possible whitespace. When the input stream begins withP\nA\nand has not yet been closed,scanfis going to continue to try reading from the input stream until it sees either the end of input or it sees a non-whitespace character. If you are new to C, don't use scanf.
If I had a project that contained two controllers and made communication between them using SPI and I configured one of them as a master and the other as a slave, then changed the master to a slave, can the slave find out byitselfthat he has to become the master?
if changed the master to a slave can the slave find out by himself that he has to become the master ? No. SPI is a very simple protocol specification. Or maybe "protocol" is too much - it's a specification how to transfer bits. The master initiates the transfer and provides clock signal. Without clock there's no communication. Without master there's no clock. Without master there's no communication. Two connected slaves will never talk to each other. canthe slave find out by itself that he has to become the master? Sure it can. You can create your own protocol and/or mechanisms to do that, build on top or separately with SPI protocol.
Is there a way (using gcc) to set the stack size of a shared library ?I build a.sothat contain a single function that uses a big buffer as local variable.Something like that: ``` void foo ( void ) { int table [1000000] ; // 4 millions bytes table ! ... } ``` I added the option-Wl,-z,stack-size=4100000but it has no effet (not even an error message).By the way, this lib is meant to be invoked from java code (using JNA).Since I didn't find any post about this peculiar question, I'm afraid it's not possible...
No, this is not possible - functions from shared library work in the context of thread which calls them and that thread will either be a main application thread (which started inmain) or a thread created with Pthreads (which will have stack allocated at thread creation time inpthread_create). -Wl,-z,stack-sizeflag is only applicable to applications, not libraries, and sets the size of main thread's stack.
Is there a way (using gcc) to set the stack size of a shared library ?I build a.sothat contain a single function that uses a big buffer as local variable.Something like that: ``` void foo ( void ) { int table [1000000] ; // 4 millions bytes table ! ... } ``` I added the option-Wl,-z,stack-size=4100000but it has no effet (not even an error message).By the way, this lib is meant to be invoked from java code (using JNA).Since I didn't find any post about this peculiar question, I'm afraid it's not possible...
No, this is not possible - functions from shared library work in the context of thread which calls them and that thread will either be a main application thread (which started inmain) or a thread created with Pthreads (which will have stack allocated at thread creation time inpthread_create). -Wl,-z,stack-sizeflag is only applicable to applications, not libraries, and sets the size of main thread's stack.
In C, is there a way to declare an implicit type conversion for the following union type: ``` enum COMP { LessThan, Equal, GreaterThan }; ``` mapping it to, say, an integer: ``` enum COMP { LessThan : 1, Equal : 0, GreaterThan : -1 }; ```
What you have is anenum, not aunion. And what itseemslike you're asking is if you can assign specific values to enum constants. You can do so like this: ``` enum COMP { LessThan=-1, Equal=0, GreaterThan=1 }; ``` Also, enums are considered integer types, so you can safely convert to or fromint.
This function is reversing the the order of chars in a given string. Its called by inputing its start and end pointers. for example the function called like so ``` reverse(str, str + strlen(str)); ``` I don't understand why the while condition works, or more precisely what are we comparing by(start<--end). ``` void reverse(char* start, char* end) { while (start < --end) swap(start++, end); } ```
startandendare pointers to the start and end of the string.start + strlen(str)is actually one character past the last character to be swapped, soendis decremented before being compared, while start is incremented after. The reverse is done when the two pointers meet in the middle of the string. The null byte at the end of the string is retained.
Linker question: if I had a file. c that has no includes at all, would we still need alinker?
Although the linker is so-named because it links together multiple object files, it performs other functions as well. It may resolve addresses that were left incomplete by the compiler. It produces a program in an executable file format that the system’s program loader can read and load, and that format may differ from that of object modules. Specifics depend on the operating system and build tools. Further, to have a complete program in one source file, you must provide not just themainroutine you are familiar with from C and C++ but also the true start of the program, the entry point that the program loader starts execution at, and you must provide implementations for all functions you use in the program, such as invocations of system services via special trap or system-call instructions to read and write data.
I am new to servers and networking so pardon my ignorance. I have a Heroku application running a NodeJS server. I am usingconsole.log()to output the port its using to the console. But when i use the port to try to perform a GET request from my browser it keep loading forever. My request is something this: https://example.herokuapp.com:28222/getHighest When i remove the port number, it works perfectly: https://example.herokuapp.com/getHighest I am ultimately trying to perform GET and POST request from a C application. The HTTP library i am using seemingly requires a port for a connection. I am using this library:GitHub. It works perfectly when i run it locally withlocalhost:8080/getHighestbut not when i use my heroku app.
As suggested by @tadman using the default https port443solved the issue.
I have a function with two strings parameters. I have to check if both strings contains any non-null characters. Here is an example code: ``` void fun(const char* str1, const char* str2) { if (!str1 || !str1[0] || !str2 || !str2[0]) { return; } // process } ``` Is that a standard approach in C or you recommend other solution ?
It is enough to write the condition like ``` if ( !str1[0] || !str2[0] ) ``` that is when the function follows the convention of C Standard string functions when passing a null-pointer invokes undefined behavior. It is the caller of the function that shall guarantee that the passed pointers are not null pointers.
Say I have the following code: ``` int main(int argc, char *argv []) { pid_t pid = fork(); if (pid > 0) { execv(*argv, argv); } int state=0; wait(&state); return state; } ``` Does the child simply ignore the wait and skip over since it's not the calling process?
It will return-1and seterrnotoECHILDsince the child process has no children of its own to wait on. From thewait(2) man page: Return valuewait(): on success, returns the process ID of the terminated child; on error,-1is returned....Each of these calls setserrnoto an appropriate value in the case of an error.ErrorsECHILD(forwait())The calling process does not have any unwaited-for children.... Note that the logic here is backwards from the norm: if (pid > 0) { execv(*argv, argv); } Here the parent process is callingexecv(). Usually it's the child that does so whenpid == 0, and it's the parent that waits.
I have two files in Arduino IDE. One is the.inofile and one is a.cfile. main.ino: ``` #include "somefile.c" void setup(){ Serial.begin(9600); // Do something } void loop(){ // Do something } ``` And insomefile.cI want to callSerial.print(). How can I do that? Thanks!
create a my_logging.h file with ``` void my_log(const char *msg); ``` create a my_logging.cpp file with ``` #include <Arduino.h> extern "C" { #include "my_logging.h" } void my_log(const char *msg) { Serial.println(msg); } ``` then in in your c file include the my_logging.h file and you can use themy_logfunction
For public functions I'll put those in a header file such as: ``` // tree.h bool TreeIsEmpty(const Tree *ptree); bool TreeIsFull(const Tree *ptree); size_t TreeItemCount(const Tree *ptree); ``` However, what about internal implementation items? Do those only go in mytree.cfile or do I also put those into mytree.hfile? For example, let's say forTreeItemCountI have a prototype such as: ``` // tree.c static bool TreeItemCountInternal(const Tree *ptree); ``` Do I do anything in the header file with that?
static bool TreeItemCountInternal(...);hasinternal linkage, so you wouldn't put anything in the header file.
Follow-up question forthisanswer. Is there any hosted C implementations (__STDC_HOSTED__is 1) which haveCHAR_BIT > 8? If so, then which ones? UPD. Fix typo: before:__STDC_HOSTED__is0, after:__STDC_HOSTED__is1.
I don't know if there was ever a post-standardisation version, but various Cray 64-bit vector supercomputers had a C compiler in whichsizeof(long) == sizeof(double) == 1, a.k.a.everything is 64 bits wide.
I have aQueuewhich is defined around anItemtype. For example, if I want a queue of integers I have the following: ``` // queue.h typedef int Item; ``` However, I'd like the end-user to define what theItemis, and so not have it hardcoded in the header file. Is there a way to do something like the following? ``` // queue.h extern typedef Item; // pseudocode // usersfile.c typdef struct Item_ { char name[50]; } Item; // or -- typedef int Item; ``` How could that be done?
Use a void pointer (void *) type. ``` typedef void* Item; ``` If you look at theGLib, they have something calledgpointerwhich is what is used refer to arbitrary types a user might want to use in a collection. Also checkoutGQueue, which might be a good reference for your implementation.
Let's say I have the following I'm using to call a function: ``` Item dummy; while (!QueueIsEmpty(pq)) DeQueue(pq, &dummy); ``` Is there a way to put thedummyparameter into the call itself? Something like: ``` while (!QueueIsEmpty(pq)) DeQueue(pq, &(Item)NULL); ```
It looks like the method dequeues an object and copies its value to the dummy variable. Where would you expect it to be copied without providing a place to copy it to? Do you want to just throw it away and clear the queue this way? If so I would expect that you have to pass it inside unless there is another method that just clears the queue without even copying it. Maybe some clear method.
I'm working with a game engine that uses escape codes in strings to perform commands such as setting color. eg to set the color to red, you write"Red text:\x81\xFF\x00\x00\xFFhello!"(0x81, red, green, blue, alpha). Is it possible to create a macro likeTEXT_COLOR(r,g,b,a)such thatTEXT_COLOR(255,0,0,255)would expand to"\x81\xFF\x00\x00\xFF"for use in constant strings?
It takes a mix of token pasting and stringification in different macros, but, yeah, it's possible using base-16 numbers: ``` #include <stdio.h> #define TEXT_COLOR2(r,g,b,a) "\x81" #r #g #b #a #define TEXT_COLOR(r,g,b,a) TEXT_COLOR2(\x ##r, \x ##g, \x ##b, \x ##a) int main(void) { char s[] = "Red text:" TEXT_COLOR(FF, 00, 00, FF) "hello!"; for (const char *c = s; c < s + sizeof(s); c++) { printf("\\x%02hhX", *c); } putchar('\n'); return 0; } ```
This question already has answers here:What is bit masking?(6 answers)Closed2 years ago. A struct I'm dealing with has a field defined asuint8_t. The spec also states that all multiple-byte fields are represented in host-endian format. Bits 0:3 contain the information that I need (also an unsigned integer). Using plain C, how do I extract those 3 bits and convert it to a number type?
unit8_t a; unit8_t b; a = input data; b = a & 0x0F; // b contains a number from 0 to 15
``` #include <stdio.h> void add(int num){ while(num < 6){ add(num+1); } printf("\n%d",num); } void main(){ int a = 1; add(a); } ``` Can any one explain me why its going Infinite 6 6 6 6.... And not only 6 single time.
In your loop: ``` while(num < 6){ add(num+1); } ``` You never modifynum. So the loop never exits. You eventually end up via recursion with a call toadd(5). That callsadd(6)which prints the value 6 and returns. Then the prior recursive call callsadd(6)again because of the loop, and so forth. Given that you have a recursive function, you don't want a loop here. This should only be anifstatement: ``` void add(int num){ if(num < 6){ add(num+1); } printf("\n%d",num); } ``` This will print values from 6 counting down to (in this case) 1.
This question already has answers here:If char*s are read only, why can I overwrite them?(9 answers)Closed2 years ago. So if I do this, I get segmentation fault: ``` #include <stdio.h> #include <cs50.h> int main(void) { string word = "WORD"; for(int i = 0; word[i] != 0; i++) { word[i] += 32; printf("%c", word[i]); } } ``` whereas if you do this: ``` printf("%c", word[i] + 32); ``` it works as intended. What gives?
stringis not a standard C symbol, and is likely defined in yourcs50.hheader file as: ``` typedef char* string; ``` This means that variablewordis a reference toconstantdata, data that cannot be changed. So when you try to do the line: ``` word[i] += 32; ``` You are trying to change data that cannot be written to, hence, seg-fault.
I have the following code, but why doesn't the second while loop run? Any changes to make it run? ``` #include<stdio.h> int main() { int a,b,c,d,e,f; while(scanf("%d,%d,%d",&a,&b,&c)==3){ printf("ok\n"); } while(scanf("%d,%d,%d",&d,&e,&f)==3){ printf("OK\n"); } return 0; } ``` My input is ``` 1,2,3 1,5,7,4,8,7 7,8,9,... ```
Let's say you input "1,5,7,4,8,7<ENTER>" for thescanf()in the 1stwhile. Thescanf("%d,%d,%d", &a, &b, &c);reads 1 intoa, 5 intob, 7 intocand returns3keeping",4,8,7<ENTER>"in the input buffer. In the 2nd time through the loop, scanf finds the comma and returns0which terminates thewhile. Immediately after that, in the 2ndwhile, the 2ndscanf()attempts to convert",4,8,7<ENTER>"to an integer and fails promptly returning0and terminating thewhile.
The following code gives me aterminated by signal SIGSEGV (Address boundary error): ``` void rec(int x, int *arr, int *size) { if (x < 0) { rec(-x, arr, size); return; } arr = realloc(arr, sizeof(int) * ++(*size)); *(arr + (*size) - 1) = x % 10; if (x % 10 != x) rec(x / 10, arr, size); } int main() { int *arr = malloc(sizeof(int)); int *size = malloc(sizeof(int)); *size = 0; rec(20, arr, 0); } ``` I already figured our that thearrcounter in the main method won't hold the desired result, but I still can't understand why I'm getting an error.
Notice that you are passingNULLas third argument: ``` rec(20, arr, 0); // 0 is NULL ``` and you get a segfault dereferencing it: ``` arr = realloc(arr, sizeof(int) * ++(*size)); // here size is `NULL` ``` try with ``` rec(20, arr, size); ```
I'm writing some kernel modules, but for debug output I'd like to (automatically) print out which kernel module is producing the output. Is there a function or variable I can use to get the name of the module that's executing?
Inside the code of the kernel module,THIS_MODULEpoints to the structure representing this module. You may usenamefield of this structure for extract the current module name: ``` printk("Current module name: %s\n", THIS_MODULE->name); ``` If your code could be compiled (depending on configuration) either as amoduleor as apart of the kernel, then in the latter caseTHIS_MODULEwill be NULL, so you cannot access its fields. For such code you could usemodule_namemacro instead: ``` printk("Current module name: %s\n", module_name(THIS_MODULE)); ``` Within the kernel core code (not a module) the macro is expanded to the string"kernel".
There must be two variables for example A and B, these two will either take the values 0 0, 0 1 , 1 0 or 1 1. I need to check these two variables and return a value between 0 to 3, is there a better way to this than doing fourifstatements like: ``` if(B == 0 && A == 0){ return 0; } if(B == 0 && A == 1){ return 1; } if(B == 1 && A == 0){ return 2; } if(B ==1 && A == 1){ return 3; } ```
The four conditions you have shown could be addressed with the single line: ``` return A + B * 2; ``` That is, of course, if theAandBvalues willneverbe anything other than0or1.
I want to create a CountDownUP program but the code is not working, I want it to output5 4 3 2 1 0 1 2 3 4 5but it only outputs5 4 3 2 1 0 1 ``` void countDownUp (unsigned int k){ printf("\n"); for (int i = 0; i < k; i=1){ k = k - i; printf("%d ", k); } for (int n = 0; n <= k; n++){ printf("%d ",n); } } int main(){ int num; fflush(stdout); scanf("%d", &num); countDownUp (num); return 0; } ```
The firstforloop decrementskeach time through the loop, and stops whenk == 1. So the second loop just iterates from0to1. You shouldn't modifykin the first loop, you should decrementi. ``` for (int i = k; i > 1; i--) { printf("%d ", i); } ```
There must be two variables for example A and B, these two will either take the values 0 0, 0 1 , 1 0 or 1 1. I need to check these two variables and return a value between 0 to 3, is there a better way to this than doing fourifstatements like: ``` if(B == 0 && A == 0){ return 0; } if(B == 0 && A == 1){ return 1; } if(B == 1 && A == 0){ return 2; } if(B ==1 && A == 1){ return 3; } ```
The four conditions you have shown could be addressed with the single line: ``` return A + B * 2; ``` That is, of course, if theAandBvalues willneverbe anything other than0or1.
I want to create a CountDownUP program but the code is not working, I want it to output5 4 3 2 1 0 1 2 3 4 5but it only outputs5 4 3 2 1 0 1 ``` void countDownUp (unsigned int k){ printf("\n"); for (int i = 0; i < k; i=1){ k = k - i; printf("%d ", k); } for (int n = 0; n <= k; n++){ printf("%d ",n); } } int main(){ int num; fflush(stdout); scanf("%d", &num); countDownUp (num); return 0; } ```
The firstforloop decrementskeach time through the loop, and stops whenk == 1. So the second loop just iterates from0to1. You shouldn't modifykin the first loop, you should decrementi. ``` for (int i = k; i > 1; i--) { printf("%d ", i); } ```
``` #include<stdio.h> enum color {b,g,i,k}; void main() { int b=100; //line 7 enum color out=b; //line 8 printf("%d\n",out); } ``` Inline 8thebwhich i am referring to iscolor.bnot the one which declared atline 7.InC++i can referb from colorascolor::b, inCHow do i do this?
As a comment already mentioned, enumerations are part of the global scope. Usually, a prefix is used to distinguish them, for example: ``` enum color { cB, cG, cI, cK } ```
Given the following two statements to usefgetsand strip the newline: ``` puts("Enter the name."); fgets(temp.name, 40, stdin); temp.name[strcspn(temp.name, "\n")] = 0; ``` Is the following macro sufficient to take the place of this? ``` #define FGETS(str, len) fgets(str, len, stdin); str[strcspn(str, "\n")] = 0 FGETS(temp.name, 40); ``` Are there any deficiencies or ways it can be improved?
File input/output is a back-hole of time. Little to gain using a macro over a clean function. Perhaps a function to do the prompt too? Code uses a leading size perC2x priciple. ``` char *getaline(int size, char *s, const char *prompt) { if (prompt) { fputs(prompt, stdout); } if (fgets(s, size, stdin)) { // Perhaps add detection of failing to read the whole line? s[strcspn(s, "\n")] = '\0'; return s; } if (size > 0) { *s = '\0'; } return NULL; } ```
I am trying to write address of array buffer in address.txt file. I do not know why the following code does not work. The following is the code I have: ``` #include <stdlib.h> #include <stdio.h> #include <string.h> int func(char *str) { int variable_a; char buffer[12]; FILE *fp; fp = fopen( "address.txt, "w"); fprintf(fp, &buffer); fclose(fp); strcpy(buffer, str); return 1; } int main(int argc, char **argv) { char *buf = "hello\n"; if(argc > 1){ buf = argv[1]; } func(buf); printf("Returned Properly\n"); return 1; } ```
If you want to write an address, use%pto format to pointer address ``` fprintf(fp, "%p", &buffer); ``` Will do the trick
``` #include <stdio.h> int main() { if (~0 == 1) printf("yes\n"); else printf("no\n"); } ``` why is theifstatement false? can anyone explain?
~Binary One's Complement Operator is unary and has the effect of 'flipping' bits. So when you do~0 == 1it will check for-1 == 1which is false
How to find size of char** array, I have been doing ``` int getSize(char** args) { int size = (int)sizeof(args)/ (int)sizeof(arg[0]); return size; } ``` But it is only returning the value 1. I cant seem to figure out how to find out how many elements are in my array of char*.
The standard way is used byargvand the environment table (in most implementations): terminate an array ofchar *pointers to strings with aNULL: ``` Array element Points to 0 -> "string 0" 1 -> "string 1" 2 -> "string 2" . -> . . -> . . -> . N -> "string N" N+1 -> NULL ``` So you'd count the size with something like: ``` int getSize(char** args) { int size = 0; while ( args[ size ] ) { size++; } return( size ); } ```
If i have a char array of 4 bytes in size and i try to cast him into a unsigned int(4 bytes too), the compiler give me an errorwarning: cast from pointer to integer of different size [-Wpointer-to-int-cast] no_pointer = (unsigned int) char_array;Why give me this error if both variables have 4 bytes in size? Code: ``` char char_array[4] = {'a', 'b', 'c', 'd'}; unsigned int no_pointer; no_pointer = (unsigned int) char_array; ```
You cannot assing arrays by value because they get converted to address to first element. Your code is equivalent to: ``` no_pointer = (unsigned int) &char_array[0]; ``` Usememcpyinstead: ``` _Static_assert(sizeof no_pointer == sizeof char_array, "Size mismatch"); // Extra safety check to make sure that size match memcpy(&no_pointer, char_array, sizeof no_pointer); ``` But please keep in mind that byte order is dependent on endianness when using this approach.
Is there any simple way-library to efficient (max possible speed) implement linear algebra on an ARM CortexA9 dual core usingXilinx SDK? I am using a zybo z7 developememt board with a dual core Arm proccesor and i want to implement a simple neural network with one convolution layer followed by a dense one, on Xilinx SDK. Specificaly, to tranfer a python numpy based model on Arm. I read some manuals for ARM and SIMD library but i don't want to dive so deep. An easy way for me is to use a library and do the multiplication/dot product/convolve etc by itself (fast) like numpy in python and avoid pure for...loop syntax. An example would be nice! Thank for your time
You can try theEigenlibrary used by Tensorflow to implement the matrix calculations, or you can even try to useTensorFlow litewhich is already tested with the ARM-Cortex M series of processors.
Looking for an understanding of what is happening here as both statements appear the same. So while thec >> 1output is what I was expecting, shifting the wrapped uint in-place changes the result. ``` #include <stdio.h> #include <stdint.h> int main() { uint16_t a, b, c; a = 20180; b = 4106; c = b - a; printf("%hu\n", c >> 1); printf("%hu\n", (b - a) >> 1); return 0; } ``` This prints: 2473157499 What causes this behaviour? Thanks.
The "in-place" operation promotes a and b to int, and the result will also be an int that you then shift. In your assignment of c = b - a, the operation is first promoted to int operation, executed, then type casted back to uint (to be set in c). The keyword to search for is "integer promotion"
For some reason, this program compiles in C: ``` int x; x = 3+-+-5+-5; printf("%d\n",x); ``` And in general, alternating "+" and "-" compiles. It seems like if there are odd "-" then it'll subtract, otherwise, add. What in the world is this?
In cases such as these, the first + or - to the right of the left-hand operand indicates the binary operation to perform; the other + and - after that are the unary + and - operators applied to the right-hand operand. The unary + operand does nothing and - changes the sign. This gives rise to the behavior you see: an odd number of - is either addition of a negative quantity (+ followed by +s and an odd number of -s) or subtraction of a positive quantity (- followed by +s and an even number of -s).
How the extracted JSON o/p of Jmeter response to be fed to external Go/C/Java application? My requirement is to analyze the o/p of Jmeter by external program and log the analysis result ( o/p of external program), basically Jmeter response will provide input parameters to the external program.
If you want to save response of a JMeter'sSamplerinto a file - just addSave Responses to a filelistener and specify the desired file location: Example configuration: Once you run your request and get the response - JMeter will store it into a file under the given path so you will be able to "feed" it to an external program. SeePerformance Testing: Upload and Download Scenarios with Apache JMeterarticle for more details if needed. If you want to perform the analysis within the bounds of the JMeter test execution - you can invoke this 3rd-party program viaOS Process Sampler
I thought I understood how memory works until I run this code, is memory backwards ? or I'm missing something ? Code: ``` #include <stdio.h> int main() { int a = 0x12345678; char *c = (char *)&a; for (int i = 0; i < 4; i++) { printf("c[%d]=%x \n", i, *(c + i)); } return 0; } ``` Output: ``` c[0]=78 c[1]=56 c[2]=34 c[3]=12 ```
What you have just done is demonstrate which "endian" your computer's architecture is using (i.e., your computer uses "little endian", not "big endian"). If your computer's architecture had instead been "big endian", then your output would instead have been this: ``` c[0] = 12 c[1] = 34 c[2] = 56 c[3] = 78 ``` You may want to read this for more information:https://en.wikipedia.org/wiki/Endianness
I can't figure out how to get the input to show-up after Enter a Character. Would appreciate if someone can help me figureout how. ``` #include <stdio.h> #include <conio.h> const int ESC = 27; char change_case(char cIn); int main() { char ch; do { printf("Enter a character: \n"); ch = _getch(); if (ch == 27) break; printf("Changed Character: %c \n\n", change_case(ch)); } while (1); } char change_case(char cIn) { if (cIn >= 'a' && cIn <= 'z') return cIn - 32; else if (cIn >= 'A' && cIn <= 'Z') return cIn + 32; printf("\nTHAT IS NOT A LETTER!\n"); return cIn; } ```
_getch()/getch()does not echo the keyboard input. Use_getche()instead - it does echo input.
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.Closed2 years ago.Improve this question I want to use the typeof operator to declare a variable that will hold the return value of a function. ``` int func(void) { ++counter; } typeof(func()) val = func(); // side effects for calling func() twice ``` Is there a way I can use typeof on a function to get the return type without calling the function? Solution: My bad. There is no side effect.
Not in standard C, but GCC and clang provide the__typeof__extension which does what you want.
So I've been trying to do this but I just can't think of a solution for this. I've got this bit of code but it outputs it backwards(if the answer is 11110 I get 01111): ``` #include <stdio.h> int base(int n) { if(n==0) return 0; else { printf("%d",n%2); } return base(n/2); } int main() { int n; scanf("%d",&n); base(n); return 0; } ``` Is there any trick for this problem or do I need to analyze this deeper?
As@ricistated, a very simple fix is to print after the recursive call: ``` #include <stdio.h> void base(int n){ if(n==0) return; base(n/2); printf("%d",n%2); } int main() { int n; scanf("%d",&n); base(n); return 0; } ```
How a C compiler like GCC defines the preprocessor macro to detect the current OS? I looked into GCC's source code and foundthisbuiltin_define ("_WIN32");but I'm not sure if this is where the macros are defined.
TL;DR: Basically, yes. The built-in macros are defined in a target description header file. There is so often a Fine Manual To Read; in this case, it's theGCC internals manual. (Specifically, in the section onRun-time target specification, but don't start reading there; you'll need some context.) There is acomplete compendium of GCC documentationin case you need more information. (The internals documents are at the bottom of that page.) (If you're comfortable using the GNU info reader and you're using a Ubuntu/Debian system, you can install the GCC documentation for your current GCC version withsudo apt-get install gcc-doc; that includes the GCC internals documentation.)
How the extracted JSON o/p of Jmeter response to be fed to external Go/C/Java application? My requirement is to analyze the o/p of Jmeter by external program and log the analysis result ( o/p of external program), basically Jmeter response will provide input parameters to the external program.
If you want to save response of a JMeter'sSamplerinto a file - just addSave Responses to a filelistener and specify the desired file location: Example configuration: Once you run your request and get the response - JMeter will store it into a file under the given path so you will be able to "feed" it to an external program. SeePerformance Testing: Upload and Download Scenarios with Apache JMeterarticle for more details if needed. If you want to perform the analysis within the bounds of the JMeter test execution - you can invoke this 3rd-party program viaOS Process Sampler
I thought I understood how memory works until I run this code, is memory backwards ? or I'm missing something ? Code: ``` #include <stdio.h> int main() { int a = 0x12345678; char *c = (char *)&a; for (int i = 0; i < 4; i++) { printf("c[%d]=%x \n", i, *(c + i)); } return 0; } ``` Output: ``` c[0]=78 c[1]=56 c[2]=34 c[3]=12 ```
What you have just done is demonstrate which "endian" your computer's architecture is using (i.e., your computer uses "little endian", not "big endian"). If your computer's architecture had instead been "big endian", then your output would instead have been this: ``` c[0] = 12 c[1] = 34 c[2] = 56 c[3] = 78 ``` You may want to read this for more information:https://en.wikipedia.org/wiki/Endianness
I can't figure out how to get the input to show-up after Enter a Character. Would appreciate if someone can help me figureout how. ``` #include <stdio.h> #include <conio.h> const int ESC = 27; char change_case(char cIn); int main() { char ch; do { printf("Enter a character: \n"); ch = _getch(); if (ch == 27) break; printf("Changed Character: %c \n\n", change_case(ch)); } while (1); } char change_case(char cIn) { if (cIn >= 'a' && cIn <= 'z') return cIn - 32; else if (cIn >= 'A' && cIn <= 'Z') return cIn + 32; printf("\nTHAT IS NOT A LETTER!\n"); return cIn; } ```
_getch()/getch()does not echo the keyboard input. Use_getche()instead - it does echo input.
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.Closed2 years ago.Improve this question I want to use the typeof operator to declare a variable that will hold the return value of a function. ``` int func(void) { ++counter; } typeof(func()) val = func(); // side effects for calling func() twice ``` Is there a way I can use typeof on a function to get the return type without calling the function? Solution: My bad. There is no side effect.
Not in standard C, but GCC and clang provide the__typeof__extension which does what you want.
So I've been trying to do this but I just can't think of a solution for this. I've got this bit of code but it outputs it backwards(if the answer is 11110 I get 01111): ``` #include <stdio.h> int base(int n) { if(n==0) return 0; else { printf("%d",n%2); } return base(n/2); } int main() { int n; scanf("%d",&n); base(n); return 0; } ``` Is there any trick for this problem or do I need to analyze this deeper?
As@ricistated, a very simple fix is to print after the recursive call: ``` #include <stdio.h> void base(int n){ if(n==0) return; base(n/2); printf("%d",n%2); } int main() { int n; scanf("%d",&n); base(n); return 0; } ```
How a C compiler like GCC defines the preprocessor macro to detect the current OS? I looked into GCC's source code and foundthisbuiltin_define ("_WIN32");but I'm not sure if this is where the macros are defined.
TL;DR: Basically, yes. The built-in macros are defined in a target description header file. There is so often a Fine Manual To Read; in this case, it's theGCC internals manual. (Specifically, in the section onRun-time target specification, but don't start reading there; you'll need some context.) There is acomplete compendium of GCC documentationin case you need more information. (The internals documents are at the bottom of that page.) (If you're comfortable using the GNU info reader and you're using a Ubuntu/Debian system, you can install the GCC documentation for your current GCC version withsudo apt-get install gcc-doc; that includes the GCC internals documentation.)
Im learning about typecasting in void pointers and the part of *((typecasting) void_pointer) i am not undestanting why need this *( before the real type casting. Can someone explain me this part of code: ``` printf("[int pointer] points to %p, which contains the int %d\n", void_pointer, *((int *) void_pointer)); ``` what this part does*((int *) void_pointer)) (Sorry my english)
I'm assuming thatvoid_pointeris of typevoid *. Void pointers can point to any type, you can't dereference them directly. So let's break down*((int *) void_pointer. First, it is casted to anintpointer (this is what(int *) void_pointer) does. Then, the pointer is dereferenced in order to get the value it points to. You can rewrite it as: ``` int *int_pointer = (int *) void_pointer; int int_value = *int_pointer; ```
I need to read specific charters from terminal, How can I do this? I need reading this characters[,],{,},(,). Is there any way to do this usingscanf? I triedscanf("%[(,),[,]]s", string), but it does not work.
You need to include]first in the list of characters to match so that it is not taken as terminating the conversion specifier. Also, unless you want to match commas, don't include them. And unless you want to match a literals, don't put thesin the format string. The conversion specifier ends with]. I think you're just looking for something like: ``` #include <stdio.h> int main(void) { char buf[32]; if( scanf("%31[][(){}]", buf) == 1 ) { printf(" read: '%s'\n", buf); } return 0; } ```
According to BSON specification an int32_t is used for the total number of bytes comprising the document. I can also see that mongo-c-driver is using Libbson and it's using int32_t. But what is the reason to usesignedinteger instead ofunsignedinteger? the document size will never be below 0. Can someone please explain the reason?
Document size is limited to 16 MB, which fits in a signed 32-bit integer with room to spare. While document size limits larger than 16 MBwereconsidered, my guess is there was no serious consideration of document sizes exceeding 2 GB, therefore the difference in range afforded by using unsigned 32-bit integers for length wasn't a meaningful benefit. Thus, there is no reason to use an unsigned type. Reasons to NOT use an unsigned type: Wraparound potential from UINT_MAX to 0.-1 could be used as a special designator.
Trying to get an struct initializer from a tertiary operator in a macro function doesn't work, it gives a bunch of errors, what should be the right way to do this: ``` #define newVar(name, type, value) (( (type) == _STRING ) ? { name, type, (long)value }) : ({ name, type, (double)value } ) ``` Edit: Sorry, i wrote array initializer and not struct initializer
You may not use the ternary (conditional) operator such a way in an initialization because the operator expects three expressions. However these constructions{ name, type, (long)value }and{ name, type, (double)value }are not expressions. They are initializer lists. For example you may write ``` int x = { 10 }; ``` but you may not write ``` int x = 1 ? { 10 } : { 20 }; ``` because in the ternary operator{ 10 }and{ 20 }are not expressions.
I am working fixing on some coverity issues and i am confused about how to solve toctou for stat a directory and make a directory. ``` //////////////////////////////////// // Make sure storage dir exists. If // not, create it. if( stat( dir, &statBuff ) != -1 ) { if( S_ISDIR( statBuff.st_mode ) ) { if( (dirPtr = opendir( fabcSsrDbStorageDir )) == NULL) { } closedir(dirPtr); } } else { //////////////////////////////////// // dir directory // does not exist- create it // now. if( (mkdir( dir, S_IRWXU )) != 0 ) { } } ``` Please give your suggestions Thanks
Just domkdir(). If the directory already exists,EEXISTwill tell you. Accept either zero or this return-code to indicate that you have, one way or the other, now accomplished your objective. "Race conditions" cease to be an issue sincemkdir()has taken care of that for you.
I have the following code: ``` int main(int argc,char **argv){ char *flags=malloc(1*sizeof(char)); flags[0]='a'; printf("%s\n",flags); free(flags); return 0; } ``` No more, no less. If I comment out the printf, no error occurs. Why does it give me this error and how can I solve it?
Withprintf("%s\n",flags);,flagsshould point to memory that contain astring. flagsmemory does not contain anull chracter, so is not a string. Either 1, make allocated memory assigned toflagsbigger and append a'\0'or 2, use a limited print:printf("%.1s\n",flags);or 3) print achar:printf("%c\n",*flags);
Trying to get an struct initializer from a tertiary operator in a macro function doesn't work, it gives a bunch of errors, what should be the right way to do this: ``` #define newVar(name, type, value) (( (type) == _STRING ) ? { name, type, (long)value }) : ({ name, type, (double)value } ) ``` Edit: Sorry, i wrote array initializer and not struct initializer
You may not use the ternary (conditional) operator such a way in an initialization because the operator expects three expressions. However these constructions{ name, type, (long)value }and{ name, type, (double)value }are not expressions. They are initializer lists. For example you may write ``` int x = { 10 }; ``` but you may not write ``` int x = 1 ? { 10 } : { 20 }; ``` because in the ternary operator{ 10 }and{ 20 }are not expressions.
I am working fixing on some coverity issues and i am confused about how to solve toctou for stat a directory and make a directory. ``` //////////////////////////////////// // Make sure storage dir exists. If // not, create it. if( stat( dir, &statBuff ) != -1 ) { if( S_ISDIR( statBuff.st_mode ) ) { if( (dirPtr = opendir( fabcSsrDbStorageDir )) == NULL) { } closedir(dirPtr); } } else { //////////////////////////////////// // dir directory // does not exist- create it // now. if( (mkdir( dir, S_IRWXU )) != 0 ) { } } ``` Please give your suggestions Thanks
Just domkdir(). If the directory already exists,EEXISTwill tell you. Accept either zero or this return-code to indicate that you have, one way or the other, now accomplished your objective. "Race conditions" cease to be an issue sincemkdir()has taken care of that for you.
I have the following code: ``` int main(int argc,char **argv){ char *flags=malloc(1*sizeof(char)); flags[0]='a'; printf("%s\n",flags); free(flags); return 0; } ``` No more, no less. If I comment out the printf, no error occurs. Why does it give me this error and how can I solve it?
Withprintf("%s\n",flags);,flagsshould point to memory that contain astring. flagsmemory does not contain anull chracter, so is not a string. Either 1, make allocated memory assigned toflagsbigger and append a'\0'or 2, use a limited print:printf("%.1s\n",flags);or 3) print achar:printf("%c\n",*flags);
I'm trying to format a string like this: ``` printf("%d%c", buffer[i], i == num_ints-1? '': ','); ``` So that the numbers print like this: ``` 123,929,345 ``` Yet doing''is invalid. Is it possible to simulate a 'nothing-char' or just not do anything in the ternary?
You can't have an empty char, but you can have empty strings. So use%s. ``` printf("%d%s", buffer[i], i == num_ints-1? "": ","); ```
I know this may sound stupid but, why is this function I implemented not working properly? I get the following error in the terminal: ``` cerinta3.c: In function ‘void realocare_memorie(student**, int)’: cerinta3.c:9:19: error: invalid conversion from ‘void*’ to ‘student*’ [-fpermissive] 9 | *vector = realloc(*vector, dimensiune * sizeof(student)); | ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | void* ``` ``` void realocare_memorie (student **vector, int dimensiune) { *vector = realloc(*vector, dimensiune * sizeof(student)); } ```
You compiled your C code through a C++ compiler (g++by the error message). This is the signature error of making that mistake. Invokegccinstead.
I know this may sound stupid but, why is this function I implemented not working properly? I get the following error in the terminal: ``` cerinta3.c: In function ‘void realocare_memorie(student**, int)’: cerinta3.c:9:19: error: invalid conversion from ‘void*’ to ‘student*’ [-fpermissive] 9 | *vector = realloc(*vector, dimensiune * sizeof(student)); | ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | void* ``` ``` void realocare_memorie (student **vector, int dimensiune) { *vector = realloc(*vector, dimensiune * sizeof(student)); } ```
You compiled your C code through a C++ compiler (g++by the error message). This is the signature error of making that mistake. Invokegccinstead.
I see that when I use that code: ``` char c,d; scanf("%s",&c); scanf("%s",&d); printf("%c%c",c,d); ``` seems fix the problem of save ENTER character indvariable. It's a good way or compiler add the string terminator in the memory address next tocvariable (equals fordvariable)?
No, because it will also want to null-terminate the string. In other words, write to*(d + 1)(at least!), and that's undefined behavior (namely, overflow).
I'm trying to port some code from C to Python. I have in C: ``` unsigned char bPort = 7777 ^ 0xCC; printf("\n %d \n", bPort); ``` Which prints 173 But then in Python ``` bPort = 7777 ^ 0xCC print(bPort) ``` this prints 7853
``` unsigned char bPort = 7777 ^ 0xCC; ``` is equivalent to ``` unsigned char bPort = the least significant 8 bits of 7777 ^ 0xCC; ``` unsigned charonly stores 8 bits. The same is not true of Python. I'm not an expert on the numerical types in Python, but I suspect that's either a 32 bit integer or a floating point representation. To fix it in Python, just mask off the extra bits. ``` bPort = (7777 ^ 0xCC) & 0xff ```
I am using the following code to calculate pi in C but the answer is only being printed to 6dp. code: ``` #include<stdio.h> #include<stdlib.h> long double calc_pi(int terms) { long double result = 0.0F; long double sign = 1.0F; for (int n = 0; n < terms; n++) { result += sign/(2.0F*n+1.0F); sign = -sign; } return 4*result; } int main(int argc, char* args[]) { long double pi = calc_pi(atoi(args[1])); printf("%LF", pi); } ``` output: ``` $ ./pi 10000 3.141493 ``` the 10000 is the number of terms that are used as the code uses an infinite series.
You can add a precision specifier to yourprintf()format specifier to have it print more digits. ``` int main(int argc, char* args[]) { long double pi = calc_pi(atoi(args[1])); printf("%.30LF", pi); /* have it print 30 digits after the decimal point */ } ```
I am so confused about the return of getopt. When does it return (-1) ? When I assign it to an int variable, it returns (-1) if I don't write any options in the terminal window. Whereas it returns the first option character in ascii even if I write more than one option. But when using it without assigning, it returns (-1) if I write more than one option. And concerning the attached images, how did it type the error message although the value equals -1 ? The Statments The results
In your example with 2 arguments getopt will return a different value each time you will call it. The first time it will return 'a' then it will return 'b' and the last time it has no more options to read from and will return -1 It should be handled within a loop like thishttps://www.tutorialspoint.com/getopt-function-in-c-to-parse-command-line-arguments
I am so confused about the return of getopt. When does it return (-1) ? When I assign it to an int variable, it returns (-1) if I don't write any options in the terminal window. Whereas it returns the first option character in ascii even if I write more than one option. But when using it without assigning, it returns (-1) if I write more than one option. And concerning the attached images, how did it type the error message although the value equals -1 ? The Statments The results
In your example with 2 arguments getopt will return a different value each time you will call it. The first time it will return 'a' then it will return 'b' and the last time it has no more options to read from and will return -1 It should be handled within a loop like thishttps://www.tutorialspoint.com/getopt-function-in-c-to-parse-command-line-arguments
I did research trying to visualise how complex number in <complex.h> are stored in RAM. I know for integers, floating points but not for complex. Is it just 2 number like in complex struct ?
The layout is specified in C11 6.2.5/13: Each complex type has the same representation and alignment requirements as an array type containing exactly two elements of the corresponding real type; the first element is equal to the real part, and the second element to the imaginary part, of the complex number.
When the user inputs a sentence with ECE in it, the program should output ECE found!, but when ECE is the only input the program does not detect it. I believe that all of the other cases work. I can not use arrays or strings for this program. ``` #include <stdio.h> #include <stdlib.h> int main() { char input; char char1, char2, char3; printf("Please enter a sentance: "); scanf(" %c, %c, %c", &char1, &char2, &char3); while(1){ if (char1 == 'E' && char2 == 'C' && char3 == 'E') printf("Found ECE!"); if(char1 == '.' || char2 == '.'|| char3 == '.') break; scanf(" %c", &input); if (input == '.') break; char1 = char2; char2 = char3; char3 = input; } return 0; } ```
Don't put commas in between the%c %c %c. They are not needed. Scanf()does something weird with characters in the%carea.
I am writing a GTK+ frontend program that shreds files. The programshredfrom GNU Coreutils is the backend. The programming language is C. So, I have a progress bar that show how much of the shredding is finished. But, in order to give the user accurate data on how much is shredded, the output of shred must be analyzed. So far I have triedg_spawn_command_line_async, but I am not able to send the output of shred to a file.
The easiest solution is using unix redirection. You can callsystem("shred -v file_to_shred > somefile.txt")and the output will be redirect to the file. You can then read from the file using POSIX read or some other file reading method. Run thesystem()call in a seperate thread, and the just incremently check the file in the main thread. You could use POSIXsleep()to check the file at some interval, say, every half second. However, never use sleep on the GUI thread, as this will freeze the UI.
``` using namespace std; int main() { int input; int i=0; while (1){ scanf("%d", &input); printf("%d input:%d\n", i, input); i++; } } ``` Stdin Inputs: 10 65 100 30 95 . . . Is there a way to stop the code and escape from while loop after hitting the last Input? Amount of Inputs can be N. edition) Is there a way to calculate the amount of Stdin Inputs? This is my major question.
``` using namespace std; int main() { int input; int i=0; while (1){ scanf("%d", &input); printf("%d input:%d\n", i, input); i++; if (i >= 5) break; //change 5 to your desired amount of inputs } } ```
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.Closed2 years ago.Improve this question scanf will only allow me to input a single number before ending the for loop, whereas I should be able to input 7, here's the code: ``` #include <stdio.h> int main(){ float M, N=0; int n; for(n=1; n<8; n++){ printf("Digite o peso da pessoa nro %d em kg:", n); scanf(" &N"); M+=N/7; n=n+1; } printf("A media de peso em kg e: %f", M); } ``` Does anyone know what's going on?
Replace the following line: ``` scanf(" %f", &N); ``` fstands for your float.
I'm trying to loop through a string by using a pointer and[]for the string, and the pointer should get on each iteration the char address, from tail to head: ``` int main(void) { char* s = "somestring"; char* s_p; int len = strlen(s); for (s_p = &s[len - 1]; s_p = &s[1]; s_p--) { //do something } return 0; } ``` The problem I have, is that at the point of theforinitialization,s_pis getting the address of the second index ofs, hences[1], for instance, if"somestring"is located in0x00d97be0, then the addresss_ppoints to is:0x00d97be1("omestring"), and my intention was thats_pstart from0x00d97be9"g". What am I missing here? P.S. When I'm writings_p = &s[len - 1];before the loop, I indeed gets_p=0x00d97be9"g", as expected.
Loop condition should use comparison operator, not assignment operator=. I guess the intention was to use!=. ``` s_p = &s[1] --> s_p != &s[1] ```
In our development, we switched from IAR ARM V7.40 to IAR ARM V8.40 We are using the python packagepyelftoolsfor postprocessing of the debug information. Unfortunately, this seems to be broken now, as the V8-compiler seems to use DWARF4 syntax, which is not fully covered by pyelftools. The V7-compiler used DWARF3 which was fine. Is there any compiler option for IAR V8 to change DWARF format? In theIAR C/C++ Development Guide, I only find the--debug, -roption to enable debug information, but no further fine tunings (e.g. like-gdwarf-3option for the arm-clang compiler).
There is a hidden compiler option--no_dwarf4which disables DWARF4. This works fine for our problem. Unfortunately, this compiler option is neither documented in theIAR C/C++ Development Guidenor listed in the command line help ($ iccarm --help) for the compiler.
So I have to make an add method that will take two 16 bit integers and return that result without using arithmetic operators. Unfortunately when inputting two numbers like 5 and 10, it returns 0 instead of 15. Is there anything I'm doing wrong in my code? The code is given below and is done in C ``` addition_subtraction_result add(uint16_t augend, uint16_t addend) { addition_subtraction_result addition; while (addend != 0){ int carry = augend & addend; augend = augend ^ addend; addend = carry << 1; } addition.overflow = false; return addition; } ``` Let me know if you need more information. Thanks!
You returnaddition(hopefully by value) and the only thing you set isaddition.overflow = false;
I have the following code: ``` ll_data_comp sh_program_comp(int pid) { int comp(void* d) { sh_program_t* p = d; return p->pid == pid; } return comp; } ``` Sincecompis declared insh_program_comp, does that mean it's declared on the stack?If so, does that mean there's potential for a seg fault if it's used after it's returned?If not, does that mean I have to freecompsomewhere?
I have the following code: And you have tagged your question withC99. The following code is invalid - it's not possible to define a function within a block scope. The code may be compiled with GNU gcc compiler withNested Functionsextensionto the C language. But from the documentation: If you try to call the nested function through its address after the containing function exits, all hell breaks loose. If you try to callcompfunction aftersh_program_comp, a portal to hell will open. Please don't do it.
I'm trying to get a copy of the RGBTRIPLE image array ``` void blur(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE arrayCopy = image[height][width]; for (int i = 0; i < height; i++) { for (int w = 0; w < width; w++) { printf("%i", arrayCopy[i][w].rgbtRed); } } return; } ``` The problem is when I want to print out a value it doesn't work
A copy of the whole 2D array? ``` RGBTRIPLE arrayCopy[height][width]; memcpy(arrayCopy, image, sizeof arrayCopy); //not sizeof image, it is a pointer to an array, not an array ``` or just a pointer toimage? ``` RGBTRIPLE (*arrayCopy)[width] = image; ``` usage is the same as you already did.
when declaring for example a malloc and then checking if it is NULL to see if it has been properly allocated, should I free the memory if it is null, example: ``` int *p; p = (int *)malloc(sizeof(int)); if (p == NULL) { free(p); //Should I free here or will it create an error? return NULL; } ```
Ifmallocreturns a null pointer it has failed to allocate anything at all, and there's nothing to free. With that said, passing a null pointer tofreedoes nothing, so it's safe. On a related note, in C you shouldn't reallycast the result ofmalloc.
Let's take two examples of having 'stuff' between a keyword: ``` #include <stdio.h> int main(void) { printf("OK\n"); pri\ ntf("OK\n"); // version 1 pri/**/ntf("Hi"); // version 2 return 0; } ``` That is, having a comment/* ... */and a\/n. How are these two supposed to be treated, or is it compiler dependent?
I save the code in file a.cpp, then pre-compile the code: ``` gcc -E a.cpp ``` The output is: ``` int main(void) { printf("OK\n"); printf("OK\n"); pri ntf("Hi"); return 0; } ``` The first case can pass the compile. but for the second case, gcc will replace/**/to blank, then compile will fail. gcc and clang have the same result on this. It's a C standard.
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed2 years ago. ``` #include<stdio.h> int main() { int i = 1; printf("%d %d %d",++i,i++,i); return 0; } ```
(not an answer, but further discussion) It really seems like an interesting question (at least for me, as I am also a C newby). I tried the followingsnippet: ``` //gcc 7.4.0 #include<stdio.h> int main() { int i = 1; printf("%d %d %d\n",pr(++i),pr(i++),pr(i)); // 3 1 1 i=1; printf("%d %d %d",++i,i++,i); // 3 1 3 return 0; } int pr(int v){ printf ("arg: %d\n",v); return v; } ``` And was shown (for the upper case) ``` arg: 1 arg: 1 arg: 3 ``` I still don't understand why my twoprintf()statements yield different results.
I'm learning C but I don't understand why the error appears on line number 9 ---> scanf("%[^\n]s",&cadena); // i tried with "%s" but still doesnt work. ``` #include <stdio.h> int main(void) { char cadena[40]; printf("Ingrese cadena: "); fflush(stdin); scanf("%[^\n]s",&cadena); printf("La cadena es %s \n", cadena); return (0); } ```
Remove the ampersand on cadena in scanf ``` scanf("%[^\n]", cadena); ``` An array decays to a pointer so you were actually passing a pointer to a pointer in that case. Also you can just write it like this ``` scanf("%s",cadena); ``` Depends on your end goal though.
I wrote following C function: ``` unsigned long long int myfunction(unsigned long long int number) { return number; } ``` and after making a shared library I want to calling it from python: ``` from pathlib import Path from ctypes import CDLL, c_ulonglong cwd = Path.cwd() so_file = Path.joinpath(cwd, Path("mylib.so")) c_lib = CDLL(so_file) c_func = c_lib.myfunction if __name__ == '__main__': my_number = 844952973115541 my_c_number = c_ulonglong(my_number) ans = c_ulonglong(c_func(my_c_number)) print(ans.value) ``` I expect to get back the number I gave, but the following number returns: ``` 18446744073471557781 ```
They python code assumes the c function returns an int. You can fix it by adding: ``` c_func.restype = c_ulonglong ```
I work on Linux. In have a legacy OpenGL application which includes gl.h. I would like to define a function pointer for storing glXGetProcAddress result: ``` typedef void (GLACTIVETEXTUREARB)(GLenum texture); extern GLACTIVETEXTUREARB glActiveTextureARB; ``` but I get the following error:redefinition of glActiveTextureARB as different kind of symbol, previous definition: gl.h:1966 I have to include gl.h because it contains basic types definitions, for example GLenum. How to hide that function prototype ? glext.h defines function prototypes based on GL_GLEXT_PROTOTYPES but gl.h doesn't use it.
Use a define to rewrite the original name: ``` #define glActiveTextureARB glh__glActiveTextureARB #include<gl.h> #undef glActiveTextureARB ``` By the way, yourgl.hprobably already hasPFNGLACTIVETEXTUREARBPROCdefined as the function pointer type you want to have, so you don't need to redefine it.
This question already has answers here:How should character arrays be used as strings?(4 answers)Closed2 years ago. ``` #include <stdio.h> int main() { char str3[6] = {'h', 'e', 'l', 'l', 'o', '\0'}; char str4[ ] = {'h', 'e', 'l', 'l', 'o'}; printf("%s, %s", str3, str4); return 0; } ``` The output for this is : hello, hellohello Why two times hello ????
str4has no 0-terminator, soprintfkeeps reading out of bounds of the array and by luck (or not) there seems to bestr3directly behindstr4, so it reads till the 0-terminator ofstr3. In the end ==> undefined behavior, don't rely on that.
If you input even numbers, only the odd numbers will be printed until it reaches 0. (0 will not be printed). For example, if you input 10, the output would be 9, 7, 5, 3, 1. This is what I came up with. I'm wondering what should I decrement x by to get the desired output. ``` int x; scanf("%d", &x); while (x >= 0) { printf("%d", x); x = x - 2; } ```
I'm wondering what should I decrement x by to get the desired output. Subtracting 2 is fine, as long as you always start from an odd number. So you could change the loop into something like this: ``` for ( int i = x % 2 ? x : x - 1; // Is x odd? good. // Otherwise, start from the previous one. i > 0; i -= 2 ) { printf("%d\n", i); } ```
So I got a function that passes in bool as an input that I declared withvoid check_Winner(bool locked_[9][9]); The error happens when I call it in "print_Winner" function: ``` bool locked[9][9]; void print_Winner(void) { for (int j=0;j<pair_count;j++) { check_Winner(locked[0][j]); } return; } ``` I dont understand why "incompatible integer to pointer conversion passing 'bool' to parameter of type 'bool (*)[9]' " occurs in thecheck_Winner(locked[0][j]);PS: pair_count<9
The function is taking in parameter an array: ``` void check_Winner(bool locked_[9][9]); ``` But the function call is providing a bool (locked[0][j]is a bool): ``` check_Winner(locked[0][j]); ```
So I got a function that passes in bool as an input that I declared withvoid check_Winner(bool locked_[9][9]); The error happens when I call it in "print_Winner" function: ``` bool locked[9][9]; void print_Winner(void) { for (int j=0;j<pair_count;j++) { check_Winner(locked[0][j]); } return; } ``` I dont understand why "incompatible integer to pointer conversion passing 'bool' to parameter of type 'bool (*)[9]' " occurs in thecheck_Winner(locked[0][j]);PS: pair_count<9
The function is taking in parameter an array: ``` void check_Winner(bool locked_[9][9]); ``` But the function call is providing a bool (locked[0][j]is a bool): ``` check_Winner(locked[0][j]); ```
When using realloc, it's better to check against possible null pointers, as: ``` int *tempPtr=realloc(ptr1,size); if(tempPtr==NULL){ fprintf(stderr,"Error allocating memory at line %d\n",__LINE__); exit(-1); } ptr1=tempPtr; ``` The problem with this approach is that it creates a new variable and if this isn't inside a quick temporary block, it will only be destroyed when the program ends. Is there any way to destroy this variable?
You can place these expressions in a block scope of its own. Essentially just encapsulate the expression within braces, ie: ``` { int *tmpptr = realloc(ptr1, size); if (tmpptr == NULL) { panic("allocation failed"); } ptr1 = tmpptr; } // Continue executing code here // note that moving forwards from here, tmpptr is out of scope and cannot be used. ```
Checksumof a number is the sum of all its digits.I wrote the following program to find the checksum of a number: ``` #include <stdio.h> int read(){ int read; printf("number between 1000 and 100.000: "); scanf("%d", &read); return read; } int calcSum(int num){ int a; if (num < 10) return num; a = calcSum (num / 10) + num % 10; if (a > 10) a += calcSum (a / 10) + a % 10; return a; } void output(int in, int num){ printf("checksum vof %d = %d", in, num); } int main(){ int num; num = read(); output(num, calcSum(num)); return 0; } ``` It works with some numbers like 11, 12 but not with numbers like 706
Ifa > 10, you are performing the same operation multiple times. Just do: ``` int calcSum(int num) { int a; if (num < 10) return num; a = calcSum (num / 10) + num % 10; return a; } ```
How can I use struct pointers with designated initialization? For example, I know how to init the struct using the dot operator and designated initialization like: ``` person per = { .x = 10,.y = 10 }; ``` But If I want to do it with struct pointer? I made this but it didn't work: ``` pper = (pperson*){10,5}; ```
Ifpperis aperson *that points to allocated memory, you can assign*ppera value using a compound literal, such as either of: ``` *pper = (person) { 10, 5 }; *pper = (person) { .x = 10, .y = 5 }; ``` If it does not already point to allocated memory, you must allocate memory for it, after which you can assign a value: ``` pper = malloc(sizeof *pper); if (!pper) { fputs("Error, unable to allocate memory.\n", stderr); exit(EXIT_FAILURE); } *pper = (person) { 10, 5 }; ``` or you can set it to point to an existing object: ``` pper = &SomeExistingPerson; ```
I'm trying to run some python code from my c program by using the python.h header but I keep gettingfatal error: Python.h: No such file or directory After checking my anaconda environment, I have found a Python.h file in...Anaconda/envs/myenv/includeI tried adding this path to my system variable's PATH but it didn't work. How can I include the Python.h file from my anaconda env to my program?
PATHis only used for executables, not C headers. Tell your compiler or build system to add this path. On gcc and clang, for example, it's the-Iflag.
I have two integer variables: int i1 = 0xdeadbeefandint i2 = 0xffffbeef. (11011110101011011011111011101111 or 37359285591and111111111111111110111110111011111 or 4294950639respectively). (int) (float) i1 == i1evaluates as false, yet(int) (float) i2 == i2evaluates as true. Why is this? In this system, bothintsandfloatsare stored in 4 bytes.
This is becausefloathas far less precision thanint, it can't store all possibleintvalues without them suffering some damage. Sometimes this damage just rounds your value, sometimes your rounded value matches precisely. A32-bitfloatcan only store 24 "significand bits", or numerical data. Other bits are reserved for things like exponent, NaN flagging, Infinity and so on, where that eats into the remaining storage space. Adoubledoes have the required precision as it's usually a 64-bit representation that can store 53 bits of numerical data data.
I'm playing around with C strings as in the following programme: ``` #include <stdio.h> int main(void){ char *player1 = "Harry"; char player2[] = "Rosie"; char player3[6] = "Ronald"; printf("%s %s %s\n", player1, player2, player3); return 0; } ``` Which prints the following: ``` Harry Rosie RonaldRosie ``` Why is "Rosie" printing out twice?
Ronaldhas 6 letters, sochar player3[6]leaves no space for the null-terminator character'\0'. In your case, it printed whatever comes afterRonaldin memory until a'\0'was encountered. That happened to beRosie. You might not always be so lucky and run into an error (e.g. memory protection) before finding a'\0'. One solution (apart from how you initializedHarryandRosie) is to increase the number of elements by one to provide space for a trailing'\0': ``` char player3[7] = "Ronald"; ```
I'm playing around with C strings as in the following programme: ``` #include <stdio.h> int main(void){ char *player1 = "Harry"; char player2[] = "Rosie"; char player3[6] = "Ronald"; printf("%s %s %s\n", player1, player2, player3); return 0; } ``` Which prints the following: ``` Harry Rosie RonaldRosie ``` Why is "Rosie" printing out twice?
Ronaldhas 6 letters, sochar player3[6]leaves no space for the null-terminator character'\0'. In your case, it printed whatever comes afterRonaldin memory until a'\0'was encountered. That happened to beRosie. You might not always be so lucky and run into an error (e.g. memory protection) before finding a'\0'. One solution (apart from how you initializedHarryandRosie) is to increase the number of elements by one to provide space for a trailing'\0': ``` char player3[7] = "Ronald"; ```
I've been stuck with this for a while. I can't really figure out why I'm getting this message: I get the error message: "Segmentation fault (core dumped)" when I first compile gcc my_program.c and then run it ./a.out my_program.c Main file:https://i.stack.imgur.com/usdsc.jpgHeader file:https://i.stack.imgur.com/jJeuu.jpg I can't for the life of me figure out where the problem is since C isn't really my friend and it doesn't tell me where the error is in the code.
It's probably line 37 in the main file. You should change printlist(node) to printnod(node). That ought to fix it.
i am trying to find out how the Number of expected bytes is calculated with Function Code 2 in Modbus RTU. I am querying registers from 0 to 71, but as a response i am getting expected bytes as 9 Below is the Query and response. query : 33 02 00 00 00 47 3C 2A resp : 33 020900 08 00 FE FF FF FF FF 03 FA 68
You queried for 71 bits, the response has 9 bytes containing 8 bits per byte, any excess bits are ignored.
i am trying to find out how the Number of expected bytes is calculated with Function Code 2 in Modbus RTU. I am querying registers from 0 to 71, but as a response i am getting expected bytes as 9 Below is the Query and response. query : 33 02 00 00 00 47 3C 2A resp : 33 020900 08 00 FE FF FF FF FF 03 FA 68
You queried for 71 bits, the response has 9 bytes containing 8 bits per byte, any excess bits are ignored.
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.Closed2 years ago.Improve this question This is my code. When i run the code it sends me an error: ``` helloworld.c:8:16: error: storage size of 'bin' isn't constant static int bin[size]; ``` but when i do a build the exe works. Help pls.
The initializer of a static variable must be known at compilation time. That's why the declaration ofbinis rejected. Instead you need to declarebinas a pointer to an integer and allocate memory dynamically, that is at run-time: ``` int *bin = malloc(size * sizeof *bin); ``` As pointed out by rioV8, you should also free the allocated memory withfree(bin)when you are done withbin.
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.Closed2 years ago.Improve this question my teacher gave me this program for assignment. I did my assignment but cant understood why this output came. can you please explain this prog. or output. #include<stdio.h> #define scanf "%sABCDE" ``` int main(){ printf(scanf,scanf); return 0; } ``` Output- ``` -->./main -->%sABCDEABCDE ```
Macros are just text replacement (info for nitpickers: I know about tokens). Macros are processed before compilation (thus term preprocessing), The compiler is compiling the code after all the macros are replaced: ``` int main(){ printf("%sABCDE","%sABCDE"); return 0; } ``` I think that now everything is clear.
Is it required, or recommended, that every pointer in C be allocated on the heap? For example, is it likely or possible that the following code could produce a segmentation fault? ``` #include <stdio.h> int main(void) { int* p; *p = 16; printf("Pointer p = %d\n", *p); return 0; } ```
This code will likely segfault becausepis uninitialized and therefore doesn't point to a valid address. A pointer doesn't necessarily have to point to heap memory. It just needs to point to a valid object. For example: ``` int x = 4; int *p = &x; *p = 5; printf("x=%d\n", x); // prints 5 ```
i want to set rise the priority and the affinity of irq processes (spi, gpiod) in linux, from a program written in C/C++. To set the priority of my own process I usepthread_setschedparamto set the affinity of my own process I usepthread_setaffinity_np. I use pthread_self() for this functions. However especially the gpio irqs are tricky because they only are created aftergpiod_line_request_rising_edge_events[1] is called. Until now I just use a shell command similar tochrt -f -p 90 $(pgrep myGpio)to give the irqs higher prioritys on my system I could just put that in asystem("..")function but there should be a better solution which I just do not know. Thank you in Advance [1]https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/tree/include/gpiod.h#n499
I solved it by using libprocps. It is possible to get the pid of the irq via the name of the gpio or of the spi device and then to set the cpu affinity/priority of the irq.
Trying to do a rank based voting algorithm. Rank tells order of voter preference. For example if rank is 0, this is the first choice of the voter. I'm trying to save the order of names to the array but it doesn't work. Error is at the ranks[rank] = name; ``` bool vote(int rank, string name, int ranks[]) { for (int i = 0; i < candidate_count; i++) { if (strcmp(name, candidates[i]) == 0) { ranks[rank] = name; printf("rank was successfuly recorded"); return true } } // TODO return false; } ```
Your are trying to store a String value in int array. Either change the type of ranks array to String or change type of name to int.