question
stringlengths
25
894
answer
stringlengths
4
863
I saw the following line of codeherein C. ``` int mask = ~0; ``` I have printed the value ofmaskin C and C++. It always prints-1. So I do have some questions: Why assigning value~0to themaskvariable?What is the purpose of~0?Can we use-1instead of~0?
It's a portable way to set all the binary bits in an integer to 1 bits without having to know how many bits are in the integer on the current architecture.
I've created a SDL2 based project, that after the building proccess creates a prog.exe file.Sending the project to other systems creates an error:ERROR: The program can't start because SDL2.dll is missing from your computer.Which makes sense, because they didn't install sdl to begin with.Is there a way for me to send them the .exe file that already has all the needed libraries, without making them to install SDL by themselves?Thanks.
You can take sdl2.dll from your computer and copy that to the same directory on the other computer as you have the .exe in. Typically an installer for your application would handle this.
I have the following C code which works: ``` int ex(unsigned int x) { int mask = 0x55555555; int a = ((x >> 0) & mask ); return a + ((x >> 1) & mask ); } ``` However, when I expand it to this, I get a different result: ``` int ex(unsigned int x) { int mask = 0x55555555; int a = ((x >> 0) & mask ); int b = ((x >> 1) & mask ); return a + b; } ``` What is the reason for this difference? EDIT: Note, I'm compiling this for 32bit.
What is the reason for this difference? The 1stsnippet returns the result of adding twounsigneds with the result being (implicitly) converted to anint. The 2ndsnippet returns the result of adding twoints . More on "The Usual Arithmetic Conversions": Usual arithmetic conversions in C : Whats the rationale behind this particular ruleC usual arithmetic conversionsImplicit integer type conversion in C
I´m getting a string like this from C socketrecvfunction and would like ideas how to process it and get numeric values that comes beside the letters(S,L,E...) on the string ``` S@AB@L1550 @W >E0578A9069C0000 >S0223W0418 >R2219H1429S0000 >G0156V0116T1800 >m0138 >m0087 ``` For example letter, need to get the numeric 223 and the same to others; Was thinking to do a loop and read all vector and checking the key words. But not sure if has some way easier or faster
I will explain the general idea and let you write the code by yourself. Create a char buffer which contains the entire string.Create another char buffer at the size of 5, the number of digits in each number - call it digits_char_array.Run in a loop over the char buffer and if the current char is a letter, copy the follwoing 4 chars to digits_char_array. You can use strncpy or memcpy.Convert digits_char_array by using an appropriate function, such asatol
From what I know, when you have multiple conditions in while or if-statements, all of them have to be true in order for the codeblock underneath to run. My question is; Is it possible to have multiple conditions, but the codeblock underneath runs if any of those stated conditions are true? Meaning that one, two or all of them could be true and the while/if statement will be true? Specifically in C.
The thing You say happens when You use the "and" (&&) operator to connect conditions.Whith this operator all the conditions that you connect with && have to be all true to the total condition to be true.Instead,you can use the "or" (||) logic operator to evaluate the conditions and with only one true condition , the total condition will be true.
This question already has answers here:What does (void)var actually do?(4 answers)Closed5 years ago. It may not be clear from the title. I came across the following code in an embedded STM32 project. I don't understand the line inside the function. ``` static void txend1(UARTDriver *uartp) { (void)uartp; // what does this do? Is it a statement? } ``` I've tried searching elsewhere online, but most results are casting pointers to void pointers, which I don't think this is. Thanks for the help!
this is just aportable way to suppress the warningon this unuseduartparameter. It has no effect, but compilers see that as used, and don't issue any warning. Very useful when the prototype of the function is imposed / cannot be changed (callback function) but your implementation doesn't need this parameter. (note thatgccfavors the__attribute__((unused))construct, easier to understand, but not compatible with all compilers)
Is it possible to run the cplex presolver to aggregate a problem without invoking the the mip solver? If it is, could you provide an example using the c callable library?
Yes, it's possible to call presolve independently. The function you're looking for isCPXpresolve. The example given in the documentation is: status = CPXpresolve (env, lp, CPX_ALG_DUAL); You may also be interested inCPXpreslvwrite. Here's the example for that (also from the documentation): status = CPXpreslvwrite (env, lp, "myfile.pre", &objoff); If you write out the presolved problem, as above, you can read it back in with CPXreadcopyprob. This will allow you to work with the presolved problem directly.
I am trying to print the output as ``` func 1 ---------------1 func 2 -------2 func 1 ---------------1 func 2 -------2 ``` indefinetly. But I am gettingsegmentation fault core(dumped)after the program executes for some time. Why is my gcc compiler showing this error? ``` #include<stdio.h> int i=2; int main(int argc, char *argv[]){ func1(); func2(); return 0; } void func1(){ printf("\n func 1 ---------------%d",i); i=2; func2(); } void func2(){ printf("\nfunc 2 -------%d",i); i=1; func1(); } ```
The compiler does not throw a segmentation fault, your program does. Your program callsfunc1()andfunc2()infinite amount of times, causing it to blow up, since the stack size will be exceeded (thus the segmentation fault will happen).
I am trying to print the output as ``` func 1 ---------------1 func 2 -------2 func 1 ---------------1 func 2 -------2 ``` indefinetly. But I am gettingsegmentation fault core(dumped)after the program executes for some time. Why is my gcc compiler showing this error? ``` #include<stdio.h> int i=2; int main(int argc, char *argv[]){ func1(); func2(); return 0; } void func1(){ printf("\n func 1 ---------------%d",i); i=2; func2(); } void func2(){ printf("\nfunc 2 -------%d",i); i=1; func1(); } ```
The compiler does not throw a segmentation fault, your program does. Your program callsfunc1()andfunc2()infinite amount of times, causing it to blow up, since the stack size will be exceeded (thus the segmentation fault will happen).
I can change Project Character Set to Unicode or to Multi-Byte in Microsoft visual studio like what is shown in the picture. But, is the same thing possible inclion?
All that this setting does is automatically set a preprocessor symbol. Either/D UNICODEor/D _MBCSor nothing. It is the kind of setting you decide on very early and never change again. With a bias towards Unicode, it doesn't make much sense to write C++ code and intentionally slow it down by using the Ansi adapter functions. Visual Studio basically only has this setting because there are so many codebases out there that started life 20+ years ago, back when character sets still seemed a practical idea and Win9x was still popular. Those days are over.
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.Closed5 years ago.Improve this question Leonardo number ``` L(x)= { 1 if x=0 1 if x=1 L(x-1)+L(x-2)+1 if x>1 } ``` If x>1, what logic can I apply to find out the Leonardo number?
In your functionL(int x) Ifxis 0 or 1 return 1; Ifxis greater than 1 return L(x-1) + L(x-2) + 1; What I am doing usingL(x - 1)is calling the function for the valuex - 1and the value will be evaluated directly as 1 if it is 0 or 1, otherwise it call again for(x - 1) - 1i.e.x - 2and the process repeats. Same is the case for callingL(x - 2). This is the logic, without the entire code. For more information on this kind of logic, try searching for Recursion.
I need to use an unix library on my windows but I don't know how to do that. With my linux this is working fine ``` #include <pthread.h> ``` But with my windows there is no such file or directory. Do you know where I can find the library ? Also, I'm using code blocks because I'm not on w10 so I can't get bash there. Thanks for your help.
Windows does not have native support for pthreads. Compatibility libraries do exist, e.g.https://sourceware.org/pthreads-win32/but I have never tried to use any of them and don't know how good they are.
I am trying to write content in a file from terminal. File is creating but content is not written into the file. ``` #include<stdio.h> #include<stdlib.h> #include<math.h> int main(int argc, char *argv[]) { FILE *fp; fp=fopen(argv[1],"w"); char ch; while((ch=getchar())!=EOF) { putc(ch,fp); } fclose(fp); return 0; } ```
If you don't signal EOF (Ctrl+Zin Windows andCtrl+Din Linux), then the loop will continue to execute until it receives that signal. If you attempt to read the file with your own eyes while the program is still on execution, then the file stream will not have close (fclose(fp);will not have execute), thus the file will appear to you empty, even though the content will be shown to you, when the file stream closes.
This question already has answers here:Passing an Array by reference in C(5 answers)Closed5 years ago. I wanted to know that while passing an array to a function in c. Is it the copy of array values that get passes or the array address(reference) that gets passed?
When a array is passed as an argument to function it is implicitly decays to a pointes for example ``` char * foo(char buffer[]) { printf("sizeof buff= %d",buffer); // here you will get pointer size not original buf because buffer is decay to pointer as char *buffer } int main() { char buf[10]="hello"; foo(buf); } ``` Reason why it decays to pointer is time .It is more costly for copying all the element in the arrays to the calling function parameter. So implicitly it decays to pointer.
This question already has answers here:What double negation does in C(5 answers)Closed5 years ago. I review thecoreutils's source tree then i found the code below which confuse me a little. (at coreutils-8.23/lib/getopt.c line 237) ``` d->__posixly_correct = posixly_correct || !!getenv ("POSIXLY_CORRECT"); ``` the using of '!' was reversing the logical state of its operand, if A was true, the !A was false, so !!A true again. I don't understand the intention of the author.
This is generally done to force the return into either a1or a0. If something returns either0orNULL, then the final state of!!<expression>will be0and therebyfalse. If something returns anything other than0orNULL, then the final state will be1and therebytrue Further reference here.
Am I allowed to do this inC99? ``` typedef struct dlNode { dlNode* next, prev; void* datum; } dlNode; const static dlNode head={ .next = &tail, .prev = NULL, .datum = NULL }; const static dlNode tail={ .next = NULL, .prev = &head, .datum = NULL }; ``` I can make my program work without this. It'd just be convenient.
You can. You just have to forward declaretailto get it to work: ``` typedef struct dlNode { struct dlNode* next; struct dlNode* prev; void* datum; } dlNode; const static dlNode tail; const static dlNode head={ .next = &tail, .prev = NULL, .datum = NULL }; const static dlNode tail={ .next = NULL, .prev = &head, .datum = NULL }; ```
I'm trying to use printf to get the following programmatic output: ``` - 20 - 15 - 10 - 5 0 + 5 + 10 + 15 + 20 ``` The key specifications are: The field width is always 4The sign is always left-justifiedThe number is always right-justifiedThe zero has no sign So far I have not been able to come up with a printf statement that will give me the desired results. The closest I have is: ``` for(int i = -20; i <= 20; i+=5) { printf("%-+4d \n", i); } ``` which produces: ``` -20 -15 -10 -5 +0 +5 +10 +15 +20 ``` Is there a way to do this without having to do any cumbersome string manipulation?
``` printf("%c%3d\n", i>0 ? '+' : i<0 ? '-' : ' ', abs(i)); ``` Note the above fails forINT_MIN, but that shouldn't be an issue since your values are only expected to be less than 1000 in magnitude.
While I sendingkill -9command to a program on ubuntu , I want to close other running processes before the program closes.I am trying this with c programming . Could it be something like this? How can I say program if you get KILL command you should do something?
Perthe POSIX standard <signal.h> documentation: ...The following signals shall be supported on all implementations (default actions are explained below the table):Signal Default Action Description .... SIGKILL T Kill (cannot be caught or ignored). Note well the "cannot be caught or ignored". Your process never "sees"SIGKILLas the OS just kills the process without any notice.
I am writing a render script code and I need some utility functions.But when I write those functions and compile I get an error saying that invokable functions must return void. They are enforcing this so that all render script invokable functions can run asynchronously. But is there a way to make the functions non invokable? I want to write functions just for use within my render script.
Make them static, that will prevent them from being invokable by the rs compiler.
How to modify variables passed by value instead of by reference within function in C? ``` void fun_a(int a, int b) { .... } int main() { int x = 5, y = 6; printf("%d, %d", x, y); // 5, 6 fun_a(x, y); // pass by value printf("%d, %d", x, y); // 1, 2 return 0; } ``` How to usefun_ato change variables? Is there any way to do it? Though I know it can change variables by passing references easily.
C does not know about reference. Use pointers instead. ``` void fun_a(int *a, int *b) { *a = 10; *b = 12; } int main() { int x = 5, y = 6; printf("%d, %d\n", x, y); // 5, 6 fun_a(&x, &y); // pass pointer to variable printf("%d, %d\n", x, y); // 10, 12 return 0; } ```
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.Closed6 years ago.Improve this question when I defined a node in linked list I came across this confusion. consider, ``` struct node *current = head; ``` hereheadis pointer to head node. and another way is, ``` struct node *current = (struct node*)malloc(Sizeof(struct node)); current = head; ``` both works the same so what is the difference between them? How is memory allocated in first case?
The difference is that the second version callsmalloc(sizeof(struct node))and loses the returned pointer; i.e. it's a memory leak. You can get the same effect by doing: ``` malloc(sizeof(struct node)); struct node *current = head; ```
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.Closed5 years ago.Improve this question ``` typedef struct Vector2D { float x, y; } Vector2D; void Vector2DZero(Vector2D *pResult) { pResult.x = 0; pResult.y = 0; } ``` In functionVector2DZero, I want to set the values ofxandyto 0 for a vector namedpResult, though I'm not sure how to access the variables in a new function especially with a pointer. (I'm pretty sure what I've done is incorrect). I HAVE to use the functions mentioned. Do I need to use the arrow operator? Please help.
if you want to use dots ``` (*pResult).x = 0; (*pResult).y = 0; ``` otherwide ``` pResult -> x = 0; pResult -> y = 0; ```
I'm converting each lowercase character into uppercase, but it's not replacing in the file. What am I doing wrong? ``` #include <stdio.h> int main() { FILE *file; char ch; file = fopen("file.txt", "r+"); if (file == NULL) { printf("Error"); exit(1); } else { while ((ch = fgetc(file)) != EOF) { if (ch >= 96 && ch <= 123) { ch = ch - 32; putc(ch, file); } } fclose(file); return 0; } } ```
You have to open another file to write. ``` fileOut = fopen("fileOut.txt", "w"); ``` chmust be integer. ``` int ch; ``` Check men page like this. ``` #man fgetc ``` And: ``` putc(ch,fileOut); ``` should be out ofifblock.
My logic is enterednumstore intotempvariable and find factorial usingtemp = temp * (num - i)insidewhileuntilnumis greater than0and initiallyi = 1, but I get problem that my loop goes in to infinite loop how to solve this problem ? ``` #include <stdio.h> int main() { int num, temp, i; printf("Enter a Num who's factorial is need to be find : "); scanf("%d", &num); printf("num = %d\n", num); temp = num; printf("temp = %d\n", temp); i = 1; while (num > 0) { temp = temp * (num - i); i++; printf(" i = %d\n ", i); } printf("fact = %d \n ", temp); return 0; } ```
Here you are checkingnum > 0but never updating value of numinsidethe loop Update it to checknum - i > 0ornum > i ``` while(num - i > 0) { temp = temp * (num-i); i++; printf(" i = %d\n ",i); } ```
``` #include <stdio.h> //Compiler version gcc 6.3.0 int main() { float da,hra,s,gs; scanf("%f",&s); da=40/100*s; hra=20/100*s; gs=s+da+hra; printf("%f",gs); return 0; } ``` For example if i entered 25000 for s then output must be 40000 but it showing 25000.000000.
Try the fix below. Note the40.0and20.0instead of40and20. The issue is that you were doing integer division.40 / 100 == 0, sodawas always0. Using40.0 / 100instead gives you floating point division and the value0.4, which is what you want to make your calculations correct. (The same holds for the computation ofhra.) ``` #include <stdio.h> int main() { float da, hra, s, gs; scanf("%f", &s); da = 40.0 / 100 * s; hra = 20.0 / 100 * s; gs = s + da + hra; printf("%f", gs); return 0; } ```
Is there a way to get the static address of a function pointed byllvm::Functionobject in a C code using the LLVM IR API?
Sincellvm::Function*is a subclass ofllvm::Value*you can just treat as anllvm::Value*and LLVM will substitute the correct address. llvm::Function Documentation
This question already has answers here:scanf() variable length specifier(4 answers)Closed6 years ago. Usually, I use a define for the size of a string, but when I usescanf(), I want to guard the function from reading too many characters (and reserve space for the null-terminator). I was wondering whether I could do this using my define, instead of a hardcoded magic number... ``` #include <stdio.h> #define MAXLEN 4 int main(void) { char a[MAXLEN]; scanf("%3s", a); // Can I do that with 'MAXLEN' somehow? } ``` Is it possible? If yes, how?
Use defines to stringify: ``` #define LENSTR_(x) #x #define LENSTR(x) LENSTR_(x) ``` then you can use: ``` #define MAXLEN 3 char a[MAXLEN + 1]; scanf("%" LENSTR(MAXLEN) "s", a); ```
I would like to know if there is a way to store the things that system prints out when you call some function from it for e.g. i want my program to read my Wi-Fi key/everything that comes out of console and store it in a .txt file.Is that possible? If not is printing out strings from system possible? Here is the code for printing out the contents: ``` #include <stdio.h> int main() { system("netsh wlan show profile wifi name key=clear"); return 0; } ```
I figured it out using a much simpler way than @Ratul Sharker and @Basile Straynkevitch suggested. The solution is using>in the system, but you must have a .txt file before compilation(might figure out a way for the program to write the file) Code: ``` #include <stdio.h> int main() { system("netsh wlan show profile wifi name key=clear > C:\\somepath\\name.txt"); return 0; } ```
Whatever program I run Valgrind tells me that there are 72 possibly lost bytes in 3 blocks, even with a simple program like: ``` int main(void) { printf("Hello, World!\n"); return 0; } ``` Do you know if this is a Valgrind bug on Mac OS sierra? How could I leak memory with a program like this?
That can very likely happen, if any of the preloaded libraries (e.g. viaLD_PRELOAD), or any parts of the linked C runtime have memory leaks. There are also a couple of memory allocations performed by the CRT which are never freed on purpose, but typically these are only a one-time thing and only happen once per process. Valgrind can not reliably distinguish between what's part of your application at what isn't. You can only check the stack trace from where the memory was allocated, and decide whether that is your domain or not.
I need to print.5as0.5using theprintfstatement in C language. It can be done easily using the following code. ``` printf("%03f", myfloatvalue); ``` But the situation ismyfloatvalueis dynamic. So i am not sure whether it is a 3 character number, it could be.5or.56or.567. In the above cases i need to print as0.5,0.56, and0.567.
%gdoes print the shortest possible representation of a float. ``` printf("%g",myfloatvalue); ```
My logic is enterednumstore intotempvariable and find factorial usingtemp = temp * (num - i)insidewhileuntilnumis greater than0and initiallyi = 1, but I get problem that my loop goes in to infinite loop how to solve this problem ? ``` #include <stdio.h> int main() { int num, temp, i; printf("Enter a Num who's factorial is need to be find : "); scanf("%d", &num); printf("num = %d\n", num); temp = num; printf("temp = %d\n", temp); i = 1; while (num > 0) { temp = temp * (num - i); i++; printf(" i = %d\n ", i); } printf("fact = %d \n ", temp); return 0; } ```
Here you are checkingnum > 0but never updating value of numinsidethe loop Update it to checknum - i > 0ornum > i ``` while(num - i > 0) { temp = temp * (num-i); i++; printf(" i = %d\n ",i); } ```
``` #include <stdio.h> //Compiler version gcc 6.3.0 int main() { float da,hra,s,gs; scanf("%f",&s); da=40/100*s; hra=20/100*s; gs=s+da+hra; printf("%f",gs); return 0; } ``` For example if i entered 25000 for s then output must be 40000 but it showing 25000.000000.
Try the fix below. Note the40.0and20.0instead of40and20. The issue is that you were doing integer division.40 / 100 == 0, sodawas always0. Using40.0 / 100instead gives you floating point division and the value0.4, which is what you want to make your calculations correct. (The same holds for the computation ofhra.) ``` #include <stdio.h> int main() { float da, hra, s, gs; scanf("%f", &s); da = 40.0 / 100 * s; hra = 20.0 / 100 * s; gs = s + da + hra; printf("%f", gs); return 0; } ```
Is there a way to get the static address of a function pointed byllvm::Functionobject in a C code using the LLVM IR API?
Sincellvm::Function*is a subclass ofllvm::Value*you can just treat as anllvm::Value*and LLVM will substitute the correct address. llvm::Function Documentation
This question already has answers here:scanf() variable length specifier(4 answers)Closed6 years ago. Usually, I use a define for the size of a string, but when I usescanf(), I want to guard the function from reading too many characters (and reserve space for the null-terminator). I was wondering whether I could do this using my define, instead of a hardcoded magic number... ``` #include <stdio.h> #define MAXLEN 4 int main(void) { char a[MAXLEN]; scanf("%3s", a); // Can I do that with 'MAXLEN' somehow? } ``` Is it possible? If yes, how?
Use defines to stringify: ``` #define LENSTR_(x) #x #define LENSTR(x) LENSTR_(x) ``` then you can use: ``` #define MAXLEN 3 char a[MAXLEN + 1]; scanf("%" LENSTR(MAXLEN) "s", a); ```
I would like to know if there is a way to store the things that system prints out when you call some function from it for e.g. i want my program to read my Wi-Fi key/everything that comes out of console and store it in a .txt file.Is that possible? If not is printing out strings from system possible? Here is the code for printing out the contents: ``` #include <stdio.h> int main() { system("netsh wlan show profile wifi name key=clear"); return 0; } ```
I figured it out using a much simpler way than @Ratul Sharker and @Basile Straynkevitch suggested. The solution is using>in the system, but you must have a .txt file before compilation(might figure out a way for the program to write the file) Code: ``` #include <stdio.h> int main() { system("netsh wlan show profile wifi name key=clear > C:\\somepath\\name.txt"); return 0; } ```
Whatever program I run Valgrind tells me that there are 72 possibly lost bytes in 3 blocks, even with a simple program like: ``` int main(void) { printf("Hello, World!\n"); return 0; } ``` Do you know if this is a Valgrind bug on Mac OS sierra? How could I leak memory with a program like this?
That can very likely happen, if any of the preloaded libraries (e.g. viaLD_PRELOAD), or any parts of the linked C runtime have memory leaks. There are also a couple of memory allocations performed by the CRT which are never freed on purpose, but typically these are only a one-time thing and only happen once per process. Valgrind can not reliably distinguish between what's part of your application at what isn't. You can only check the stack trace from where the memory was allocated, and decide whether that is your domain or not.
``` #include<stdio.h> int main() { char *s="Peace"; printf("%s\n",s); printf("%s\n",s+1); printf("%s\n",s++); } ``` Output: ``` Peace eace Peace ``` My query is while I dids++it should have print"eace"instead of"Peace". Why is this happening? Another question ischar *s="Peace";this line stores the string literal in an anonymous array so whenspoints to'P'but when I onlyprintf("%d\n",s);wrote this how could it able to print all the string? shouldn't it print only"P"?
s++is thepost-increment operation. It returns thecurrentvalue ofsthenincrementss. To get what you want you need to usepre-increment,++s.
When I construct a string like this: ``` char string[1] = {'a'}; printf("%s", string) ``` it returns aa4. Why is there a four at the end? How can I get rid of it? I choose this method because I need to make a string from character indexes, such aschar array[4] = {string[i],string[j],string[k]};.
Your string should end with terminating char '\0' You can do it by: ``` char string[2] = {'a','\0'}; ``` Or: ``` char string[] = "a"; ```
I'm having a hard time to understand why I'm getting this compilation warning while using GCC 4.8.4 on Linux: warning: comparison is always true due to limited range of data type [-Wtype-limits] when comparing values like these: ``` uint16_t port_number = 23620; if (ntohs(port_number) >= 0 && ntohs(port_number) <= 1023) { puts("The compiler warns that I will always end up here."); } else { puts("Not reached"); } ``` I understand that the problem is due to the max size supported by each value involved in this comparison. But how can I understand this better and fix it?
ntohsreturns auint16_t. Sinceuint16_tis unsigned, it will always be greater than or equal to0. Therefore,ntohs(port_number) >= 0will always resolve to true. This is why you're getting the warning.
Suppose I receive a list in a volatile environment, where the tail element is only partially filled with accessible items; further, passing on/deleting/dropping the element is a perfectly adequate solution. So, ``` next->A // is unaccessible next->B // is accessible if (next->A) // evaluates to true ``` is there a method to test and pass/delete this list element?
C does not provide a built-in way of testing if a memory location is accessible or not. You cannot check ifnext->Ais available for the same reason that you cannot check if a pointer is "dangling". A fix to this is to add a level of indirection: make a list of "envelope" objects which are always available. Each envelope holds a pointer to the actual object, along with a flag indicating object's accessibility. This way the provider of the list would be able to manipulate the flag independently of the data object itself, without disturbing the content of the list:
This question already has answers here:What does i = (i, ++i, 1) + 1; do?(7 answers)Closed6 years ago. If I write code using comma operator like this: ``` int i; i = 5, i++, i++; ``` does it invoke undefined behavior?
No. It will not invoke undefined behavior as there is a sequence point between evaluation of left and right operands of comma operators. =has higher precedence than that of,operator and therefore5will bind to=as ``` (i = 5), i++, i++; ``` Since operands of comma operator guaranteed to evaluates from left to right,i = 5will be evaluated first andiwill be assigned5, then the second expressioni++will be evaluated andiwill be6and finally the third expression will incrementito7. The above statement is equivalent to ``` i = 5; i++; i++; ```
When I construct a string like this: ``` char string[1] = {'a'}; printf("%s", string) ``` it returns aa4. Why is there a four at the end? How can I get rid of it? I choose this method because I need to make a string from character indexes, such aschar array[4] = {string[i],string[j],string[k]};.
Your string should end with terminating char '\0' You can do it by: ``` char string[2] = {'a','\0'}; ``` Or: ``` char string[] = "a"; ```
I'm having a hard time to understand why I'm getting this compilation warning while using GCC 4.8.4 on Linux: warning: comparison is always true due to limited range of data type [-Wtype-limits] when comparing values like these: ``` uint16_t port_number = 23620; if (ntohs(port_number) >= 0 && ntohs(port_number) <= 1023) { puts("The compiler warns that I will always end up here."); } else { puts("Not reached"); } ``` I understand that the problem is due to the max size supported by each value involved in this comparison. But how can I understand this better and fix it?
ntohsreturns auint16_t. Sinceuint16_tis unsigned, it will always be greater than or equal to0. Therefore,ntohs(port_number) >= 0will always resolve to true. This is why you're getting the warning.
Suppose I receive a list in a volatile environment, where the tail element is only partially filled with accessible items; further, passing on/deleting/dropping the element is a perfectly adequate solution. So, ``` next->A // is unaccessible next->B // is accessible if (next->A) // evaluates to true ``` is there a method to test and pass/delete this list element?
C does not provide a built-in way of testing if a memory location is accessible or not. You cannot check ifnext->Ais available for the same reason that you cannot check if a pointer is "dangling". A fix to this is to add a level of indirection: make a list of "envelope" objects which are always available. Each envelope holds a pointer to the actual object, along with a flag indicating object's accessibility. This way the provider of the list would be able to manipulate the flag independently of the data object itself, without disturbing the content of the list:
My code is below and problem is also explained below with why thelvalueis happening; ``` typedef struct test_item { char id[MENU_NAME_LEN + NULL_SPACE]; MenuFunction function; } test_item; ``` and ``` typedef void (*MenuFunction)(VmSystem *); ``` and ``` void display(VmSystem * system) { printf("test"); } ``` I am able to assign the ID with what I want however when i try to assign the function pointer I get the following errorlvaluerequired as unary&operand ``` test_item test; test.function = &display(system); ```
You meant: ``` test.function = display; ``` The()afterdisplaymeans to call that function. Justdisplaywill evaluate to a pointer to the function. There is no need for&display.
I keep getting this warning c:9:80: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]printf("Char= %c ASCII = %i hex = %x pointer = %p \n", i, i, i , (void*)i ); Code ``` #include<stdio.h> int main (void) { int *i; for (int i = 75; i < 75 + 26; i++) { printf("Char= %c ASCII = %i hex = %x pointer = %p \n", i, i, i , (void*)i ); } return(0); } ```
I fail to see what the question might be that is not answered by the compiler warning. You've got a variable "i" of typeint(32 bit on 64 bit platforms), shadowing another variable called "i" in the main program. You're casting theintvariable tovoid*, and the compiler says you can't do that, because you are 32 bit short. Rename one of the two variables callediin your program to resolve.
This question already has answers here:Convert char array to string use C(3 answers)Closed6 years ago. I want to convert my char array to a string so I can pass it into a function. Say if I have this: ``` char array[3] = {'1', 'a', '/'}; ``` and I want to convert it to ``` char *string = "1a/"; ``` Do I just add a NULL terminator on the end?
Declare your array like this ``` char array[] = {'1', 'a', '/', '\0'}; ``` or ``` char array[] = "1a/"; ```
can anyone tell me why this program is printing 3 as the output or tell the functionality of the program. ``` #include<stdio.h> #include<stdlib.h> struct st { int a; int b; }; void func(struct st*); int main() { struct st ab={128,768}; struct st *pq=&ab; func(pq); return 0; } void func(struct st *p) { char *pt; p->a=768; p->b=128; pt=(char*)p; printf("----%d\n",*(++pt)); } ```
You have stored 768 in first member of struct st, so address at start of struct has 0x00000300(considering 4 bytes of int) in memory, when viewed as little endian stream it will look as 0x00030000 You have stored its pointer in ptr which is char * which now points to value 0x00, ++ptr will point to next value ie 0x03
Suppose I have a Pointer looks like: ``` char *tmp = calloc(1, 500); ``` Then I signed the value into the pointer: ``` char *token = "star"; for(int cur = 0, cur < 500,cur += 50){ strncpy(&tmp[cur], token, 50);//each 50 units will get a value } ``` Now I have a pointer with several values stored. What should I do print out the value one by one? ``` printf("--- %s\n", tmp); // this seems can only print the first one ``` I dont know how to jump or read to the next value, and keeping reading until the whole pointer is printed.
Since you copied null-terminated values into the array using (the corrected code): ``` for (int cur = 0; cur < 500; cur += 50) strncpy(&tmp[cur], token, 50); ``` You can print the values using: ``` for (int cur = 0; cur < 500; cur += 50) printf("--- %s\n", &tmp[cur]); ```
Let's say we have a macro defined as such ``` #define VALUE_ENTRY(a, b, c, d, e, f, g) \ case E_##a##e: temp.a##e = d; break; ``` How does the pre-processor know that the 'e' in 'temp' shouldn't be expanded? Is it due to not having##in front of the 'e'? Also, shouldtemp.a##ebetemp.##a##e?
The preprocessor works on tokens.eby itself is a token, whereas theeintempis just a character that's part of the largertemptoken.##applies only to tokens. Furthermore, pasting must produce a single token. Therefore, pasting.andais not valid;temp.a##eis correct, and pastesaandeto formtemp.<a><e>, where<a>and<e>are the replacement texts ofaande.
I just executed the following code ``` main() { char a = 0xfb; unsigned char b = 0xfb; printf("a=%c,b=%c",a,b); if(a==b) { printf("\nSame"); } else { printf("\nNot Same"); } } ``` For this code I got the answer as a=? b=? Different Why don't I get Same, and what is the value for a and b?
The lineif (a == b)... promotes the characters to integers before comparison, so the signedness of the character affects how that happens. The unsigned character 0xFB becomes the integer 251; the signed character 0xFB becomes the integer -5. Thus, they are unequal.
Apple's LLVM does not warn about this problem, even when-Wallis specified: ``` uint8_t tta; typedef uint32_t TT; TT ttb; ttb= 0xdeadbeef; tta = ttb; // here tta is only 0xEF ``` What can be done to force the compiler to warn about loss of data during assignment?
If you use-Wconversionyou get a warning: ``` <stdin>:9:7: warning: implicit conversion loses integer precision: 'TT' (aka 'unsigned int') to 'uint8_t' (aka 'unsigned char') [-Wconversion] tta = ttb; ~ ^~~ 1 warning generated. ``` This was generated by the current release version of Apple's developer tools: Apple LLVM version 8.1.0 (clang-802.0.42)
This question already has answers here:What does the comma operator , do?(8 answers)Closed6 years ago. ``` #include<stdio.h> int main(void) { int a; a = (1, 2), 3; printf("%d", a); return 0; } ``` output: 2Can any one explain how output is 2?
Can any one explain how output is 2? Because the precedence of theassignment operator(=) is higher than thecomma operator(,). Therefore, the statement: a = (1, 2), 3; is equivalent to: (a = (1, 2)), 3; and the expression(1, 2)evaluates to2.
assuming there's the following code - ``` HANDLE h = CreateFile(L"some_dll.dll", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); HANDLE map = CreateFileMapping(h, NULL, PAGE_READONLY | SEC_IMAGE, 0, 0, NULL); LPVOID res = MapViewOfFileEx(map, 0, 0, 0, 0, 0); ``` Is it possible to extract 'some_dll', given the address it's mapped to, using c++ ? When trying to debug this executable using windbg, it seems that it doesn't extract the module well too
Yes, this is exactly whatGetMappedFileNameis for: Checks whether the specified address is within a memory-mapped file in the address space of the specified process. If so, the function returns the name of the memory-mapped file. PS: there's no reason forwindbgto show the name of a memory mapped file that isn't a loaded module, even if the file happens to be a DLL.
Is this statement correct in C-language? ``` a && b && c ``` I want to check((a==2) && (b==3) && (c==4)).Is this usage of logicalANDcorrect?
Yes, the usage is correct. You can AND as many expressions as you want.
This question already has answers here:uninitialized local variable 'j' used(3 answers)Closed6 years ago. ``` #include <stdio.h> int main() { int x; int counter; while (scanf_s("%d", &x) != 0) { puts("Enter the a signed number : "); if (x % 2 == 0) { counter=counter++; } } printf(" %d pair numbers", counter); } ``` I get uninitialized local variable counter used. The program is supposed to keep asking for numbers until it gets zero and tells us the amount of pairs given.
You need to initialize counter to 0 before trying to increment it. Alsocounter = counter++;is redundant (and undefined!). Just usecounter++
Is this statement correct in C-language? ``` a && b && c ``` I want to check((a==2) && (b==3) && (c==4)).Is this usage of logicalANDcorrect?
Yes, the usage is correct. You can AND as many expressions as you want.
This question already has answers here:uninitialized local variable 'j' used(3 answers)Closed6 years ago. ``` #include <stdio.h> int main() { int x; int counter; while (scanf_s("%d", &x) != 0) { puts("Enter the a signed number : "); if (x % 2 == 0) { counter=counter++; } } printf(" %d pair numbers", counter); } ``` I get uninitialized local variable counter used. The program is supposed to keep asking for numbers until it gets zero and tells us the amount of pairs given.
You need to initialize counter to 0 before trying to increment it. Alsocounter = counter++;is redundant (and undefined!). Just usecounter++
``` #include<stdio.h> int main() { int i, j; for(scanf("%d ",&i); i<=10; i++) printf("%d ",i); return 0; } ``` I am a beginner in the programming world so please help me understand why on compiling the above C code it asks inputs twice.Maybe there's some logic to loop here I might be missing. Please help me understand.Thanks in advance.:)
Change this: ``` scanf("%d ",&i); ``` to this: ``` scanf("%d",&i); ``` Read more inWhat does space in scanf mean?
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.Closed6 years ago.Improve this question The below program when executed is printing ';' as output. I am not understanding why. When I am changing the value of 'c' and 'i', it is sometimes adding those two and sometimes printing symbols like '=' and ';' ``` #include<stdio.h> int main() { char c='1'; int i=10; printf("%c", c|i); } ```
Because49 | 10 = 59and59is the ASCII code of';'.
This question already has answers here:How to initialize a struct in accordance with C programming language standards(16 answers)Closed6 years ago. ``` typedef struct foo{ void (*del)(void *toDel); char* (*p)(void *tp) } Foo; Foo init(char* (*print)(void*),void (*delFunc)(void*)); ``` Trying to figure out how to assign or initialize the supplied parameters to the struct function pointers.
``` Foo init(char* (*print)(void *toBePrinted),void (*delFunc)(void *toBeDeleted)) { return Foo{ .del = delFunc, .p = print}; } ``` What about this? Long form: ``` Foo init(char* (*print)(void *toBePrinted),void (*delFunc)(void *toBeDeleted)) { Foo tmp = { .del = delFunc, .p = print }; return tmp; } ```
In my driver module data is coming in callback function. I want to add data to read callback but not able to find read callback in tty structure
There is no read callback. The tty core buffers the data received by the tty drivers in a structure called struct tty_flip_buffer. ReadChapter 18of LDD3
I want to exchange messages between client and server which are on two different machines. The two machines are directly connected by an Ethernet cable. I can successfully send and receive messages between client and server if they are both on the same machine. What should be the server address in order to have communication between the two machines? ``` serveraddr.sin_addr.s_addr = htonl( ???? ); ``` I've tried runningifconfigon the server machine but just found the MAC address and no IP to assign in the code. Both machines are running DHCP.
Have a look atthe UDP wiki, as you can see, it requires an network layer. This is typically IP. You can set a static IP address to both devices and use these static IP address or you can set up a DHCP server on one of these machines to assign IP addresses automatically.
I'm new to Linux and C and when trying to run a basic "Hello World" script, i kept getting the same two errors. I have confirmed that everything in the program is correct.errors gotten when trying to compile code
You are running thegcccommand from the home directory (~) when thehello.cfile is in~/Documents. Either navigate toDocumentsusingcdbefore runninggccor placehello.cin the home directory.
This question already has answers here:How do get numbers to display as two digits in C?(3 answers)Closed6 years ago. ``` main () { int a; // Dabartine data int b; // Gimimo data int c; printf("Iveskite dabartine data formatu yymmdd:"); scanf("%d", &a); printf("Iveskite savo gimimo data formatu yymmdd:"); scanf("%d", &b); c = a - b; printf("Jusu amzius yra %d metai", c); return 0; } ``` Could someone tell me how to make that in the end the result would be only 2 digits? It is a code to calculate your age accordingly to current date and date of birth. The answer is in yymmdd format and I need to remove the mmdd part and leave only the year part, for example: it prints 180602, and I only need to leave 18(it is the age of person)
You could tryc = (a - b)/10000;That will discard the last 4 digits without rounding up.
I understand that you can easily make a matrix with a fixed length: ``` double m[][2]; ``` However, I want to have a datastructure which is an array, where I store arrays of double type which have different lengths. How do I do that? An example would be: ``` arr1 = {1,2,3,4}; arr2 = {1,2}; ```
Jagged arraysare commonly represented as arrays of pointers to pointers in C: ``` double arr0[] = {4, 1, 7}; double arr1[] = {1, 2, 3, 4}; double arr2[] = {1, 2}; double *m[] = {arr0, arr1, arr2}; ``` Unfortunately, there is no standard syntax for defining inner arrays "in line" with the outer array of pointers. Note that there is no way to find the length of each inner array now, so you need to add some sort of a "marker", or to store lengths separately: ``` #define SIZE(arr) (sizeof(arr)/sizeof(arr[0])) ... size_t len[] = { SIZE(arr0), SIZE(arr1), SIZE(arr2) }; ```
I have this code to retrieve list of opened handlers (mostly FILE) ``` int flags; int fd; char buf[MAXPATHLEN+1] ; int n = 1 ; for (fd = 0; fd < (int) FD_SETSIZE; fd++) { errno = 0; flags = fcntl(fd, F_GETFD, 0); if (flags == -1 && errno) { if (errno != EBADF) { return; } } fcntl(fd , F_GETPATH, buf ) ; printf( "File Descriptor %d number %d in use for: %s",fd,n , buf ) ; ++n ; } ``` However, when i call singlefopenand run this, it prints the same file multiple times (fromntoFD_SETSIZE, wherenis some offset id... first 0 ..nare some system handlers like dev/nul etc.).
Your error check afterfcntl(fd, F_GETFD, 0)is a bit suspect. Assuming your intent is to bail after you hit the first badfd, then the check should beerrno == EBADF. Also, I suggest checking result of your secondfcntlbeforeprintf
This question already has answers here:How to initialize a struct in accordance with C programming language standards(16 answers)Closed6 years ago. ``` typedef struct foo{ void (*del)(void *toDel); char* (*p)(void *tp) } Foo; Foo init(char* (*print)(void*),void (*delFunc)(void*)); ``` Trying to figure out how to assign or initialize the supplied parameters to the struct function pointers.
``` Foo init(char* (*print)(void *toBePrinted),void (*delFunc)(void *toBeDeleted)) { return Foo{ .del = delFunc, .p = print}; } ``` What about this? Long form: ``` Foo init(char* (*print)(void *toBePrinted),void (*delFunc)(void *toBeDeleted)) { Foo tmp = { .del = delFunc, .p = print }; return tmp; } ```
In my driver module data is coming in callback function. I want to add data to read callback but not able to find read callback in tty structure
There is no read callback. The tty core buffers the data received by the tty drivers in a structure called struct tty_flip_buffer. ReadChapter 18of LDD3
I want to exchange messages between client and server which are on two different machines. The two machines are directly connected by an Ethernet cable. I can successfully send and receive messages between client and server if they are both on the same machine. What should be the server address in order to have communication between the two machines? ``` serveraddr.sin_addr.s_addr = htonl( ???? ); ``` I've tried runningifconfigon the server machine but just found the MAC address and no IP to assign in the code. Both machines are running DHCP.
Have a look atthe UDP wiki, as you can see, it requires an network layer. This is typically IP. You can set a static IP address to both devices and use these static IP address or you can set up a DHCP server on one of these machines to assign IP addresses automatically.
I'm new to Linux and C and when trying to run a basic "Hello World" script, i kept getting the same two errors. I have confirmed that everything in the program is correct.errors gotten when trying to compile code
You are running thegcccommand from the home directory (~) when thehello.cfile is in~/Documents. Either navigate toDocumentsusingcdbefore runninggccor placehello.cin the home directory.
This question already has answers here:How do get numbers to display as two digits in C?(3 answers)Closed6 years ago. ``` main () { int a; // Dabartine data int b; // Gimimo data int c; printf("Iveskite dabartine data formatu yymmdd:"); scanf("%d", &a); printf("Iveskite savo gimimo data formatu yymmdd:"); scanf("%d", &b); c = a - b; printf("Jusu amzius yra %d metai", c); return 0; } ``` Could someone tell me how to make that in the end the result would be only 2 digits? It is a code to calculate your age accordingly to current date and date of birth. The answer is in yymmdd format and I need to remove the mmdd part and leave only the year part, for example: it prints 180602, and I only need to leave 18(it is the age of person)
You could tryc = (a - b)/10000;That will discard the last 4 digits without rounding up.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed6 years ago.Improve this question Anytime I try to run a simple C or C++ program in CLion or emacs, no output shows up. EDIT: Using virtual environment, C was not installed properly.
CLion doesn't ship with a C/C++ compiler. You need to install your own compiler, and then set it up with CLion. For windows, you can install: MinGWCygwin(make sure you select gcc-core and g++ during setup) CLion will detect these environments automatically during installation if you set them up in their default locations.
I have this code: ``` void main() { int x; scanf("%d", &x); int array[x]; int i; for(i=0; i<x; i++) { scanf("%d", &array[i]); } int j; for(i=0; i<x-1; i++) { if(array[i]>=array[i+1]) j=array[i]; else j=array[i+1]; } printf("%d", &j); } ``` And I want to print the biggest number in the array. But it always returns a giant random number and I'm struggling to find my mistake here. Any help would be appreciated. Thanks in advance.
You have probably messed upscanfandprintf.scanfrequires a pointer e.gscanf("%d", &j);(in order to change the value of the variable) but in printf you shouldn't pass a pointer soprintf("%d", &j);should beprintf("%d", j);(sinceprintfonly prints the value of the variable and doesn't change it)
This question already has answers here:hello world in C without semicolons and without IF/WHILE/FOR statements [closed](7 answers)Closed6 years ago. I want to display hello world message in c without using semicolon. how can I do that? Is it possible?
Yes, It is possible. ``` #include<stdio.h> int main(){ if(printf("hello world")){} } ```
I found a note in a Software Development Plan: Use of declared types is encouraged. Use of processor dependent types such aschar,int, andlongis discouraged. What is the point of this statement? Why is the use of declared types encouraged? An example of a declared type in this context would beBOOLinstead ofbool.
Data types likeint,long, etc. have a size that is platform dependent. As a result one can discourage the usage of those types, for platform independence... Read more in: integer size in c depends on what?"C variable type sizes are machine dependent." Is it really true? signed & unsigned numbers ;
I am having declaration in C as follows : ``` void abcd(int , char); void main() { extern void abcd(char); abcd (q); } ``` Is it okay to have such code implemented? How C will allow us to code like this? function call to abcd() will take 'q' as a char or as an integer?
C11 6.2.7p2 All declarations that refer to the same object or function shall havecompatible type; otherwise,the behavior is undefined. void abcd(int, char);is an external declaration that saysabcdtakesintandcharas arguments. It is not compatible withextern void abcd(char);, which says that the same function now takes just onecharas an argument. If I read the standard correctly, this is not a constraint error, so a compiler need not produce even awarningfor this. It is still broken and wrong.
I have the following multidimensional char array. I need to firstXORone of the arrays with the mask array and thenANDthe result with the other array. What is the fastest way to implement it? Note: the char arrays can be as large as 20 KB in size. ``` unsigned char test1[2][2] = { { 'a','b' },{ 0 } }; unsigned char test2[2][2] = { { 0 },{ 'O','S' } }; unsigned char mask[2][2] = { 0 }; ```
something like that may be fast: ``` int cnt = sizeof(mask)/sizeof(unsigned char) while(cnt>0) { *((unsigned char*)test1+cnt) ^= *((unsigned char*)mask+cnt); *((unsigned char*)test1+cnt) &= *((unsigned char*)test2+cnt); cnt--; } ``` There is only one time the way through the arrays and you move only 3 pointer wich may be well optimized by the compiler. To be MOST efficient, we must do some tests and see the assembly output. IT also depends on the architecture you use (X86, ARM, AVR, PIC, ...)
This question already has answers here:How can I print a quotation mark in C?(9 answers)Closed6 years ago. How do I store the following into a char array: ``` AT+CIPSTART="TCP","103.6.157.239","8085" ``` When I do the following : ``` char L []="AT+CIPSTART="TCP","103.6.157.239","8085""; ``` I get an error : ../GPRS.c:48: error: expected ',' or ';' before 'TCP'
Try this ``` char c[]="AT+CIPSTART=\"TCP\",\"103.6.157.239\",\"8085\""; ``` Micro controller escape sequences : \? for ?\\ for \\' for '\" for "\b for backspace\n for new line\ooo for octal number\t for horizontal tab\v for vertical tab\xxx for hexadecimal number
I have a really simple c program that I want to compile using gcc, importing from linux kernel headers. ``` #include <stdio.h> #include <stdlib.h> #include <linux/random.h> int main(){ int rand; get_random_bytes(&rand,sizeof(rand)); printf("%d",rand); return 0; } ``` I have tried to compile this program using the following command: ``` gcc rand.c -D__KERNEL__ -isystem /lib/modules/`uname -r`/build/include ``` But I get a bunch of errors (below). What am I missing?: ``` /usr/src/kernels/4.9.8-201.fc25.x86_64/include/linux/linkage.h:7:25: fatal error: asm/linkage.h: No such file or directory #include <asm/linkage.h> ```
From some quick Google searches, it seems likeget_random_bytesmight be a private function only usable from within the kernel. How about you try usinggetrandominstead? Here is the documentation ofgetrandom: http://man7.org/linux/man-pages/man2/getrandom.2.html
I create a variable to store the value of superblock's s_uuid. But I get trouble into how to print this variable like xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx in this form. I tried to use printf in %x and %s to print my variable, but it doesn't work. I want to know how the UUID stores in file system and how I can print it in console instead of wrong encoding.
The s_uuid is defined in the superblock as: u8 s_uuid[16]; In order to print this to the console in the above format: ``` uint8_t s_uuid[16] = {0xf3, 0x58, 0x6b, 0xaf, 0xb5, 0xaa, 0x49, 0xb5, 0x8d, 0x6c, 0x05, 0x69, 0x28, 0x4c, 0x63, 0x9f}; printf("%02x%02x%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n", s_uuid[0], s_uuid[1], s_uuid[2], s_uuid[3], s_uuid[4], s_uuid[5], s_uuid[6], s_uuid[7], s_uuid[8], s_uuid[9], s_uuid[10], s_uuid[11], s_uuid[12], s_uuid[13], s_uuid[14], s_uuid[15]); ```
I am writing a very simple function in C to check if a string is an absolute path or relative path. No matter what I try it is always returning false. Here is what I have tried: ``` int isAbsolute(char *str){ if(strcmp(str,"/")){ return 1; } return 0; } ``` and I call it like: ``` printf("%d\n", isAbsolute("/")); ``` which is returning false every time. Clearly I am missing something obvious but I haven't been able to figure it out...
Don't have access to a compiler, but I think this will work because C-style strings are just arrays with a termination character: ``` int isAbsolute(const char *str){ return (str[0] == '/'); } ```
This question already has answers here:How can I print a quotation mark in C?(9 answers)Closed6 years ago. How do I store the following into a char array: ``` AT+CIPSTART="TCP","103.6.157.239","8085" ``` When I do the following : ``` char L []="AT+CIPSTART="TCP","103.6.157.239","8085""; ``` I get an error : ../GPRS.c:48: error: expected ',' or ';' before 'TCP'
Try this ``` char c[]="AT+CIPSTART=\"TCP\",\"103.6.157.239\",\"8085\""; ``` Micro controller escape sequences : \? for ?\\ for \\' for '\" for "\b for backspace\n for new line\ooo for octal number\t for horizontal tab\v for vertical tab\xxx for hexadecimal number
I have a really simple c program that I want to compile using gcc, importing from linux kernel headers. ``` #include <stdio.h> #include <stdlib.h> #include <linux/random.h> int main(){ int rand; get_random_bytes(&rand,sizeof(rand)); printf("%d",rand); return 0; } ``` I have tried to compile this program using the following command: ``` gcc rand.c -D__KERNEL__ -isystem /lib/modules/`uname -r`/build/include ``` But I get a bunch of errors (below). What am I missing?: ``` /usr/src/kernels/4.9.8-201.fc25.x86_64/include/linux/linkage.h:7:25: fatal error: asm/linkage.h: No such file or directory #include <asm/linkage.h> ```
From some quick Google searches, it seems likeget_random_bytesmight be a private function only usable from within the kernel. How about you try usinggetrandominstead? Here is the documentation ofgetrandom: http://man7.org/linux/man-pages/man2/getrandom.2.html
I create a variable to store the value of superblock's s_uuid. But I get trouble into how to print this variable like xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx in this form. I tried to use printf in %x and %s to print my variable, but it doesn't work. I want to know how the UUID stores in file system and how I can print it in console instead of wrong encoding.
The s_uuid is defined in the superblock as: u8 s_uuid[16]; In order to print this to the console in the above format: ``` uint8_t s_uuid[16] = {0xf3, 0x58, 0x6b, 0xaf, 0xb5, 0xaa, 0x49, 0xb5, 0x8d, 0x6c, 0x05, 0x69, 0x28, 0x4c, 0x63, 0x9f}; printf("%02x%02x%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n", s_uuid[0], s_uuid[1], s_uuid[2], s_uuid[3], s_uuid[4], s_uuid[5], s_uuid[6], s_uuid[7], s_uuid[8], s_uuid[9], s_uuid[10], s_uuid[11], s_uuid[12], s_uuid[13], s_uuid[14], s_uuid[15]); ```
I am writing a very simple function in C to check if a string is an absolute path or relative path. No matter what I try it is always returning false. Here is what I have tried: ``` int isAbsolute(char *str){ if(strcmp(str,"/")){ return 1; } return 0; } ``` and I call it like: ``` printf("%d\n", isAbsolute("/")); ``` which is returning false every time. Clearly I am missing something obvious but I haven't been able to figure it out...
Don't have access to a compiler, but I think this will work because C-style strings are just arrays with a termination character: ``` int isAbsolute(const char *str){ return (str[0] == '/'); } ```
I am trying to understand all this HUGE concept of function pointers... Is it possible to initalize function pointer with non-declared function? For example, a simple use of function pointer would be: ``` void f() { printf("Hello world!"); } //Somewhere in the program void (*foo)(); foo = &f; ``` Is there any way to skip the declaration of f? something like that: ``` void (*foo)(); foo = { printf("Hello world!"); } ```
What you describe are calledlambda functions, a mechanism which is not available in C. You can think of lambda functions as anonymous functions. C++ and C# support that. Read more in .Function pointers, Closures, and Lambda
I saw something similar to this instretchy_buffer.h: ``` #define stb_sb_free(a) ((a) ? free(stb__sbraw(a)),0 : 0) ``` What is the purpose of the,0after the call tofree()? Similarly, there are two curious commas here: ``` #define stb_sb_add(a,n) (stb__sbmaybegrow(a,n), stb__sbn(a)+=(n), &(a)[stb__sbn(a)-(n)]) ``` It seems like it's running multiple statements, but wouldn't that require a semicolon?
What happens in this line ``` #define stb_sb_free(a) ((a) ? free(stb__sbraw(a)),0 : 0) ``` is, ifacorrsponseds totrue, firstfree(stb__sbraw(a))will be executed, then0will be returned due to,0. In general, all expressions which they're separated by comma will be evaluated, but the result has the type and value of the rightmost expression.
I am new in the IDE Code::Blocks, and I accidentally inserted this mark in every line of the code (CR LF), and I want to remove, I'm sure to be a pretty simple thing to fix but I found nothing in the Settings. By the way, what does it mean?
There is a checkbox in Menue "Settings""Editor..."General SettingsEditor SettingsEnd of Line options"show end of line chars"
I have tried several solution answers from the site but unable to understand what is going wrong with this code. I am simply trying to read the file data.txt and print it. The file contains just 12 characters "abcd1234efgh". fd comes out positive but "br" is 0 on executing the read. Please help out if anyone has some clue on this ``` #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> int main(int args,char* vargs[]) { int fd = 0; fd = open("data.txt",O_RDONLY); if(fd<=0) printf("Invalid file name"); else{ off_t fs =lseek(fd, (off_t) 0, SEEK_END); char buf[10]; off_t br = read(fd,buf,10); printf("%s",buf); } return 0; } ```
lseek(fd, 0, SEEK_END); After this file pointer is set at the end of the file, so any further reading is unsuccessful. Just comment this instruction out, or change it to suit your needs.
I am new in the IDE Code::Blocks, and I accidentally inserted this mark in every line of the code (CR LF), and I want to remove, I'm sure to be a pretty simple thing to fix but I found nothing in the Settings. By the way, what does it mean?
There is a checkbox in Menue "Settings""Editor..."General SettingsEditor SettingsEnd of Line options"show end of line chars"
I have two source files that I'm currently compiling into one executable. I usegcc -o ProgramName file1.c file2.c I know gdb requires the-gflag when being compiled but I must be placing it incorrectly. I have tried several things but nothing along the lines of: gcc -g -o ProgramName file1.c file2.cis working for me. When I rungdb->runit says that no executable was found. How do I compile this correctly so it will run in GDB?
The proper command is ``` gdb ProgramName ``` followed by ``` run ``` in the prompt.
On amd64, the following struct has a size of 16 bytes: ``` typedef struct _my_struct { void *a; UINT32 b; UINT16 c; UINT8 d; UINT8 e; } my_struct; ``` But when I put the first three variable in a union as such, the size goes to 24. Why? ``` typedef struct _my_struct { union { struct { void *a; UINT32 b; UINT16 c; } my_inner; struct { void **f; } my_inner2; } UINT8 d; UINT8 e; } my_struct; ```
You're creating a new struct type (my_inner). The compiler adds padding to this struct which makes its size go to 16 bytes (for amd64). Then it adds padding to the outer struct type (my_struct), which makes its size grow to 24 bytes.
I have a NodeJS server running on the same server with a C program. I need to sent a byte array from my NodeJS server to my C program. I have a set_title function in C. ``` set_title(uint16_t *title) ``` Any idea how can I do this ?
You need some form of interprocess communication to be able to do that. There are libraries out there which can facilitate that work for you, have a look atnanomsgandzmqwhich both have both C and JS bindings.
What's the best way to allocate an array on the stack that will be used by several helper functions/macros. Is there anyway to avoid passing pointers around?
No, there is not. You will have to use pointers.
This question already has answers here:Big array gives segmentation error in C(4 answers)Closed6 years ago. I'm new to c ``` int main(int argc,char *argv[]) { char *p[1234567] = { NULL }; return 1; } ``` givesSegmentation fault if I change to 12345, it will work.
An array of 1234567 pointers will be more than 4MB. That is larger than the stack capacity for a thread on many systems. For example, if I recall correctly, on Win32 the address space reserved for a thread's stack defaults to 1MB.
On amd64, the following struct has a size of 16 bytes: ``` typedef struct _my_struct { void *a; UINT32 b; UINT16 c; UINT8 d; UINT8 e; } my_struct; ``` But when I put the first three variable in a union as such, the size goes to 24. Why? ``` typedef struct _my_struct { union { struct { void *a; UINT32 b; UINT16 c; } my_inner; struct { void **f; } my_inner2; } UINT8 d; UINT8 e; } my_struct; ```
You're creating a new struct type (my_inner). The compiler adds padding to this struct which makes its size go to 16 bytes (for amd64). Then it adds padding to the outer struct type (my_struct), which makes its size grow to 24 bytes.
I have a NodeJS server running on the same server with a C program. I need to sent a byte array from my NodeJS server to my C program. I have a set_title function in C. ``` set_title(uint16_t *title) ``` Any idea how can I do this ?
You need some form of interprocess communication to be able to do that. There are libraries out there which can facilitate that work for you, have a look atnanomsgandzmqwhich both have both C and JS bindings.
What's the best way to allocate an array on the stack that will be used by several helper functions/macros. Is there anyway to avoid passing pointers around?
No, there is not. You will have to use pointers.
This question already has answers here:Big array gives segmentation error in C(4 answers)Closed6 years ago. I'm new to c ``` int main(int argc,char *argv[]) { char *p[1234567] = { NULL }; return 1; } ``` givesSegmentation fault if I change to 12345, it will work.
An array of 1234567 pointers will be more than 4MB. That is larger than the stack capacity for a thread on many systems. For example, if I recall correctly, on Win32 the address space reserved for a thread's stack defaults to 1MB.