question
stringlengths
25
894
answer
stringlengths
4
863
I want to check if any of the 1024 bits (128 bytes) are set. If all are clear, then I want to do something. Is it possible to do this quickly, i.e one instruction or do I have to loop through my bitmap?
As i have understood the questions, you want to check if any of the bit is set out of 1024 bits you have. Assuming you are on 64 bit machine. store the bits as array ofunit64_ttype which is8 bytes. So you have array of this kind. ``` uint64_t bits[16] = {0}; // 1024 bits ``` and to check your bit condition ``` for(int i = 0, j=0; i < 16; i++){ if(bits[i]) { return FAIL_CONDITION; } } return SUCCESS_CONDITION; ```
Suppose there is a struct a with other structs as members ``` struct a { struct b* b; struct c* c; }; struct a* a1; ``` Now I allocate memory dynamically to an object of aa1 = (struct a*) malloc(sizeof(a)); Now I similarly create a new object of struct bstruct b* b1 = (struct b*) malloc(sizeof(b)); Now after some time in code I create a reference for b1 in a1 ``` a1.b = b1; b1 = NULL; ``` Later if I free a1, will the memory allocated to b1 also get freed?free(a1);
Later if I free a1, will the memory allocated to b1 also get freed No it will not. The rules are very simple: Exactly onefreefor eachmalloc(assuming we do want to free memory)The address passed tofreemust be exactly what was returned by a previousmalloc. Heremallocof course applies also to any other allocation function such ascalloc,realloc, etc. So in your example the requiredfreecalls are: ``` free(a1.b); free(a1); ```
Thexgettextcommand extracted this.potfrom my .c file: ``` #: src/callbacks.c:171 msgid "" "A new NEC2 input file may not be opened\n" "while the Frequency Loop is running" msgstr "" ``` from here: ``` if( !Nec2_Save_Warn( _("A new NEC2 input file may not be opened\n" "while the Frequency Loop is running")) ) return; ``` Questions: Is it a problem that the first line of msgid is an empty string?Will it affect the ability fordgettextto find the translation when the lines are translated?Other considerations?
This is normal, this is how gettext works with multi-line strings, the first""line isn't an empty string it just says "this is a multi-line string".xgettextdoes this for lines that are too long (that can be controlled by--no-wrap) and for strings withembedded new lines. The translation must be in the same format but other than that, there's no reason to worry.
I'am trying to round a number of a multiply sum but I have no luck with it. I think I'am using the round function wrong. But I can't find anything. ``` int main() { double euro, ats, sum; euro = 414; ats = 13.760; // Umrechnen in Komma sum = euro * ats; printf("Summe = %f\n", sum, lround(sum)); return 0; } ``` My Goal is that the calculation 414 * 13.760 = 5697 rounded.
Your code is passing 2 arguments toprintfand your format expects only 1 (%f). ``` printf("Summe = %f\n", sum, lround(sum)); ``` So you could simply (as Eugene said in the comments): ``` printf("Summe = %.0f\n", sum); ``` In this case you're printing a float rounded to digits after the decimal point (.0). If you really want to uselround, notice that it returns along(some ref). So, you'd better: ``` printf("Summe = %ld\n", lround(sum)); ``` Or check the math.hround,ceilorfloorfunctions too!
What I would like to do is : a simple function "register_function" allowing a user to indicate a callback function to call (that this user has implemented)when calling that function with "call_callback", to be able to pass arguments like a buffer for example Here is my code: ``` static void (*callback)(int *buffer, int size) = NULL; void register_callback(void (*ptr)()) { (*callback) = ptr; } void call_callback(int *buffer, int size) { (*callback)(buffer, size); } ``` The problem is that I have a compile-time error in the register_callback declaration.
Inregister_callback()the assignment is just: ``` void register_callback(void (*ptr)( int *buffer, int size )) { callback = ptr; } ``` Please note that I also added the parameter declarations to the definition ofptrso the compiler can check for the correct function pointer type passed (assuming you have an identical prototype)
this is a snippet from my code. I'm wondering if the pointers I'm using and the way I'm using them is valid. The code works but I need more clarification on how they work. Here's the code: ``` void swapValues(int *x, int *y) { int max; max = *x; *x = *y; *y = max; } ``` The int variablemaxcan be equal to*x? I understand how the*y = max;works but I'm confused in the first one. Can y'all please elaborate it more so that I can grasp how it works.
Assuming you mean ``` max = *x; ``` with*xinstead of*p, then it works basically the same as the assignment ``` *y = max; ``` First the pointerxis dereferenced to get the valuexis pointing to. Then that value is assigned to the (rather badly named)maxvariable.
I am trying to find cube root of the volume and it does not work well. I think there is a problem with the floating point but do not know how to fix it. As you can see cube root should be 3 not 37 ``` #include <stdio.h> int main() { int width; int length; int height; int volume; double volumes; printf("write width "); scanf("%d", &width); printf("write length "); scanf("%d", &length); printf("write height "); scanf("%d", &height); volume = width * length * height; printf("volume is %d \n", volume); volumes = (double)pow((double)volume,1.0/ 3.0); printf("cube root is %f \n", volumes); return 0; } ```
you can use cbrt() function in math.h file ``` #include<math.h> //cbrt(x) to get cube root of x :) printf("cube root is %f \n",cbrt(x)); ```
I have a text file with lines like this: "string maybe contains more than one word - string as the previous - number" I read from this file line by line with fgets, but the sscanf just cut off everything except the first string. How can I solve this problem? ``` char new_name[30], new_district[30], buffer[100]; unsigned new_part_count; while(fgets(buffer, 100, file)) { sscanf(buffer, "%s - %s - %u", new_name, new_district, &new_part_count); } ```
Try the following call ``` sscanf( buffer, "%29[^-] - %29[^-] - %u", new_name, new_district, &new_part_count ); ``` If to use just the conversion specifier%sthen any white space character terminates the input of a string.
``` strcpy(strng, "cd.. "); strcat(strng, "& copy %cd%\\bin\\"); strcat(strng, file); strcat(strng, " %cd%\\txt"); system( strng ); ``` Greetings, I've been working on file handling for C in windows, and unfortunately, I have run into this odd pickle. While I have gotten most of my code to work, including the issue I'm running into previously, "cd.." doesn't seem to be correctly going to the parent directory. Is there any word on why [or a quick and similar fix]? Prior in the program it works in this short line of code: ``` if (numLog > 8) { system("cd.. & cd txt & del *.txt"); return errinit(); }; ```
Your effective string is ``` cd..& copy %cd%\bin\file %cd%\txt ``` Batch parses the entire line, then executes it, so%cd%is evaluated as its valuebeforethecd ..is executed. ``` copy %cd%\..\bin\file %cd%\..\txt ``` should do what you appear to want.
I am working with sockets. On creating one using socket(), we get an integer file descriptor. I then want to read data from this fd. To do so, I was following functioning C code - using the read() syscall, in the following line: ``` read (sockfd /* int */, buff /* char* */, 50); ``` However, compiling gives the error "read was not declared in this scope; did you mean 'fread'?". On simply compiling the given functioning C client code as a C++ file with g++, I get the same errors. The includes in this C++ program are (in-order): iostream, netdb.h, netinet/in.h, stdio.h, stdlib.h, string.h, sys/socket.h, sys/types.h And the std namespace is in use. What am I doing wrong?
You might be missing#include <unistd.h>But I also recommend usingrecv, which is declared insys/socket.h If you're stuck, always try manpages:man read.2
I am working with sockets. On creating one using socket(), we get an integer file descriptor. I then want to read data from this fd. To do so, I was following functioning C code - using the read() syscall, in the following line: ``` read (sockfd /* int */, buff /* char* */, 50); ``` However, compiling gives the error "read was not declared in this scope; did you mean 'fread'?". On simply compiling the given functioning C client code as a C++ file with g++, I get the same errors. The includes in this C++ program are (in-order): iostream, netdb.h, netinet/in.h, stdio.h, stdlib.h, string.h, sys/socket.h, sys/types.h And the std namespace is in use. What am I doing wrong?
You might be missing#include <unistd.h>But I also recommend usingrecv, which is declared insys/socket.h If you're stuck, always try manpages:man read.2
When I was using Linux I used to use Linux namespaces: https://man7.org/linux/man-pages/man7/namespaces.7.html Also on FreeBSD, there are jails: https://www.freebsd.org/cgi/man.cgi?jail I was wondering what the alternative was on macOS 12? I'm new to Macs so I'm just trying to learn the system and any features it might have.
The equivalent feature to FreeBSD'sjailsand linuxnamespacesformacOSis theApp Sandbox. You can find relevant details in theApp Sandbox Design Guide.
I need to write some code that would allow me to read a string that wasinputby a user usingfgets()but the first character is info about what the program should do. For example in the program that i'm writing, ifinput[0] == 'p'i want it to add to a struct the characters that follow it ininput [2]throughinput[4]but every way i've tried to do it has failed. Anyone know how i can separate parts of a string?
``` int startIndex = 2; int lastIndex = 4; char answer[lastIndex - startIndex]; for (int i = startIndex; i <= lastIndex; i++) { answer[i-startIndex] = input[i]; } ``` This grabs every character within the start and last index
I'm currently messing around with printing strings in the console and making them draw functions over time, and while that happened I thought of making the graph more visual by making use of the chars\|/. Obviously, it's not that important, but while writing it down in code ``` oscilated[t]='\'; ``` the compiler immediately starts complaining, probably due to the char having to do with the\0of the string. So my question is if I can print the char another way, or is it really impossible?
You should use an escape sequence. ``` oscilated[t]='\\'; ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closedlast year.Improve this question I just wondered, is there a way to define a macro in C to replace it for certain symbols that I print ? I tried something similar to defining number values, like#define NUMBER 7, but I haven't managed to do the same for characters. Googling hasn't given me a proper answer either. Is something like defining characters by macros even a thing in C ? Thanks for your advice !
I believe this is what you are looking for ``` #include <stdio.h> #define mystr "HELLO WORLD" int main() { printf("%s", mystr); return 0; } ```
Opening a semaphore withsem_openwill also initialize it to any given value, is there any way to open a semaphore that is used by another thread without changing its value?
What you say isn't true. Usingsem_opento open an existing semaphore doesn't change its value. So, to answer you question, ``` sem_t *sem = sem_open( name, O_RDWR ); if ( sem == SEM_FAILED ) { perror( NULL ); exit( EXIT_FAILURE ); } ```
Should readmq_receiveand writemq_sendbe protected by semaphores when accessing a queue in a multiprocess program or is there any sort of protection alredy built in
It's always recomended to read the formal documentation for API you are using. Specifcally formq_receiveandmq_sendthese are: https://man7.org/linux/man-pages/man3/mq_send.3.htmlhttps://man7.org/linux/man-pages/man3/mq_receive.3.html In theatributes sectionyou can see that both these functions arethread safe, meaning you can access them from multiple threads without additional protection.
Should readmq_receiveand writemq_sendbe protected by semaphores when accessing a queue in a multiprocess program or is there any sort of protection alredy built in
It's always recomended to read the formal documentation for API you are using. Specifcally formq_receiveandmq_sendthese are: https://man7.org/linux/man-pages/man3/mq_send.3.htmlhttps://man7.org/linux/man-pages/man3/mq_receive.3.html In theatributes sectionyou can see that both these functions arethread safe, meaning you can access them from multiple threads without additional protection.
I was doing some exercises on the order of execution of operations in C and I came across a case that I did not quite understand. ``` int d = 1; int e = d--/10; // the result of e will be 0; ``` before calculating the value of "e", we decremented the "d" then we did the division. on the other hand in "f", we made the division before decrementing the "d"! ``` int d = 1; int f = 10/d--; // the result of f will be: 10 ``` My question is: why there is a differentiation in the value of "d" used knowing that in both cases the decrementation of "d" is a post-decrement?
There's actually no difference. It usesd=1and does a post-decrement in both cases. The reason you see an apparent difference is that you're doing integer division, which rounds towards 0. That is:(int)1 / (int)10 = 0. See the accepted answer onWhat is the behavior of integer division?
I think the title describes everything, but the story isI'm re-implementing thebzerofunction in c, and that's where I encountered thisaq\0aqby some searching I understood that it has the same role as\0(which is a null character to determine the end of a string)but I'm curious if there's any difference and what is theaq?
what is the aq? It's an artifact left by converting groff (man pages, seeman 7 groff) to html. It should be just'\0'. Seeman bzero. https://github.com/mkerrisk/man-pages/blob/master/man3/bzero.3#L45 by writing zeros (bytes containing \(aq\e0\(aq) to that area.
I want to do something like this in plain C: ``` struct data_msg { uint8_t id = 25; uint8_t data1; uint32_t data2; } ``` I need the id to be set to 25 by default so that when I create an instance of the struct, the id is already set to 25, like this: ``` struct data_msg tmp_msg; printf("ID: %d", tmp_msg.id); // outputs ID: 25 ``` Is there a way to do this in C? I know it can be done in C++, but have not figured a way in C. Doing this in C will throw errors: struct data_msg { uint8_t id = 25; }
Unfortunately, you can't, but if you do this a lot, you could create a constant that you use for initialization: ``` struct data_msg { uint8_t id; uint8_t data1; uint32_t data2; }; const struct data_msg dm_init = {.id = 25}; int main(void) { struct data_msg var = dm_init; // var.id is now 25, data1 = 0, data2 = 0 // ... } ```
I would like to run ansi C unit tests in VS by mean of Test Explorer (not only with Console). I saw that it's possible for C++ projects (https://learn.microsoft.com/it-it/visualstudio/test/writing-unit-tests-for-c-cpp?view=vs-2022), but I can't find any help about writing pure C test in Visual Studio. Is it feasable? And in case how? Thx.
Yes, it is. See myexample. (To avoid LNK2019 error you shall include *.c to your test project, not *.h).
Is there any way to loop array of character pointers? I was able to get the number of items in **args but how to get number of its each element so we can print its characters. As we can see each element column dimension differs. So is there any way in C to loop this? ``` int main() { char *argv_c1[3] = {"cat","f.txt",NULL}; char *argv_c2[2]={"sort",NULL}; char *argv_c3[2]={"uniq",NULL}; char *argv_c4[3]={"grep","day",NULL}; char *argv_c5[3]={"wc","-l",NULL}; char **args[]={argv_c1, argv_c2, argv_c3, argv_c4, argv_c5}; unsigned long int total = sizeof(args)/sizeof(args[0]); printf("ld\n",total); for(int i=0;i<total;i++) { //how to loop argv_c1, argv_c2 ... argv_c5 ? } return 0; } ```
This will loop over the elements ofargs[i]: ``` for(int j=0; args[i][j]!=NULL; j++) ```
``` #include <stdio.h> #include <string.h> int main() { int take_photo = 0; char command[8]; char * pictures = "take_pictures"; strcpy(command, pictures); if (strcmp(command, "take_pictures") == 0) { printf("%s\n", "CLICK_PHOTO_TAKEN"); take_photo = 1; } else { printf("%s\n", "SEG_FAULT_NO_PHOTO"); } return 0; } ``` Can someone tell me why I keep getting aSEGMENTATION FAULTerror? It looks perfectly fine to me Might have something to do with the array
You're getting the segfault at this line: ``` strcpy(command, pictures); ``` The stringcommandis too small. You're trying to copy a long string to it.The behavior is undefined. You can fix this by makingcommandlarger. For example, ``` char command[32]; ```
I want to test my error handling code when using thelibjpegbut I cannot find a suitable call which to produce an error. If I simply pass anullptrto some of the calls expecting a pointer to a structure then the library just crashes. I want to find a statement that calls the set in thejpeg_error_mgr'serror_exitfunction.
I managed to produce an error when callinglibjpeg's functions onjpeg_compress_structorjpeg_decompress_structwithout first calling thejpeg_create_compressorjpeg_create_decompressfunctions respectively.
I'm readingComputer Systems: A Programmer's Perspective. In section 3.8.2 there is an example that says &E[i] - E equals i, assuming E is an array of 4-byte integers. Why isn't the answer 4i?
This is just how pointer arithmetic works in C. Subtracting pointers gives a result in units of elements, not in units of bytes. It's symmetric with the fact that if you want to access element 2 of the arrayE, you useE[2]or*(E+2), notE[8]nor*(E+8).
``` #include <stdio.h> #include <locale.h> #include <wchar.h> int main() { // setlocale("LC_ALL",""); unsigned char utf[]={0xe4,0xb8,0x80,0x0a}; printf("%s",utf); return 0; } ``` The first four bytes of output are correct. The second line in the console is not expected
Your array is missing the null terminator strings require, so printf keeps on printing bytes beyond the end of the array until it happens upon a null byte. (Or when your program crashes due to an out of bounds access.) Add the null byte: ``` unsigned char utf[]={0xe4,0xb8,0x80,0x0a,0x00}; ```
Good day! How do I print each row twice in a 2D array in C program? ``` for(int row = 0; row < 5; row++) { for(int col = 0; col < 5; col++) { printf("%d ", arr[row][col]); } printf("\n"); } ``` The above code is my loop for printing the elements that I received from user.
``` for(int row = 0; row < 5; row++) { for(int col = 0; col < 5; col++) { printf("%d ", arr[row][col]); } for(int col = 0; col < 5; col++) { printf("%d ", arr[row][col]); } printf("\n"); } ``` or you want to use only one loop ``` for(int row = 0; row < 5; row++) { for(int col = 0; col < 5*2; col++) { printf("%d ", arr[row][col%5]); } printf("\n"); } ```
I am working on a program where the main program forks itself and the child process calls exec. I have set it up so that the parent process has 2 pipesStdOutPipeandStdInPipe, and the child process calls dup so thatstdoutwrites to theStdOutPipeandstdinreads fromStdInPipe. Then the parent process calls wait, after which i would like to read the entirety of the StdOutPipe into a buffer. I know you can do so by reading one character at a time, but is there a faster way to do so?
For performance reasons, one typically reads a chunk at a time, not a character at a time. Loop,Attempt to enlarge the buffer so it can fit CHUNK_SIZE more bytes.If an error occurred,Fail.Attempt to read CHUNK_SIZE bytes from the pipe into the unused part of the buffer.If an error occurred,Fail.If EOF was reached,Break.Increased the total number of bytes read by the number of bytes read.
All of my programs before have been working well with C except for today. For some reason I keep getting "expected a type specifier" I am confused why this is not working. ``` #include <stdio.h> printf("Hello World"); // error: expected a type specifer int test = 90; printf("%d", test); // same error here: expected a type specifier // also getting "variable "test" is not a type name" ```
You cannot have statements outside of a function in C. That's what is causing the errors you're seeing. Themainfunction serves at the starting point for a C program, so start by putting the statements in that function. ``` #include <stdio.h> int main() { printf("Hello World"); int test = 90; printf("%d", test); return 0; } ```
``` #include <stdio.h> #include <math.h> int main() { int numbers[5]; printf("Enter your first number:%d"); scanf("%d", numbers[0]); printf("Enter your second number:%d"); scanf("%d", numbers[1]); numbers[3]=numbers[0]+numbers[1]; printf("Your desired result is:%d",numbers[3]); return 0; } ``` I seem to find no problem in the code but it won't even let me input numbers in the array I declared
The issue is in the second argument of scanf. ``` scanf("%d", numbers[0]); ``` it expects an address of where to write your input to but you are passing thevalueof numbers[0]. So scanf will write to whatever is in numbers[0] which is an int, not a pointer. Take the address of numbers[0] by changing it to: ``` scanf("%d", &numbers[0]); ```
When I am trying to get the input for my variable, it is only meeting one of the requirements (ie: the< 1requirement) and skips the other requirement even though im using the&&operator. ``` #include <cs50.h> #include <stdio.h> int main(void) { int x; do { x = get_int("what is the height of the pyramid?:"); } while (x > 0 && x < 8); printf("%i", x); } ``` I tried just using thex < 8for the requirement but it still went through when I entered9,10,11etc.
If you wantxto bebetween0 and 8 (both ends exclusive), then you need to repeatedly ask for input when this condition isnotsatisfied. In other words, whenxis outside this range it meansxis less than or equal to 0ORgreater than or equal to 8. That said, I believe the proper input range for that problem set is actually 1-8 (both ends inclusive): ``` do { x = get_int("What is the height of the pyramid?: ") } while (x < 1 || x > 8); ```
Is applying_Atomictype qualifier to an incomplete type valid? Example: ``` _Atomic void* p; _Atomic struct S* p1; _Atomic struct S x; struct S { int i; }; ``` Invocations: ``` $ gcc t0.c -std=c11 -pedantic -Wall -Wextra -c <nothing> $ clang t0.c -std=c11 -pedantic -Wall -Wextra -c <source>:1:1: error: _Atomic cannot be applied to incomplete type 'void' <source>:2:1: error: _Atomic cannot be applied to incomplete type 'struct S' <source>:3:1: error: _Atomic cannot be applied to incomplete type 'struct S' ``` In the C11 standard (as well as in the C2x draftn2596.pdf) I couldn't find any constraints / semantics, which forbid / restrict applying_Atomicto an incomplete type.
Fromhttps://github.com/llvm/llvm-project/issues/36585: it does appear to be valid
``` #include <stdio.h> int main() { for (int i = 0; i < 10; i++) { printf("%d",i); } } ``` I just wonder why the result of the program whether putreturn 0;on the code or not the result is still correct.
There is no difference. According to the C standard, you can leave outreturn 0;on themain()function (andonly that function) and it will still behave as if there is areturn 0;at the end. The exact wording in the C standard: […]reaching the } that terminates the main function returns a value of 0. From n2346 §5.1.2.2.3 Program termination.
I will divide the question into two parts Part I: Let’s say I have a python classA. And this objectAis pass to a C code. I want the C code to readA.dataandA.index(which are just integers or doubles) and how would I do it? I try usingPyArg_ParseTuplefunction, but it doesn't work well. All I need here is for the C function to read the data and the index inA. ``` #include "Python.h" int function(PyObject *A) { double data; // data <- A.data int index; // index <- A.index // code here } ``` Part II: IfAis now instead a list of objects, how do I readA[0]from it in C code? I have a code like the following: ``` PyObject * read(PyObject *A) { PyObject * out; PyArg_ParseTuple(A[0], "O", out); return out; } ``` But the compiler fails.
UsePyObject_GetAttrorGetAttrString. For iterable objects, usePyObject_GetIter.
I am just checking out some leetcode submissions and came across this assignment for the 2sum soution: ``` int* twoSum(int* nums, int numsSize, int target, int* returnSize){ int* res = calloc((*returnSize = 2), sizeof(int)); ... } ``` Is this saying "res is a pointer to an integer block of memory storing 2 int types initialised to 0" ? So the equivalent of: ``` int* res = calloc(2, sizeof(int)); ``` Or is it something else?
It isn't "taking an assignment operator for size_t" exactly. Rather, it's taking the result of the assignment operation for size_t. For example (a = 2) Puts the value 2 in aandreturns that assigned value. So you could also do something like: ``` int a, b; b = (a = 2); ``` Here,bwould get the result of the operation(a = 2), which is 2. That's what's happening in your case. The first argument passed tocallocis the result of the assignment(*returnSize = 2), which is 2.
Sorry for my bad english. I'm using macOS 12.3 in M1 Pro MacBook Pro I want to know about source code of printf in C standard library. I can find stdio.h file in usr/include directory. But I can't find printf.c or stdio.c file in same directory. And I think Apple Open Source's printf.c is too complicate, dosen't looks like a real code in macOS and dosen't helpful for me. Is that Apple Open Source printf.c code is really used in macOS? https://opensource.apple.com/source/xnu/xnu-201/osfmk/kern/printf.c.auto.html
The newest Apple Open Sourcelibcimplementation ofvfprintf(which is the generic underlying function that plainprintfcalls) can be foundhere on opensource.apple.com. It's about 1400 lines, and yes, it is complex. Some other alternate implementations (which are complex too) are: musl libc: 696 linesGNU glibc: 2289 linesuClibc: 1928 lines
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closedlast year.Improve this question Is there a way to implement the log function witch works for string numbers without converting the string to a int? example of string number: char *stringNumber = "432" the string represents only integers(whole Numbers) but they can be near infinitely long the log should return an int as well(represented as a string) if i result is a float the decimal part should be removed (no rounding) i know that for numbers you can implement: ``` int logn(int n, int x) //n is the number , x is the base { if (n <= r-1)return 0; return (1 + logn(n/x, x); } ``` but for a string i have no idea how to do it
You need to convert the string to a number ``` char * numStr = "2.7"; double num = strtod(numStr, NULL); ```
``` #include<stdio.h> #include<stdlib.h> int main(){ int month, day; printf("Enter the input : "); scanf("%d %d",&month,&day); if (day == 1 && month==1 || month == 2 || month == 3 || month ==4){ printf("Green\n"); } else if(day == 2 && month == 5 || month == 6 || month ==7 || month ==8 ){ printf("Red"); } return 0; } ``` In the above code whenever I choosed = 1andmonth = 1-4, it is supposed to print green which it does correctly. The problem is when I chooseday = 2 & month = 8 or 7 or 6it is supposed to printredbut it is printinggreen. Am I missing something here?
you need to check the day and month diffently. Try this instead: ``` if (day == 1 && (month==1 || month == 2 || month == 3 || month ==4)){ printf("Green\n"); } else if(day == 2 && (month == 5 || month == 6 || month ==7 || month ==8)){ printf("Red"); } ```
I have to install a Chrome extension using C/C++. I tried to copy the whole folder of a extension in C:\Users[login_name]\AppData\Local\Google\Chrome\User Data\Default\Extensions. After copying it I deleted the extension from Chrome and then pasted the extension folder back to its own place but it doesn't get installed. How can I install a Chrome extension without using the Chrome browser? I want to install the extension using C/C++.
Google Chrome supports the following alternative extension installation methods: Using a preferences JSON file (for macOS X and Linux only)Using the Windows registry (for Windows only) source:https://developer.chrome.com/docs/extensions/mv3/external_extensions/
``` #include<stdio.h> #include<stdlib.h> int main(){ int month, day; printf("Enter the input : "); scanf("%d %d",&month,&day); if (day == 1 && month==1 || month == 2 || month == 3 || month ==4){ printf("Green\n"); } else if(day == 2 && month == 5 || month == 6 || month ==7 || month ==8 ){ printf("Red"); } return 0; } ``` In the above code whenever I choosed = 1andmonth = 1-4, it is supposed to print green which it does correctly. The problem is when I chooseday = 2 & month = 8 or 7 or 6it is supposed to printredbut it is printinggreen. Am I missing something here?
you need to check the day and month diffently. Try this instead: ``` if (day == 1 && (month==1 || month == 2 || month == 3 || month ==4)){ printf("Green\n"); } else if(day == 2 && (month == 5 || month == 6 || month ==7 || month ==8)){ printf("Red"); } ```
I have to install a Chrome extension using C/C++. I tried to copy the whole folder of a extension in C:\Users[login_name]\AppData\Local\Google\Chrome\User Data\Default\Extensions. After copying it I deleted the extension from Chrome and then pasted the extension folder back to its own place but it doesn't get installed. How can I install a Chrome extension without using the Chrome browser? I want to install the extension using C/C++.
Google Chrome supports the following alternative extension installation methods: Using a preferences JSON file (for macOS X and Linux only)Using the Windows registry (for Windows only) source:https://developer.chrome.com/docs/extensions/mv3/external_extensions/
I am learning to use fread and fwrite right now. As far as I understand, from the documentation, it just seems to read from or write into a specified number of bytes, but always from the beginning of the file. Is there any way not to have to start at the beginning of the file or am I misunderstanding the functions?
use fseek ``` int fseek(FILE *pointer, long int offset, int position) pointer: pointer to a FILE object that identifies the stream. offset: number of bytes to offset from position position: position from where offset is added. returns: zero if successful, or else it returns a non-zero value SEEK_END : It denotes end of the file. SEEK_SET : It denotes starting of the file. SEEK_CUR : It denotes file pointer’s current position. ```
When I execute the following code, the output is5 6. ``` int main() { int one = 5, two = 6; #ifdef next one = 2; two = 1; #endif printf("%d %d", one, two); return 0; } ``` Definitely the code within#ifdef #endifis not getting excuted. I am unable to understand the utility of the identifiernext. What is the keyword instead ofnextthat will make the compiler execute the code inside the#ifdef #endifsection? reference
You simply define the macro ``` #define next int main() { int one = 5, two = 6; #ifdef next one = 2; two = 1; #endif printf("%d %d", one, two); return 0; } ``` Now the values will change.
When I execute the following C program, the output isi. ``` struct student { char a[5]; }; int main() { struct student s[] = { "hi","hey" }; printf("%c", s[0].a[1]); return 0; } ``` I am unable to understand what is the function of the commandstruct student s[] = { "hi","hey" };Any possible justification will be highly helpful.
The definition ``` struct student s[] = { "hi","hey" }; ``` is equivalent to ``` struct student s[2] = { { "hi" }, { "hey" } }; ``` Sos[0]is the first element of the arrays. Ands[0].a[1]will be the second character ofs[0].a.
Can we useforstatement like that? (C programming language) ``` for(int i = 0,double j = 2; i != j+134; i++, j = j+17); ``` I'm trying to learn linked list and I try to increase the index and set the pointer to next node just by using a singlefor: ``` for(node* current,int i = 0; current!=NULL; current=current->next_node, i++); ```
What about? ``` struct IntDouble { int i; double j; }; for (struct IntDouble q = {0, 2}; q.i != q.j + 134; q.i++, q.j += 17) /* void */; ``` See code "running" athttps://ideone.com/jEXBh7
I tried to include <windows.h> with also <stdio.h> but it shows: tcc: undefined symbol '_MessageBoxA@16' when i use my only Pocket Edition TinyCCompiler. does anybody know why? ``` #include <stdio.h> #include <winapi/windows.h> #include <winapi/winuser.h> /* ooops fell of my chair */ int main() { char name[40]; char age[6]; printf("Enter name:"); scanf("%39s", name); printf("\n"); printf("Enter age:"); scanf("%5s", age); printf("\n"); printf("You: Hello my name is %s, and i'm %s years old.",name,age); printf("\n----------------OTHER PROGRAM----------"); MessageBox(0, "Hello", "Hellodd", 1); return 0; } ```
You need to link with user32: ``` tcc -Wall code.c -luser32 ```
I see a fewin this makefile. eg: ``` $(CC32) -B./obj32 $(LDFLAGS) $(LDFLAGS32) -o $@ $(LDLIBS) -Wl,--hugetlbfs-align $(filter %.o,$^) ``` What does this-Bmean?
That is not a linker switch. If it were a linker switch specifically it would be prefixed with-Wl,telling the GCC front-end to pass that option through to the linker. The-Boption is for the GCC front-end, and you can learn about its options here:https://gcc.gnu.org/onlinedocs/gcc/Invoking-GCC.html Index of options here:https://gcc.gnu.org/onlinedocs/gcc/Option-Index.html The-Boption here:https://gcc.gnu.org/onlinedocs/gcc/Directory-Options.html#index-B
I am not able to understand why the operation 'c | 11100000' does not seem to work. But I also noticed that 'c | 10000000' works as expected. ``` #include <stdio.h> int main() { unsigned char c, c1; c = c & 0; c = c | 11100000; printf("%o \t", c); /** prints 140 ***/ c = c & 0; c = c | 111; c << 5; printf("%o", c); /** prints 157 **/ return 0; } ```
The constant values that you are using are in decimal format, not binary. C doesn't support binary constants, but it does support hex constants: ``` c = c | 0xe0; ... c = c | 0x7; ``` Also, this doesn't do anything: ``` c << 5; ``` Presumably, you want: ``` c = c << 5; ```
``` int main() { int y=2147483647; printf("%d\n",!(~y+~y)); } ``` When i compile it by gcc and run it in ubuntu, the result is 0.but when i compile and run it on vs2022,the result is 1. I can not understand how did the result of 0 come about.
The bitwise inverse of decimal value2147483647/0x7FFFFFFFwill end up as0x80000000. On a 2's complement system like yours, this is equivalent to-2147483648. -2147483648+-2147483648gives an arithmetic underflow ofsigned int, it's undefined behavior and anything can happen. In practice, during optimization the compiler can either make the decision that~y+~yequals zero or that it equals non-zero, it's not well-defined. Fix this by switching all types toint64_t/PRIi64(#include <inttypes.h>).
please see attached image, where the stack and data area are nicely shown in the gdb as text: originally found in herehttps://www.youtube.com/watch?v=KAr2cjLPufA&t=1390sat 24:30 the audio is not good so I didn't get the name for the extension. does somebody know and would be so kind to indicate a source? much appreciated. cheers.
mammon . The guess ishttps://github.com/mammon/gdbinit, see the comments below the video.
I've found trailing '#' characters in the pin description section in some datasheets, which indicates that the specific pin hasactive-lowfunctionality. Is there any conventions for variable names which hold for example pulled up GPIO input pin values?
It is very helpful when translating a schematic to a header file with constants for the pin numbers to name the constants as close as possible to the net names on the schematic. This leaves three problems that I have encountered regularly: Net names with a dash: I just replace this with an underscore.BAT-LEVELbecomesBAT_LEVEL.Net names starting with a digit: I start all the pin numbers with the same prefix:3V3_ENABLEbecomesPIN_3V3_ENABLE.Net names with a slash or hash character or overbar (all of which signify active low). I replace this with a lower-casenin an otherwise all-capitals constant.SPI_CS#becomesSPI_nCS.
I want to pad a column so it's 8 characters wide, and make integers left-aligned with at most one leading zero like this: ``` [00 ] [01 ] [07 ] [11 ] [14 ] ``` I know how to add the leading zeroes (printf("%02d\n", integer)) or the padding (printf("%-8d\n", integer)), but I don't know how to combine the two. Is there an easy way to achieve this?
Specify the minimum field width (8) and the precision (.2) and left-justification (-) — seefprintf()— like this: ``` #include <stdio.h> int main(void) { int array[] = { 0, 1, 7, 11, 14, 314159 }; enum { NUM_ARRAY = sizeof(array) / sizeof(array[0]) }; for (int i = 0; i < NUM_ARRAY; i++) printf("[%-8.2d]\n", array[i]); return 0; } ``` Output (on macOS 12.3): ``` [00 ] [01 ] [07 ] [11 ] [14 ] [314159 ] ``` This seems to be what you want.
As the title asks, do object files have to have the same name as the header file in order to be properly linked? ie. could I have a header file 'foo.h' and call it 'bar.o' and still have it properly link? In source code, I would still need to writeinclude "foo.h"so I speculate that the linker will reject this since the two do not share the same name.
There is nothing that says a particular header file is associated with a particular object file. A header file typically contains only declarations. It doesnotsay anything regarding where the associated definitions reside. You could have two source files such as main.c and foo.c and have both use a header file called common.h. When you compile, you could then create main.o and foo.o and link them together into "myprogram".
I have a simple hello world program, but the .exe is somehow 100kb big. ``` #include <stdio.h> int main() { printf("Hello world"); return 0; } ``` I'm currently using a .bat file to call the commands. ``` @echo off call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" x86 cl /nologo /O2 /W3 ./Main.c /FeHello.exe ``` I am using MSVC compiler from Visual Studio 2019 to compile with the command prompt. Thanks
Large size is caused by linking runtime statically./MDswitch can be used in order to link it dynamically and shrink size of the executable.
I am programming a kernel in C for a custom operating system that I'm making and I was wondering how I could loop for every character in aconst char*and then useifoperators to identify a character in theconst char*to run specific code.
how I could loop for every character in aconst char* Like that: ``` const char *p; for (p = str; *p; p++) { // ... } ``` and then use if operators to identify a character in theconst char*to run specific code. Inside your loop: ``` if (*p == 'x') { // Identify a character // Run the specific code here } ``` Or, if you want to identify a lot of characters: ``` switch (*p) { case 'x': // Run the specific code here break; case 'y': // Run the specific code here break; // ... } ```
This is the C problem and i need your help. I have checked my code lots of time but I can not print out the result. Question: input n and print out S = 1-1/2+1/3-1/4... +-1/n with abs(1/n)>e ``` #include<stdio.h> #include<stdlib.h> #include<math.h> #include<string.h> float checkQ3(int n){ float sum = 0; for(int i = 0; i<= n; i++){ if(i % 2 == 0){ sum += -1/i; }else{ sum += 1/i; } } return sum; } int main(){ int n; printf("Input n: "); scanf("%d",&n); float sum1 = checkQ3(n); printf("%f",sum1); } ``` Then there is no ouput, I have tried so many way but it did not work,please help me.
Yourforloop starts at 0, rather than one resulting in division-by-zero. Edit your code to the following: ``` for(int i = 1; i<= n; i++){ if(i % 2 == 0){ sum += -1/i; }else{ sum += 1/i; } } ```
What's the difference between ``` struct point var, *varptr; ``` and ``` struct point *var; ``` Can we just use the second one without assigning any variable's address to it?
The difference is that this statement creates two variables: ``` struct point var, *varptr; ``` It has the same effect as using 2 statements: ``` struct point var; // type struct point struct point *varptr; // type pointer to struct point ``` And this statement creates 1 variable: ``` struct point *var; // type pointer to struct point ``` Can we just use the second one without assigning any variable's address to it? Yes you can use the second one but you would want to initialize it to something (usually another variable's address) before derefrencing the pointer.
Is there any performance penalty if I attach gdb to a process? I do not set any breakpoint and I'm only waiting for a segfault. Thanks
Is there any performance penalty if I attach gdb to a process? Yes. There are several aspects which slow down when a debugger is attached. One is thread creation / destruction -- GDB needs to keep track of threads, and the pthread library has hooks which GDB sets up. Also GDBalwayssets a few internal breakpoints. One of them is on_dl_debug_state(), and sodlopen()anddlclose()become slower as well. Finally, GDB gets notified by the kernel about any signals the program receives, so any application which handles a lot of signals will run slower.
``` #define BIT(n) ( 1<<(n) ) #define A BIT(0) void main(void) { if(A == 0) { } } ``` I want to see the definition ofA, vs code will jump to#define BIT(n) ( 1<<(n) )I hope vs code jump to#define A BIT(0)there are any way to achive that?
This is aknown bugin the C/C++ extension, which (seems like) will be fixed in the upcoming release 1.10
I am trying to make a kernel which has some functions that print out characters, draw, etc. And these functions will later be linked with assembly. I was wondering if I could still use these functions:strlen()strcpy()strrev()strcmp()strcat()
Anyways, I found this snippet of code from osdev.org, which I am going to build off of, to have thestrlen()function, although I cant find a way to create the other functions that I listed in the title if this question. ``` size_t strlen(const char* str) { size_t len = 0; while (str[len]) len++; return len; } ```
I am currently trying to get my project to work as an executable so I can share it more easily, but the code involved imports some c code to improve speed using the ctypes library. I am using pyinstaller to produce my .exes and it's working fine except with the CDLL ctype function, as in the code below: ``` from ctypes import CDLL import time foo_lib_path = 'theories/foo.so' foo = CDLL(foo_lib_path) print('Mission accomplished') time.sleep(10) ``` When I run this code in my normal environment it works fine but when I compile to exe usingpyinstaller --onefile 'bar.py'orpyinstaller --hidden-import 'theories/foo.so' --onefile 'bar.py'it immediately cuts out. How can I account for importing c libraries in my code?
The solution I eventually found for any future users with the same problem was to add the command--add-binary 'theories/foo.so;.'to--onefileinstead of--hidden-import 'theories/foo.so'.
``` #include <stdio.h> int main () { int row, i, j; printf("Enter a number: "); scanf("%d", &row); for (i=1; i<=row; i++) { for (j=1; j<=row; j++) { if (i==1 || i==row || i+j==row+1) { printf("*"); } else { printf(" "); } } printf("\n"); } printf("\n\n"); } return 0; } ``` The program prints out the letter "Z" out of stars. I have to add a do-while loop in this. (This is for school, you can clearly see that I'm a begginer.)
Perhaps this is what you want: ``` do { printf("Enter a number: "); scanf("%d", &row); if (row < 4) puts("Try again"); } while (row < 4); ```
``` #include <stdio.h> int sum(int n){ int sum = n; while(n>0){ sum += n%10; n /= 10; } return sum; } int main(){ int check,i; int arr[10001]; for(i=1;i<10001;i++){ check = sum(i); if(check<10001) // this code arr[check] = 1; } for(i=1;i<10001;i++){ if(arr[i]!=1) printf("%d\n",i); } } ``` I don't understand why 'if(check<10001)' used
Check out this last 10 outputs made without theif(check<10001) arr[check] = 1;:9990 9991 9993 9994 9995 9996 9997 9998 9999 On the other hand, this one containsif(check<10001) arr[check] = 1;:9903 9914 9925 9927 9938 9949 9960 9971 9982 9993 I assume that the second output is the one you wish to get. As you see, thesum()function would not work as intended withoutif(check<10001) arr[check] = 1;as the "stopper", otherwise it will print everycheckcalculated in theiloop.
``` #include <stdio.h> int main () { int row, i, j; printf("Enter a number: "); scanf("%d", &row); for (i=1; i<=row; i++) { for (j=1; j<=row; j++) { if (i==1 || i==row || i+j==row+1) { printf("*"); } else { printf(" "); } } printf("\n"); } printf("\n\n"); } return 0; } ``` The program prints out the letter "Z" out of stars. I have to add a do-while loop in this. (This is for school, you can clearly see that I'm a begginer.)
Perhaps this is what you want: ``` do { printf("Enter a number: "); scanf("%d", &row); if (row < 4) puts("Try again"); } while (row < 4); ```
``` #include <stdio.h> int sum(int n){ int sum = n; while(n>0){ sum += n%10; n /= 10; } return sum; } int main(){ int check,i; int arr[10001]; for(i=1;i<10001;i++){ check = sum(i); if(check<10001) // this code arr[check] = 1; } for(i=1;i<10001;i++){ if(arr[i]!=1) printf("%d\n",i); } } ``` I don't understand why 'if(check<10001)' used
Check out this last 10 outputs made without theif(check<10001) arr[check] = 1;:9990 9991 9993 9994 9995 9996 9997 9998 9999 On the other hand, this one containsif(check<10001) arr[check] = 1;:9903 9914 9925 9927 9938 9949 9960 9971 9982 9993 I assume that the second output is the one you wish to get. As you see, thesum()function would not work as intended withoutif(check<10001) arr[check] = 1;as the "stopper", otherwise it will print everycheckcalculated in theiloop.
I want to take screenshots from other logon sessions. Taking screenshot from the session that has ran the executable is okay but how can I do this with other sessions ? Note: My executable is going to be executed as administrator.
You can't access UIs from across session boundaries. You will have to run a separate process in the target session, and then that process can capture the screenshot locally and then use an IPC mechanism of your choosing, such as a socket or pipe, to transmit the data to your main process.
I have this code: ``` char *ps = "hello"; scanf("%s", ps); ``` I want to write a string, let's pretend "a", to pointer without using an array. Trying to scanf a string into ps causes errorinterrupted by signal 10: SIGBUS. I'd be happy to hear an explanation for such a behavior.
The pointer points to a string literal ``` char *ps = "hello"; ``` So this call ``` scanf("%s", ps); ``` tries to change a string literal. You may not change string literals. Any attempt to change a string literal results in undefined behavior. From the C Standard (6.4.5 String literals) 7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values.If the program attempts to modify such an array, the behavior is undefined
I have always heard that strings such as "%d:%d:%f" (random example) can cause a buffer overflow, but I never really understood why. Is it when they are used with scanf input, printf, or both? Why does it happen? I have been told this many times but couldn't find examples online.
%d,%dand%fcan hardly result in a buffer overflow if used correctly with correct implementations ofscanfandprintf. But with the%sspecifier you can get very easily a buffer overflow: ``` char string[10]; scanf("%s", string); ``` If the user types more than 9 characters, thestringarray will overflow. Also withsprintfyou can easily get a buffer overflow with any format specifier: ``` char string[4]; sprintf(string, "%d", 1234); ``` Here: thestringarray needs to have 5 characters instead of 4.
I work on vsc with remote-ssh. On local side the code works fine, but in ssh I can only compile the code (gcc program.c -o program -std=c11) but when I run it with.\program I get the error message: bash: .program: command not found What could be the reason and how can I fix it?
Use./program. In Bash, and Unix systems generally, the character to separate file system components is the forward slash, “/”. The backward slash, “\” is used to “escape” characters normal purposes and treat the character literally. So\psays to treat “p” as an ordinary “p”, which it already is. So.\programis equivalent to.program, which requests the shell to execute a file named.program. Since there is no such file, it gives you an error message.
I am making software for windows that uses things like windows api and I really do not like developing on windows. Is there a way to develop software on Linux, for Windows, preferably without virtual machines as my computer is not very powerful, I am using C/C++.
There is probably no universal answer to this. This is how I develop software on Linux that is used mainly on Windows: I use the Qt framework which abstracts away all platform-dependent details in my case.I useMinGW-w64to cross-compile. It works very well with CMake-based projects and the excellentbinaries from Martchus, which also have great support for static builds.I use Wine for testing. However during development I can test and debug the Linux binary. A luxury due to Qt abstraction that fits my needs.
Myschedule->start.hourpoints to the currect element of array. How to make it point to the previous element of array? ``` struct Time { int hour; } start, end; struct Class { struct Time start, end; } schedule[100]; ``` I need to use this inside a function which sets start of current to be equal to end of previous. ``` void add_class(struct Class shedule[]){ schedule->start.hour=schedule*(--).end.hour; }; ```
It seems you need something like the following ``` void add_class( struct Class shedule[], size_t n ) { for ( size_t i = 1; i < n; i++ ) { shedule[i].start.hour = shedule[i-1].end.hour; } //... } ``` and the function is called like ``` add_class( shedule, sizeof( shedule ) / sizeof( *shedule ) ); ``` or like ``` add_class( shedule, 100 ); ```
I've looked at some questions asked here regarding Pascal Triangle, yet I still can't seem to visualize how the algorithm would work. ``` [1] [1 1] [1 2 1] [1 3 3 1] (3 comes from 1 + 2 on the previous row) [1 4 6 4 1] (4 comes from 1 + 3, while 6 comes 3 + 3 on the previous row) etc. ``` I have difficulties in imagining how adding the numbers visually in the triangle (just like how they told you to do it in school) can be implemented through loops. I would really appreciate a detailed answer in helping to bridge this.
do a 2-D array. put1int he first cell, leave that row filled with garbabe ``` [1|g|g|g|... // 1st row (arr[0][0] = 1;) ``` for the second row (and third, ...) start with1at the left, then add the value from the row above ``` [1|g|g|g|... // 1st row [1|g|g|g|... // 2nd row (arr[1][0] = 1;) // (arr[1][1] = arr[1][0] + arr[0][0]) ``` etc...
I have a structure in which there is achar line[20] = "2022/03/13 11:22:33". I have to format this char line as"20220313112233". I am trying like this but getting segmentation fault. ``` for (int i = 0, j; line[i] != '\0'; ++i) { while (! (line[i] >= '0' && line[i] <= '9') && ! (line[i] == '\0')) { for (j = i; line[j] != '\0'; ++j) line[j] = line[j + 1]; line[j] = '\0'; } } ```
Like it's pointed out in comments, use one loop to get the job done: ``` #include <ctype.h> // for isdigit() char line[20] = "2022/03/13 11:22:33"; for (char *ai = line, *zi = line; 1; ++zi) { if (isdigit (*zi)) *ai++ = *zi; else if ('\0' == *zi) { *ai = '\0'; break; } } printf ("\n%s\n", line); ```
I have a structure in which there is achar line[20] = "2022/03/13 11:22:33". I have to format this char line as"20220313112233". I am trying like this but getting segmentation fault. ``` for (int i = 0, j; line[i] != '\0'; ++i) { while (! (line[i] >= '0' && line[i] <= '9') && ! (line[i] == '\0')) { for (j = i; line[j] != '\0'; ++j) line[j] = line[j + 1]; line[j] = '\0'; } } ```
Like it's pointed out in comments, use one loop to get the job done: ``` #include <ctype.h> // for isdigit() char line[20] = "2022/03/13 11:22:33"; for (char *ai = line, *zi = line; 1; ++zi) { if (isdigit (*zi)) *ai++ = *zi; else if ('\0' == *zi) { *ai = '\0'; break; } } printf ("\n%s\n", line); ```
I'm having some issues withrealloc, for example, this code ``` char *s = (char*)malloc(sizeof(char)*17); s = "bruhbruhlmaolmao"; s = (char*)realloc(s, sizeof(char)*18); if(s == NULL) printf("Memory allocation failed"); else printf("%s\n",s); ``` I'm trying to reallocate the memory chunk that s is pointing at to a larger memory location in the heap. I've compiled it and the compiler returns no warning. When I run the executable, It prints out nothing. I hope you can explain to me why and how to fix it
Well, apparently I made a dumb decision by assigningsto a string:s = "bruhbruhlmaolmao";, what I should really do is use something instring.hlibrary likestrcpy
What isCHAR_BIT==16means in this code? It doesn't compile, I can not figure out the reason and what will be in puts so code will compile? ``` #include <stdio.h> #include <stdlib.h> #include <assert.h> static_assert(CHAR_BIT==16,"16 bit falsely assumed"); int main() { puts("hello world this"); return 0; } ```
CHAR_BITis a Macro defined inlimits.h. It mentions the number of bits in achar. Most systems use 8 bits, but there are architectures with less (7 bits) or more. In your code, the assert is checking, if the system is using 16 bits for achar, then only the code will compile. Note: Based on your compiler version and support, you may need to use_Static_assertinstead.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closedlast year.Improve this question I convert string to unsigned long like this code. ``` String t = "1667451600"; unsigned long ret; ret = strtoul(t,NULL,10); ``` It show error like this. ``` test:122:19: error: cannot convert 'String' to 'const char*' 122 | ret = strtoul(t,NULL,10); | ^ | | | String exit status 1 cannot convert 'String' to 'const char*' ``` How to canvert string to unsigned long in C ?
Stringis not a standard type in C. Try this: ``` char *t = "1667451600"; unsigned long ret; ret = strtoul(t,NULL,10); ```
If I have code like this ``` struct s { int x; char b[]; }; int main() { struct s s[10]; } ``` and I compile with "gcc -O2 -W -Wall -pedantic" then I get: ``` <source>:4:14: warning: invalid use of structure with flexible array member [-Wpedantic] 4 | struct s s[10]; | ^ ``` And gcc is totally right. Structs with flexible array members can't work like that. Where in the C/C++ standards is this defined?
In C, it's §6.7.2.1, paragraph 3: A structure or union shall not contain a member with incomplete or function type,… except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array. As@phuclvpoints out in acomment, C++ doesn't have this feature.
After I download the CLion, I configure MinGW-64 also. I've tried almost everything online, and they're surprisingly consistent, but they still don't solve my problem. I know it's just a simple configuration issue, but I spent the whole day and still couldn't solve it. Can someone help me? I'd appreciate it.
In order to compile the c/c++ file, none ofCygwinandMinGWcan be ignore! Thanks for the brother's (@long.kl) suggest! just do as follows pictures, your c/c++ compile can work too. Note that the order
I am in a project and I have to comply with ISO26262 so I need to verify my CAN frame. I am going to check my frame using the CRC calculation. My question is: Should I do this calculation in my program or does the CAN protocol already do it automatically?
Actually, you might not just rely on the CAN CRC itself in the case of ISO26262. Because, the E2E protection (as it is called in AUTOSAR) consisting of CRC + SeqCounter, are done between two SWCs, in an ASIL-context. The BSW is usually not ASIL. So, between the SWC providing the data to the BSW, and the receiving SWC checking the CRC, anything could happen in between. So, your BSW could put some flipped data into the CAN HW mailbox. The CAN HW will then build the wrong CRC when transmitting that data. Or the receiver might have a bug and flip the received data between the CAN mailbox and the actual receiving SWC end.
For example. The value of the wanted sum of 2534 is 154 (2^4 + 5^3 + 3^2 + 4^1 = 16 + 125 + 9 + 4 = 154). ``` int main() { int b, a, s, j, i, ss = 0, t; do { printf("TYPE A NATURAL NUMBER: "); scanf_s("%d", &b); } while (b < 1); t = b; for (i = 1; b != 0; i++) { a = b % 10; if (i < 2) { ss += a; } s = a; for (j = 1; j >= 2; j--) { s *= a; } if (i >= 2) { ss += s; } b /= 10; } printf("value of the wanted sum %d is %d", t, ss); return 0; } ```
You can use this: ``` for (i = 1; b != 0; i++) { a = b % 10; s = a; for (j = i; j > 1; j--) { s *= a; } ss += s; b /= 10; } ``` The main problem is your inner loop.for (j = 1;j>=2..)will never execute as j starts from 1 and is never bigger than 2.
Please see the below code : ``` SomeStructure* SomeFunc(); #define kkData (*SomeFunc()) ``` Question : What doeskkDatarepresents ? EDIT : Removed semi-colon from second line.
This directive ``` #define kkData (*SomeFunc()); ``` means a call of the functionSomeFuncand dereferencing the pointer to a structure returned from the function. For example you could write in the program ``` SomeStructure s = kkData ``` Pay attention to that the semicolon in the directive should be removed. In this case the code in the program ``` SomeStructure s = kkData; ``` will be more clear.
i have ``` void *string; // it is array of characters different encodings ``` i read it with my func, after that i want to print it, all good, it prints right. and after that i want to print i character (first for example), how can i access him? ``` string=readline(); printf("%s\n", string); printf("%c\n", ??? ); ``` i tried this, but it doesn't work ``` string=readline(); printf("%s\n", string); printf("%c\n", string + sizeof(void *); ```
If the data is representable ascharthen simply cast and de-reference: ``` printf("%c\n", *(char*)string); ``` Or alternatively: ``` char* str = string; ... printf("%c\n", str[i]); ```
I cannot use string or char input. If I use input like "c" then ``` int x,y,z; while (1) { z=scanf("%d%d", &x,&y); if(z == 0){ printf("correct!\n"); } else{ printf("Incorrect!\n"); } } ```
Check properly against success, not 0. On failure, consume characters until end-of line. Ifscanf("%c", ...)or the like not allowed due to "I cannot use string or char input.", you are out of luck. Exit the loop on success or end-of-file ``` do { z = scanf("%d%d", &x,&y); //if(z == 0){ if (z == 2) { printf("correct!\n");` } else if (z != EOF) { printf("Incorrect!\n"); char ch; while ( scanf("%c", &ch) == 1 && ch != '\n') { ; } } } while (z != 2 && z != EOF); ```
This question already has answers here:How do I properly compare strings in C?(11 answers)Closedlast year. I would like to know what is the problem with this code. I want to right a name in the programming and if it's correct give me "Let's go" if it's not give me go back. I want to add Zay in if statement through right it in scanf. but it gives me an error I searched a lot but there is a problem, pls help me. ``` #include <stdio.h> int main() { char name[15]; printf("Type name "); scanf("%s",&name); if(name == 'zay') { printf("Let's go, %s\n", name); } else { printf("go back, %s\n", name); } return 0;} ```
This is wrong ``` if(name == 'zay') ``` you mean ``` if(strcmp(name, "zap") == 0) ``` seehttps://man7.org/linux/man-pages/man3/strcmp.3.html and you need to includestring.h
I don't get why the free here is not working and i still get 5 in the printf. Should i just point the p value to NULL? I've searched many threads but didn't find any helpful informations about this. ``` #include<stdio.h> void main(){ int *p = malloc(sizeof(int)); *p = 5; free(p); printf("%d\n",*p); } ```
The function is calledfreenoterase, it does not "erase" the memory pointed by the pointer, it merely allows that area of memory to be used for something else.printfprinted the previous value, meaning that nothing else happened to use the memory that has been just freed. Regardless, you are still attempting to access a memory that no longer belongs to you, and hence invoking undefined behaviour. The code may crash, or print the previous value, or print garbage, or it might as well draw a unicorn to the console, this is what makes undefined behaviour ...undefined.
``` #include <stdio.h> void main(void){ char a[11]= "EN21396304"; char*ptr1; ptr1 = a; ptr1 = (ptr1+2); char i; char sum = 0; for(i=0; i<=8; i++){ sum = sum + *(ptr1+i); } printf("Sum of the digits in the array = %d\n", sum); } ```
You are adding ASCII values. You also don't need a separate pointer (ptr1). What you want is this: ``` #include <stdio.h> void main(void) { char a[] = "EN21396304"; int sum = 0; for(int i = 2; a[i]; i++) { sum += (a[i] - '0'); } printf("Sum of the digits in the array = %d\n", sum); } ``` Note thatsumshould be anint, becauseintis the most natural and efficient type for the platform and compiler.
I need to limit the maximum size of Berkeley's buffer. I've tried using the code below, but the buffer keeps growing. ``` DB_ENV *db_env; u_int32_t env_flags; char *DBNOMENV = ""; db_env_create(&db_env, 0); db_env->set_cache_max(db_env, 0.1, 0); env_flags = DB_CREATE | DB_INIT_MPOOL; db_env->open(db_env, DBNOMENV, env_flags, 0); DB *BDB_database; db_create(&BDB_database, db_env, 0); ```
You wantDB_ENV->set_cachesize:set_cachesize, from the Oracle docs. What's the purpose ofset_cache_max, when all it appears to do is limit the number you can specify with some other function call? You got me. There's probably some nuance here, but in practice,set_cache_maxis only there to to add to the confusion. Note that both of these functions only accept integer arguments for the sizing. You'll needset_cachesize(db_env, 0, 100*1024*1024, 1);to do what you were trying to do with that0.1. "Number of caches" should be 1.
When I define an array like ``` double *first = (double *)malloc( N*N*sizeof( double ) ); ``` There is not problem. But when I specify ``` static double *first = (double *)malloc( N*N*sizeof( double ) ); ``` I get this error ``` error: initializer element is not constant 10 | static double *first = (double *)malloc( N*N*sizeof( double ) ); | ^ ``` How can I fix that?
You may initialize objects with static storage duration with constant expressions. And an expression with a call of malloc is not a constant expression. So you need for example initialize the pointer as a null pointer like for example static double *first = NULL; and then call the function malloc in a function ``` if ( first == NULL ) first = (double *)malloc( N*N*sizeof( double ) ); ```
I understand that thestrtok()function allows you to split a string with a predefined delimiter (or a set of delimiters), but is there a way to split a string by the FIRST INSTANCE of a delimiter? Example: (Delimiter=":") Input: "Host: localhost:5000" Output: ["Host", "localhost:5000"] The output does not necessarily need to be in a list, but the string needs to be split into two strings. Thanks for the help!
The first time you callstrtok, use the delimiter you want to split with. For the second call, use an empty delimiter string (if you really want the rest of the string) or use"\n", in the case that your string might include a newline character and you don't want that in the split (or even"\r\n"): ``` const char* first = strtok(buf, ":"); const char* rest = strtok(NULL, ""); /* or: const char* rest = strtok(NULL, "\n"); */ ```
How that code (of the language C) can works? I don't understand how much memory that chunk of code, "char* op[30]", allocate. And I don't know too how the memory is organized in that situation. I got the ideia how allocate memory with "malloc" works, but the case below is obscure to me. ``` int main(void) { int n; scanf("%i", &n); char* op[30]; op[0] = "Hello, World" op[1] = "Hello, World World World" op[2] = "Hello, World World World World World World" op[3] = "Hello, World World World World World World World World World..." printf("%s\n", op[0]); printf("%s\n", op[1]); printf("%s\n", op[2]); printf("%s\n", op[3]); return 0; } ```
You will have a contiguous array on the stack of length 30. Each element of that array is a char* pointer. The first 4 pointers each point to a literal character string. The other entries are uninitialized
(num%2==0)? sum1+=num:sum2+=num; why does this code give a lvalue required as left operand of the assignment error? I tried reading about the error but from what i understood this happens when assigning a value in an incorrect manner. Like 8+a=b which is not my case. In my case i am doing sum1 = sum1+num; anyone know why perhaps?
Operator precedence.?:has higher precedence than+=so this gets treated as: ``` ((num%2==0) ? sum1+=num : sum2) += num; ``` Which is of course nonsense. Quick fix: ``` (num%2==0) ? (sum1+=num) : (sum2+=num); ``` However, there's no apparent need to use?:here so you should probably go withif-elsefor better readability.
``` #include<stdio.h> int main() { char c; while((c=getchar()!=EOF)) { putchar(c);// } } ``` Every character of the output is displaced by '' these sorts of things. enter image description here
Your parentheses are wrong socgets assigned the value of the condition, which is0or1(falseortrue). What you have now is the same asc = (getchar() != EOF)because ofoperator precedence. Also, use the correct type forc, which isint: ``` #include<stdio.h> int main() { int c; while( (c = getchar()) != EOF ) { putchar(c);// } } ```
``` for (int x= 7; 0<=x; x--) { size_t x_val = ((1<<4)-1) & io>>x*4; printf("%lX", x_val); ``` Trying to print a hexadecimal number here after converting it from integer. While the conversion is successful, the output isFFFFFFCDinstead of the desired outputFFCD. How can I limit maximum 4 characters to be printed?
to print a four character hexadecimal Limit value to the [0...0xFFFF] range.Print 4 digits padded with zeros with the correct specifier. Example ``` unsigned masked_value = io & 0xFFFF; printf("%04X\n", masked_value); ```
SLES 15 SP3 makes use of glibc 2.31 and our convert time code using mktime is failing with ulong overflow. Can anyone let us know if we are missing something here. Or do we have any other alternative system call that does the same? ``` main() { time_t time_since_epoch = 0; struct tm gmTimetm; gmTimetm.tm_year = 2022; gmTimetm.tm_mon = 02; gmTimetm.tm_mday = 24; gmTimetm.tm_hour = 11; gmTimetm.tm_min = 42; gmTimetm.tm_sec = 45; time_since_epoch = mktime(&gmTimetm); printf("%lu \n", time_since_epoch); return 0; } ``` OP: 18446744073709551615
mktime() is failing. It is returning -1.
I am trying to make a C program lexical analyzer using flex. I readhttps://en.cppreference.com/w/c/language/translation_phasesand was told that vertical tab\vand form feed\fis kept before the line-combining and the decomposing phases. Should I consider them as newlines characters just like\n? looking forward to any reply, thank you.
The C standard says in chapter 5.1.1.2 "Translation phases" for phase 3: The source file is decomposed into preprocessing tokens and sequences of white-space characters (including comments).[...]Whether each nonempty sequence of white-space characters other than new-line is retained or replaced by one space character is implementation-defined. Since\vand\fare white-space characters, it is up to you to replace them with a single space or not. But you should not replace them with new-lines.
I am new to c language and I am trying to compile my first program, following a tutorial. My file hello.c : ``` #include <stdio.h> int main(void) { printf("hello, world\n"); } ``` I use "make hello" command to compile it but I get the error: ``` cc hello.c -o hello process_begin: CreateProcess(NULL, cc hello.c -o hello, ...) failed. make (e=2): The system cannot find the file specified. <builtin>: recipe for target 'hello' failed make: *** [hello] Error 2 ``` I have MinGW installed and I have it in my environment variables PATH. I am trying it on Windows 8. Please any help I would very appreciate. Maybe there is another way to compile a c files?
MinGW is actually a gcc compiler. So the C compiler is invoked withgccinstead ofcc. Try running this command: ``` make hello CC=gcc ```
I know I should use memmove if there's overlapping but I can't imagine how sprintf (or memcpy for that matter) would be coded such that it would run into a problem.
The source and target are clearly overlapping. So, yes, this counts.
I'm new to C and I was wondering if using system() is a good way to change the color of a text in the console. ``` int main() { system("echo \x1b[32m"); printf("hello"); return 0; } ``` And is it cross-platform ?
There are two problems with this code: system("echo \x1b[32m");does the exact same thing asputs("\x1b[32m");but more slowly. It creates a subprocess and runs a command interpreter of some stripe, which must then interpret the commandecho ␛[32m. I don't know any reason to writesystem("echo ...").The byte sequence␛[32m(1b 5b 33 32 6d) is anANSI X3.64 terminal control codewhich may or may not be understood by whateverstdoutis connected to. It is better to use a terminal control library, such asncurses, which will figure out what it's talking to and use the correct control sequence (or not use colors at all, if they're not supported).