question
stringlengths
25
894
answer
stringlengths
4
863
I'm trying to call a C function from python. This function takes a number of arrays as input and returns a float. Do I need a SWIG typemap to do this? One concern is that python doesn't make a distinction betweenfloats,double, etc and I'm specifically interested in returning only c-typefloat.
Returningfloat"just works". You don't need additional typemaps: test.i ``` %module test %inline %{ float func(void) { return 1.5; } %} ``` After running swig and compiling the result: ``` >>> import test >>> test.func() 1.5 ```
I need to design an algorithm which will sort an array which contains numbers -1,0,1 only, without using any temp variable or array and by using only swapping I have come up with the following method I'm not sure if it is O(n). ``` #include <stdio.h> #define MAXSIZE 10 int main() { int array[MAXSIZE]; int i, j, num = 8, temp; int list[] = {-1,0,-1,0,1,1,0,1}; int size = sizeof(list)/sizeof(list[0]); for (int i = 1; i < size; i++) { if (list[i] < list[i - 1]) { list[i] = list[i] + list[i - 1]; list[i - 1] = list[i] - list[i - 1]; list[i] = list[i] - list[i - 1]; i = 0; } } printf("Sorted array is...\n"); for (int i = 0; i < size; i++) { printf("%d\n", list[i]); } } ```
The algorithm is definitely not O(n).You are settingito0when you do a swap. At worst, it is O(n^2).
struct page* alloc_pages(gfp_t gfp_mask, unsigned int order)is the function used to allocate page in kernel. So this will allocate 2^order contiguous physical pages. So this means the pages will allocate in the manner of 1,2,4,8,16 and so on. What if only 3 pages are needed or 5 ,9 and so on.
Fromthe link provided by tkausl: The order is the power of two number of pages to allocate Soalloc_pages(gfp_mask, 3)will allocate 8 pages.alloc_pages(gfp_mask, 4)will allocate 16 pages, and so on.
I would like to know how to define a char array, in C, of three elementsa,b,c, whereais located on one first octet,bin one second andcin one third.
Well, In C, the size ofcharit's 1. I think we can't know if it's 1 octet or more (or less). So, ``` char tab[3] = {'a','b','c'}; ``` doesn't work ?
I am having trouble when using right to left rule to interpret variable declarations when typedef is involved. In the C++ primer 5th edition book I saw the following code: ``` typedef char *pstring; const pstring cstr = 0; // cstr is a constant pointer to char const pstring *ps; // ps is a pointer to a constant pointer to char ``` If I replace the pstring with char * then it stands like this: const char *cstr So I expect cstr to be a pointer to a const char. But the comments in the book states the pointer itself is constant. My question is what's wrong with my way of thinking.
Atypedefis not a macro. You don't just text replace it. Read it ascstris a "constantpstring", which is a "constant (pointer to char)". Compare this toconst char*, which is "pointer to constantchar". If you were to replace the typedef it would look like this: ``` char* const cstr = 0; char* const* ps; ```
When I build a simple console app with clang, it works fine: void main() { puts("HELLO"); } But when I create a Windows app withWinMain, I can't see stdout. There must be a flag that fixes it, like MinGW's-mconsole
A quick stdout-enabler for otherwise GUI apps: ``` if (AllocConsole()) { FILE* fi = 0; freopen_s(&fi, "CONOUT$", "w", stdout); } ``` and thenstd::coutandprintfwork.
Some simple preprocessor code in Linux Kernel module gives the following error: missing binary operator before token "(" The code: ``` #if defined(AAA) || defined(BBB) #if LINUX_VERSION_CODE <= KERNEL_VERSION(3,13,0) #define SOME 111 #else #define SOME 222 #endif #define OTHER 999 #else #define SOME 1 #define OTHER 9 #endif /* AAA || BBB */ ``` That postdidn't help.
that error means KERNEL_VERSION is not defined you missed to#include <linux/version.h> Edit About kernel version see also :Is there a macro definition to check the Linux kernel version?
I am trying to print each word on a new line. I have made it to scan for a space and then print new line. It cansput deletes some letters at times: ``` #include <stdio.h> #include <ctype.h> int main(void) { char ch; int nextChar; nextChar = getchar(); while (ch != EOF) { if (ch == ' ') { putchar('\n'); } else { putchar(ch); } ch = getchar(); } return 0; } ``` For example Input:hello how are you output: ``` hello how are you ```
The issue here is you assign first char value tonextCharvariable and usechvariable. To correct try the folowing: ``` #include <stdio.h> #include <ctype.h> int main(void) { char ch = getchar(); while (ch != EOF) { if (ch == ' ') { putchar('\n'); } else { putchar(ch); } ch = getchar(); } return 0; } ```
I am a beginner in C and I can't find an answer. How can i change array in main function? Please, help. Thank you. Sorry for my bad English. ``` char name [] = "Maks"; printf ("&s",name); name = "Alex"; printf ("&s",name); ``` So my question is how can i change the value of stray name during program. I want to change the name from Maks to Alex. Thank you.
you need to usestrcpy()function ``` #include <stdio.h> #include <string.h> int main() { char name[5] = "Mark"; printf("%s\n", name); char get[5] = "Alex"; strcpy(name, get); } ```
In C, I need to input four variables using scanf scanf("%c %d %d %d", &v1, &v2, &v3, &v4) the first variable may take two values 'c' and 'q' when I enter c then I enter the other variables it will do some calculations but when I want to quit I should enter 'q' only and not enter the rest of the variables but scanf does not move forward until I enter the rest of the variables is there anyway to solve it, I am not sure if it is possible using scanf but if there is another function then I don't mind using it
"is there anyway to solve it" Read alineof user input withfgets()... ``` char buf[100]; if (fgets(buf, sizeof buf, stdin)) { ``` .. and then scan it ``` char v1; int v2,v2,v3; int cnt = sscanf(buf, "%c %d %d %d", &v1, &v2, &v3, &v4); if (cnt >= 1 && v1 == 'q') Quit(); else if (cnt == 4 && v1 == 'c') Do_stuff(v2,v3,v4); else puts("Bad input"); ```
I am trying to print each word on a new line. I have made it to scan for a space and then print new line. It cansput deletes some letters at times: ``` #include <stdio.h> #include <ctype.h> int main(void) { char ch; int nextChar; nextChar = getchar(); while (ch != EOF) { if (ch == ' ') { putchar('\n'); } else { putchar(ch); } ch = getchar(); } return 0; } ``` For example Input:hello how are you output: ``` hello how are you ```
The issue here is you assign first char value tonextCharvariable and usechvariable. To correct try the folowing: ``` #include <stdio.h> #include <ctype.h> int main(void) { char ch = getchar(); while (ch != EOF) { if (ch == ' ') { putchar('\n'); } else { putchar(ch); } ch = getchar(); } return 0; } ```
I am a beginner in C and I can't find an answer. How can i change array in main function? Please, help. Thank you. Sorry for my bad English. ``` char name [] = "Maks"; printf ("&s",name); name = "Alex"; printf ("&s",name); ``` So my question is how can i change the value of stray name during program. I want to change the name from Maks to Alex. Thank you.
you need to usestrcpy()function ``` #include <stdio.h> #include <string.h> int main() { char name[5] = "Mark"; printf("%s\n", name); char get[5] = "Alex"; strcpy(name, get); } ```
In C, I need to input four variables using scanf scanf("%c %d %d %d", &v1, &v2, &v3, &v4) the first variable may take two values 'c' and 'q' when I enter c then I enter the other variables it will do some calculations but when I want to quit I should enter 'q' only and not enter the rest of the variables but scanf does not move forward until I enter the rest of the variables is there anyway to solve it, I am not sure if it is possible using scanf but if there is another function then I don't mind using it
"is there anyway to solve it" Read alineof user input withfgets()... ``` char buf[100]; if (fgets(buf, sizeof buf, stdin)) { ``` .. and then scan it ``` char v1; int v2,v2,v3; int cnt = sscanf(buf, "%c %d %d %d", &v1, &v2, &v3, &v4); if (cnt >= 1 && v1 == 'q') Quit(); else if (cnt == 4 && v1 == 'c') Do_stuff(v2,v3,v4); else puts("Bad input"); ```
I have an array of strings defined as an array of pointers to string as following ``` char* dict[50]; dict[0][0]= 0; printf("%d", dict[0][0]); ``` // This gives a segmentation fault, could someone please explain why so? Also if I put dict[0]=0, is it the same as dict[0][0]=0
The reason is that you haven't allocated any memory.char* dict[50]is a 50 elements long array of char pointers: if these pointers haven't been pointed to valid memory, writing to them is undefined behaviour and will frequently crash your program or worse.
``` __m256 dst = _mm256_cmp_ps(value1, value2, _CMP_LE_OQ); ``` Ifdstis[0,0,0,-nan, 0,0,0,-nan];I want to be able to know the first-nanindex, in this case3without doing a for loop with8iterations. Is this possible?
I wouldmovmskpsthe result of the comparison and then do abitscan forward. Using intrinsics (this works with gcc/clang, seehere for alternatives): ``` int pos = __builtin_ctz(_mm256_movemask_ps(dst)); ``` Note that the result ofbsfis unspecified if no bit is set. To work around this you can, e.g., write this to get8, if no other bit is set: ``` int pos = __builtin_ctz(_mm256_movemask_ps(dst) | 0x100); ```
I apologise if this seems simple, I'm still learning and I'm new to C. I have this as my struct: ``` struct Game{ char id; char name[50]; char genre[20]; char platform[15]; char company[30]; float price; int quantity = 10; }; ``` And this declared as a struct array: ``` struct Game gList[30]; ``` I have a function where I'm passing all of 'gList' to search through values in the gList[i].name variables. So my question is,is it possible to send only the gList[i].name part of the struct to the function as a parameter?(ie All the 30namevalues only).
No. But you could make an array of pointers that point to thenamefield and pass it to the function: ``` char* ptr[30]; for(int i = 0; i < 30; i++) ptr[i] = gList[i].name; func(ptr); ```
I was trying to store an int value (all 4 bytes) into achar *: So, I would like to store the full value i.e all the bytes (all 4) of the int variable into the char such that I use up 4 bytes out of the 512 bytes. I should also be able to read back the value that I assigned. I tried to use a lot of the stuff but couldn't figure this out. This is for my LFS (Log File System) where I try to store files into data blocks on my disk using fragmentation of data ``` char *c = malloc(512); int value = 4096; ```
You can copy into the buffer pointed to byc: ``` memcpy(c, &value, sizeof(value)); ``` If you want to write another value following that, you can add offset toc: ``` memcpy(c + sizeof(value), &value2, sizeof(value2)); // adds value2 at an offset right after value ``` To read the value, you can copy it into a different variable: ``` int readVal; memcpy(&readVal, c, sizeof(readVal)); ```
I am trying to build a UDP server, I want to access to the socket optionIPV6_RECVPKTINFO. When I try to access this option, the following message appears : "error: use of undeclared identifier 'IPV6_RECVPKTINFO". The libraries<sys/socket.h>and<netinet/in.h>are include. I am working on MacOS, is there a way to enable this option or is there an alternative ?
You need to define__APPLE_USE_RFC_3542to use the newer constants. Put this before your other includes: ``` #define __APPLE_USE_RFC_3542 ``` Or do it on the command line: ``` … -D__APPLE_USE_RFC_3542 … ```
I have cmake project that consist of multiple targets. ``` MyProject/ /target1 /Some stuff /CMakeLists.txt // here add_executable(target1 main.c) /target2 /target3 ... CMakeLists.txt // root CMakeLists.txt file /build // folder for build files ``` I wand to build only target1 and put it into /build folder inside my project I could build all targets ``` [MyProject/build]$ cmake .. [MyProject/build]$ make ``` How to build only target1? I guess it must be something like this? ``` [MyProject/build]$ cmake .. [MyProject/build]$ cmake --build . --target target1 -- -j 12 ```
Suppose you set an executable inside CMakeLists.txt ``` add_executable( my_exe ${my_exe_sources} ) ``` Then you can callmake my_exe -j 2
Had some trouble reading the following code snipped in git repo. link to repo and problem: https://github.com/paolo-sz/fatty/blob/master/src/winmain.c#L2649 ``` switch (confirm_multi_tab()) { when IDNO: if (!cfg.confirm_exit || confirm_tab_exit()) { child_terminate(term->child); } return; when IDCANCEL: return; } ``` Could someone explain why there is a 'when' in the switch statement and not 'case' . Appreciate the help.
See thestd.hfile athttps://github.com/paolo-sz/fatty/blob/master/src/std.hline 143: ``` #define when break; case ```
Other than the textbook definitions of the keyword 'assert' What is the actual use case ? Its not a commonly used keyword so examples are rare to find explaining the actual implementation and its use in Code
You can use it in any way you may find suitable. Personally, I use it for writing simple unit tests when I don't want to rely on any dependency. Some people use it for checking pre and post-conditions, like for example: ``` int foo(int a, int b) { int result; assert(a > 0 && a < 150); assert(b > 20 && b < 1000); // do something with a, b and store something in result assert(result > -10 && result < 10); return result; } ``` But please beware that assertions can be disabled at compile time by defining theNDEBUGmacro. So for example if you rely on it for pre-conditions, you may want to double them with tests built un-conditionally.
This question already has answers here:What does the question mark and the colon (?: ternary operator) mean in objective-c?(13 answers)Closed4 years ago. What does this code mean? int c, sign; sign = (c == '-') ? -1 : 1; I only know integers as numbers. What do the question mark etc. mean?
This is the ternary operator. ``` sign = (c == '-') ? -1 : 1; ``` and the code above is equivalent to ``` if(c == '-') sign =-1; else sign=1; ``` To explain more about the ternary operator : the syntax is : ``` (condition)? do this if condition is true:do this if condition is false ``` Another example you can use it for : ``` int a=1; printf( "Value of test is %d\n", (a == 1) ? 20: 30 ); ``` this will print 20 if a==1 is true and 30 if a==1 is false
always the first line of my file is empty whst can i do ? ``` printf("donner n"); scanf("%d",&n); for(int i=0;i<n;i++) { gets(ch); fprintf(f,"%s\n",ch);} ``` ```
change ``` scanf("%d",&n); ``` to ``` scanf("%d\n",&n); ``` Should be able to get the results you want Because the first empty line is a newline character that is not read at scanf.
always the first line of my file is empty whst can i do ? ``` printf("donner n"); scanf("%d",&n); for(int i=0;i<n;i++) { gets(ch); fprintf(f,"%s\n",ch);} ``` ```
change ``` scanf("%d",&n); ``` to ``` scanf("%d\n",&n); ``` Should be able to get the results you want Because the first empty line is a newline character that is not read at scanf.
I want to get the intersection of two linked lists but when i declare the iterators outside the for loop it just doesn't work ``` // THIS WORKS FINE for (SList iter1 = list1 ; !slist_empty(iter1); iter1 = iter1->next) { for(SList iter2 = list2 ; !slist_empty(iter2); iter2 = iter2->next) { if(comp(iter1->data, iter2->data)) { result = slist_add(result, iter1->data); } } } // THIS DOESN't SList iter1 = list1 ; SList iter2 = list2 ; for (; !slist_empty(iter1); iter1 = iter1->next) { for(; !slist_empty(iter2); iter2 = iter2->next) { if(comp(iter1->data, iter2->data)) { result = slist_add(result, iter1->data); } } } ``` im compiling with -std=c99
In the first version you go throughlist2for every item inlist1. In the second version you only go throughlist2for the first item inlist1. You need to "reset"iter2to the start oflist2each time.
I have a variable initialized when declared that is also marked to be linked into a NOLOAD section, i.e. : ``` struct mystruct_s mystruct __attribute((section(".noload_sec"))) = { .something = 100, .something_else = 100, }; ``` Is there a way for the linker to automatically detect this invalid condition? Meaning can we error if someone tries to initialize a variable at declaration which is located into a section which will not be loaded?
After a few different attempts, and a lack of answers here, I've concluded that this cannot be enforced with current GCC. A solution would be to write a build time script to scan the source and throw the error when a variable declaration for a symbol located in a no init section is initialized.
I'm trying to build my library but a file called evutil.c fom libevent is giving me a hard time. libevent/evutil.c: error: implicit declaration of function 'pipe2' is invalid in C99 The code involved is: ``` if (pipe2(fd, O_NONBLOCK|O_CLOEXEC) == 0) return 0; ``` I can't update my code to c11 right now. How should I change the code to not get this error anymore?
This isn't a C99 issue. You need to include the header forpipe2.According to the pipe2 manualthat isunistd.h. Why libevent isn't doing this itself is a valid question.
Consider below example ``` void func(int i){ if(i) { int arr[2048] = {0}; //Doing something related to arr; } else { //Doing something } } ``` I have a large array declaration in theifblock. The initialization of this array should cost some time. My question is: ifi == 0, will this array be initialized at all?
if i == 0, will this array be initialized at all? because your code is if(i) { int arr[2048] = {0}; //Doing something related to arr; } else { //Doing something } the array does not exist ifi==0so it cannot be initialized, the array only exists in the branch of theifwherei != 0
Basically I'm running this code on this CLion application due to my teacher's demands. I have my struct of 'Estado' defined in .c file like this: ``` struct estado{ char modo; char jogador; char matriz[8][8]; int pretas; int brancas; }; ``` And have this on my .h file: ``` typedef struct estado* Estado; ``` In my main.c file where i try to acess: ``` printf("%s",novo -> matriz[1]); ``` It says: "error : dereferencing pointer to incomplete type ‘struct estado' " Can you help me ?
You should put thestructdeclaration in your.hfile instead of the.cfile.
Basically I'm running this code on this CLion application due to my teacher's demands. I have my struct of 'Estado' defined in .c file like this: ``` struct estado{ char modo; char jogador; char matriz[8][8]; int pretas; int brancas; }; ``` And have this on my .h file: ``` typedef struct estado* Estado; ``` In my main.c file where i try to acess: ``` printf("%s",novo -> matriz[1]); ``` It says: "error : dereferencing pointer to incomplete type ‘struct estado' " Can you help me ?
You should put thestructdeclaration in your.hfile instead of the.cfile.
How can I trace the gcc ld linker linking process? I need to see how it link with function from shared objects.
Depending on what you are after, you can pass either-Wl,--traceor-Wl,--creftogcc, instructing the linker to print additional details about the linking process: --traceoption--crefoption If you are interested in a particular symbol, saySYMBOL, you could try-Wl,--trace-symbol,SYMBOLas well. (This assumes that you are using binutilsld, of course.)
Firstly, my "C code" listens serial Port all the time so I want to make file and writes all data which I receives from serial Port. and I have a question: Is there any necessary condition which file will be best or what file Extension will be better, or is there any good rules, advice?
It depends what you want to do with that file afterward and the information transmitted by the serial port. Using a text file is easy and is often enough for a lot of situation, in particular if the objective is to keep a log. https://www.tutorialspoint.com/cprogramming/c_file_io.htm
I am a beginner in C language. I used a nested for loop to check conditions of individual elements in a 2-D array. Basically, I want to check every elements except for those in the 3rd row. Is this correct? Will value i go from 0 to 5 and skip i=2? Or will the loop condition be met when i=0, stops and return true? Thank you! I wrote ``` for(i=0; i<6& i!=2;i++){ for (j=0;i<6;j++){ if(board[i][j]!='U'){return true;} } } ```
Usecontinueto begin next iteration: ``` for(i = 0; i < 6; ++i){ if(i == 2){ continue; } for(j = 0; j < 6; ++j){ if(board[i][j] != 'U'){ return true; } } } ``` This however will only work on the innermost loop in which thecontinueis contained. Edit: This is a working solution. For discussions over clean code and wether to usecontinueor not rather refer to theSoftware Engineering Forum.
What is the fastest way to duplicate the bits of an integer. For example, 17->10001 after duplication:1100000011
Looks like a variation ofbit interleaving. Interleave bits the obvious way(modified fromhttp://graphics.stanford.edu/~seander/bithacks.html)unsigned int x = 17; unsigned int z = 0; // z gets the resulting Morton Number. for (int i = 0; i < sizeof(x) * CHAR_BIT; i++) // unroll for more speed... { z |= (x & 1U << i) << i | (x & 1U << i) << (i + 1); } Seehttp://graphics.stanford.edu/~seander/bithacks.html#InterleaveTableObviousfor more approaches.
This question already has answers here:C easy program not working - "if"(5 answers)Closed4 years ago. I intended to make a program to make a program that tells the user if a given integer number is even or odd. However, it says that the 'else' has no previous 'if', what am I getting wrong? ``` #include <stdio.h> #include <stdlib.h> int main() { int num; printf("type an integer "); scanf("%d", &num); if(num % 2 == 0); printf("%d is even", num); else printf("%d is odd", num); return 0; } ``` There´s no output
Your code ``` if(num % 2 == 0); printf("%d is even", num); ``` The fix ``` if(num % 2 == 0) printf("%d is even", num); ``` The issue You have a semi-colon after your if statement, removing it will resolve your issue.
This question already has answers here:C easy program not working - "if"(5 answers)Closed4 years ago. I intended to make a program to make a program that tells the user if a given integer number is even or odd. However, it says that the 'else' has no previous 'if', what am I getting wrong? ``` #include <stdio.h> #include <stdlib.h> int main() { int num; printf("type an integer "); scanf("%d", &num); if(num % 2 == 0); printf("%d is even", num); else printf("%d is odd", num); return 0; } ``` There´s no output
Your code ``` if(num % 2 == 0); printf("%d is even", num); ``` The fix ``` if(num % 2 == 0) printf("%d is even", num); ``` The issue You have a semi-colon after your if statement, removing it will resolve your issue.
From the codeherethere is the pointerchar **strData = NULL;in line 12. I'm new to C and pointers. I get, that it is a pointer, which points toanotherpointer. I just don't see the other pointer. Can somebody help me?
strData = (char**)realloc(strData, sizeof(char**)*(noOfLines+1));is in the while loop, sostrDatapoints to a memory block, which can hold pointer.sizeof(char**)should besizeof(char*). It is followed bystrData[noOfLines] = (char*)calloc(MAX_LEN,sizeof(char));, which is the pointer you asked for. SostrDatapoints to a block of pointers,strData[i]points to a block ofchars.
I'm using: IntelliJ IDEA 2018.3.5 (Community Edition) Build #IC-183.5912.21, built on February 26, 2019 JRE: 1.8.0_152-release-1343-b28 amd64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o Windows 10 10.0 I want to use C/C++ code. I know that there is a separate IDE 'CLion' available for this, but is it possible to integrate C/C++ in this community edition of Intellij only? I don't want to have any seperate IDE.
There is no C/C++ support for IntelliJ IDEA Community and Ultimate at the moment. Here is the related feature request. Even when implemented, it will be probably available only in the Ultimate version.
I'm trying to make a loop using * as my text. Im trying to make my output look like this: ``` * * * * * * * * * * * * * * * ``` I am a little unsure how to do this. I currently got: ``` #include <stdio.h> int main(int argc, const char *argv[]) { int i=1; while (i <= 4) { printf("%d\n",i); i++; } return 0; } ``` this outputs: ``` 1 2 3 4 ``` can I have some helping changing the numbers to (*) form. thanks,
Here you are, try it: ``` #include <stdio.h> int main(int argc, const char *argv[]) { int i, j; for(i = 0; i <= 5; ++i) { for(j = i; j > 0; j--) { printf("* "); } printf("\n"); } return 0; } ```
I have a.cfile with a program (obviously written in C): ``` #include <stdlib.h> int main(int argc, char** argv) { printf("Hello World\n"); return 0; } ``` I'm having problems running it. At first, this happened: ``` $ ./file.c bash: ./file.c: Permission denied ``` I then added execute permissions withchmod +x file.c, but it still didn't work: ``` $ ./file.c ./file.c: line 3: syntax error near unexpected token `(' ./file.c: line 3: `int main(int argc, char** argv) {' ``` However, as far as I know, this C program should be syntactically correct. How do I execute it?
You cannot execute an file ".c" from shell. You must compile it first. For example: We have an file called "file.c" Open a terminalUse gcc for compile the file and make an executable (gcc file.c -o executable)Now you can open the executable file since shell (just go to the folder and execute./executable
I need to check if the user input is using the correct delimiters. However the code I have right now would still allow for example "15-10/1999", which it shouldn't. I'm not quite sure how exactly to change the while condition to disallow this though. ``` char delim1, delim2; do { printf("Please enter date (dd-mm-yy or dd/mm/yy):"); scanf("%d%c%d%c%d", &day1, &delim1, &mon1, &delim2, &year1); } while (delim1 != '-' && delim1 != '/' && delim2 != '-' && delim2 != '/'); ```
You can use: ``` while (delim1 != delim2 || (delim1 != '-' && delim1 != '/')); ``` This ensures that the delimiters are equal after the while condition is satisfied and that it is either '-' or '/'.
This question already has answers here:Macros and postincrement(8 answers)Closed4 years ago. I am trying to learn pre increment operator in C. I have made a sample code and tried to understand the output: ``` #include<stdio.h> #include<conio.h> #define max(a,b) (a>b ? a:b) int main() { int I =1; int j=2; int k = 0; k = max(++I,++j); pirntf("%d",k); } ``` I am getting 4 as output. Shouldn't it be 3?
Your code expands to: ``` #include<stdio.h> #include<conio.h> #define max(a,b) (a>b ? a:b) int main() { int I =1; int j=2; int k = 0; k = (++I>++j ? ++I:++j); printf("%d",k); } ``` You can see that the value will be incremented twice.
``` #include <stdio.h> int main(void) { int nr = 5; char castChar = (char)nr; char realChar = '5'; printf("The value is: %d\n", castChar); } ``` If the above code is compiled, the output will be: ``` The value is: 5 ``` But if the code below is compiled, the console will output the value 53 instead. Why doesn't it print the same as the when the "castChar" is printed? ``` #include <stdio.h> int main(void) { int nr = 5; char castChar = (char)nr; char realChar = '5'; printf("The value is: %d\n", realChar); } ```
It is showing the ASCII value of the character as you are using %d with a character.Use %c instead. ``` #include int main(void) { int nr = 5; char castChar = (char)nr; char realChar = '5'; printf("The value is: %c\n", realChar); } ```
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.Closed4 years ago.Improve this question I need to implement a function that can count the number of digits in a string, and here is my code which is not working and i need to know what's the problem. int main() { ``` /* Enter your code here. Read input from STDIN. Print output to STDOUT */ char s[100]; scanf("%s",s); int i,j=0; for(i=0;i<10;i++) { int freq=0; while(s[j] != '\0') { if(s[j] == i +'0') { freq++; } j++; } printf("%d ",freq); } return 0; ``` }
Resetjto 0 after eachforloop iteration
I am writing a code in which a certain character must be displayed based on some condition and nothing must be displayed (not even space) if that condition is not fulfilled.I am usingprintf()with%cconversion specifier.When I want to print nothing then I passed'\0'for%cbut that is printing a space.What should I have to pass for my purpose?
There is no value that can be passed for the argument corresponding to a%cspecification toprintfthat results in no character being printed. To not to print a character, you must not executeprintfwith a%cspecification.
I have a byte and I want to test if Bit 1 is turned on. The condition I wrote is:if(byte & (1 << 0)) return true; Confusion: I not understand how to read a byte. Is Bit 1 this?ie. (1 << 0) ``` 00000000 ^ ``` Or this?(1 << 1) ``` 00000000 ^ ``` In other words, do we read a byte from 0 -7 or 1 - 8?
In computer science, counting always starts from 0. So the 0th bit is the rightmost one. That's why, in the example inthat answer,110 (6) << 1becomes1100 (12). This also means that shifting by 0 is a null operation (it doesn't do anything). This also means that for your case, if you want to test the rightmost bit, all you need to do isbyte & 1- no shifting necessary.
So I'm trying to get input into my c code but I keep on getting garbage when I use getchar(). I've tried using scanf() instead but no luck. ``` #include <stdio.h> int main(){ int c; while((c=getchar()) != EOF){ printf("%d", c); } } ``` I compile it on a bash shell with a text file as input and the values don't match at all. my input ``` lo hello, world 23 ``` my output ``` lo 108 111 10 104 101 108 108 111 44 32 119 111 114 108 100 10 50 51 10 10 ``` Why is this happening?
Your code outputs the numerical code that corresponds to each character your code reads in. Presumably, those are the numerical codes your computer uses to represent the characters you input. You don't say what you expected or why, but it would have to be a series of integers since that's all your code can possibly output.
I´m new in the C language, and I´m trying to get the 4 least significant bits from an unsigned char. So far I have no idea how to get them. I´ll appreciate any help
It's simplebitwiselogic: ``` unsigned char c = 120; unsigned char lsb4 = c & 0x0F; ``` Where0x0Frepresents the binary value00001111. If you'reusing GCC, it's even more literal: ``` unsigned char lsb4 = c & 0b00001111; ``` Technically the leading0s are not required here but they're included to help illustrate which bits are being selected.
I'm trying to read from a .csv file in C and it works for my character arrays, but not for my long. ``` char fname[24]; char lnem[48]; char email[36] long phone; fscanf(fp, "%[^,],%[^,],%[^,]%*s,%lf", fname, lname, email, phone); ```
The line should be ``` fscanf(fp, "%[^,],%[^,],%[^,],%ld", fname, lname, email, &phone); // removed %*s ----^ ^---- format specifier ^---- address-of operator ```
If I have the following algorithm ``` for (i = 1; i <= 4 * n; i = i * 4) { for (k = 1; k < 1000; k = 2 * k) { print(k); } print(i); } ``` how can I calculate its complexity? I only understand that for one iteration offor(i=1; i≤4n; i=i*4), the line withprint(i)is O(1), and for one iteration offor(k=1; k<1000; k=2*k), the line withprint(k)is O(1). I'm not sure how to proceed.
Here's the inner loop: ``` for(k=1; k<1000; k=2*k) { print(k); } ``` That loop is constant time, because there are no free variables. It's always going to callprintexactly 9 times, fork ∈ {1,2,4,8,16,32,64,128,256,512}. The outer loop is O(log n), because it will execute ⌊log₄ 4n⌋ times. Overall, the program fragment you posted (if we add the final closing brace you omitted) is O(log n).
Recently, I am trying to write a simple version of Linux commandmore. In order to do that, I need to enter noncanonical mode and non-echo mode in the terminal so that I get the input immediately after keypressing and terminal does not show the character I type. I did it by doing so: ``` // set the terminal mode struct termios tm; tcgetattr(STDIN_FILENO, &old); tm = old; tm.c_lflag &= ~(ICANON | ECHO); tm.c_cc[VMIN] = 1; tm.c_cc[VTIME] = 0; tcsetattr(STDIN_FILENO, TCSADRAIN, &tm); ``` This works when I use arguments like ``` more test_file ``` But when I tried to pipemorewith other command like ``` ls /bin | more ``` The terminal is back to canonical and echo mode. Why does this happen?
Generally speaking, things likemoreare expected to read fromstderr(or sometimes/dev/ttybutstderrworks better). You set terminal onstdininstead. That doesn't work so well.
I'm trying to write a C program that takes an input file name, and outputs a file with the same name but a different extension. For example, it would take in a file example.in and output example.out. I'm currently trying: ``` char *fname = argv[2]; char *fout = fname; ``` but I don't know how to proceed and change the extension of the file.
Check outstrrchr. From the man page: ``` The strrchr() function returns a pointer to the last occurrence of the character c in the string s. ``` This will allow you to identify where your "." is. From there, you can copy the beginning of the string to a new memory area, andstrcatthe ending on.
Example: ``` void *a = malloc(4); ... free(a); ... *a = 5; ``` In c for example is there a way of catching this error using some kind of system call or something? (assuming this is set up such that it can only be checked at runtime) if(isalloc (a))maybe? I'm wondering because c++ has figured it out somehow, except they have exceptions baked in. Can this be done in c? Perhaps a simple function exists, but I can't find it.
You can create such facility yourself. ``` #include <stdlib.h> #include <stdio.h> char _unallocated[] = ""; #define free(p) free(p); p = _unallocated #define isalloc(p) (p && p != _unallocated) int main() { void* a = _unallocated; printf("%d\n", isalloc(a)); a = malloc(4); printf("%d\n", isalloc(a)); free(a); printf("%d\n", isalloc(a)); } ```
I want to use a for loop to iterate through vector and when a certain condition is met, I want to go back to a certain element of vector and restart the loop from there. For example, let's say that my vector is 1,2,3,4,5,6,7,8,9; and when the first element that is bigger than 5 is met, I want to restart the loop from number 3 again. This is just an example. I don't know if I can write something like: ``` for(int i = 0; i < 8; i ++) { if(v[i] > 5) { i = 3; } } ``` Is this correct? If no, how can I do this using a for loop and the index of the vector?
Yes, it is perfectly fine to assign a value of choice to a loop variable inside the loop and its behaviour is well defined. You just have to realise that if this process leads to an infinite loop, you should put a check in place to be able to break out of the loop.
I need a solution to find the current used line in text file. I opened it with: ``` FILE *fp; fp=fopen(“data.txt”, “ r+“); ```
To keep track of which line in a file containing lines of text that you're currently processing, you could use a count variable. Here's a simple example ``` while (fgets(buffer, BUFLEN, fp) != NULL) { printf("Line %d: %s", line, buffer); if (buffer[strlen(buffer)-1] != '\n') // fgets didnt read an entire line, so increment the file pointer to // the start of the next line. also, output the newline since it wasn't // part of buffer above { int ch; do { ch = fgetc(fp); } while (ch != '\n' && ch != EOF); putchar('\n'); } line++; } ```
``` #include <stdio.h> int main() { int num[] = { 6, 8, 4, -5, 7, 9 }; int sum = 0; for (int i = 0; i < 6; i++) { for (int j = i + 1; j < 6; j++) { sum = num[i] + num[j]; if (sum == 15) { printf("%d\n%d", num[i], num[j]); } } } return 0; } ``` I'm trying to find a pair of numbers in the array with a sum of 15. The expected output is 6 & 9. But I'm getting output as 6, 98, 7. What is wrong? EDIT: The issue was not giving a new line after the first result. Sorry.
The issue was not giving a new line after the first result. replace printf("%d\n%d",num[i],num[j]); by ``` printf("%d,%d\n",num[i],num[j]); ```
Recently, I am trying to write a simple version of Linux commandmore. In order to do that, I need to enter noncanonical mode and non-echo mode in the terminal so that I get the input immediately after keypressing and terminal does not show the character I type. I did it by doing so: ``` // set the terminal mode struct termios tm; tcgetattr(STDIN_FILENO, &old); tm = old; tm.c_lflag &= ~(ICANON | ECHO); tm.c_cc[VMIN] = 1; tm.c_cc[VTIME] = 0; tcsetattr(STDIN_FILENO, TCSADRAIN, &tm); ``` This works when I use arguments like ``` more test_file ``` But when I tried to pipemorewith other command like ``` ls /bin | more ``` The terminal is back to canonical and echo mode. Why does this happen?
Generally speaking, things likemoreare expected to read fromstderr(or sometimes/dev/ttybutstderrworks better). You set terminal onstdininstead. That doesn't work so well.
I'm trying to write a C program that takes an input file name, and outputs a file with the same name but a different extension. For example, it would take in a file example.in and output example.out. I'm currently trying: ``` char *fname = argv[2]; char *fout = fname; ``` but I don't know how to proceed and change the extension of the file.
Check outstrrchr. From the man page: ``` The strrchr() function returns a pointer to the last occurrence of the character c in the string s. ``` This will allow you to identify where your "." is. From there, you can copy the beginning of the string to a new memory area, andstrcatthe ending on.
Example: ``` void *a = malloc(4); ... free(a); ... *a = 5; ``` In c for example is there a way of catching this error using some kind of system call or something? (assuming this is set up such that it can only be checked at runtime) if(isalloc (a))maybe? I'm wondering because c++ has figured it out somehow, except they have exceptions baked in. Can this be done in c? Perhaps a simple function exists, but I can't find it.
You can create such facility yourself. ``` #include <stdlib.h> #include <stdio.h> char _unallocated[] = ""; #define free(p) free(p); p = _unallocated #define isalloc(p) (p && p != _unallocated) int main() { void* a = _unallocated; printf("%d\n", isalloc(a)); a = malloc(4); printf("%d\n", isalloc(a)); free(a); printf("%d\n", isalloc(a)); } ```
I want to use a for loop to iterate through vector and when a certain condition is met, I want to go back to a certain element of vector and restart the loop from there. For example, let's say that my vector is 1,2,3,4,5,6,7,8,9; and when the first element that is bigger than 5 is met, I want to restart the loop from number 3 again. This is just an example. I don't know if I can write something like: ``` for(int i = 0; i < 8; i ++) { if(v[i] > 5) { i = 3; } } ``` Is this correct? If no, how can I do this using a for loop and the index of the vector?
Yes, it is perfectly fine to assign a value of choice to a loop variable inside the loop and its behaviour is well defined. You just have to realise that if this process leads to an infinite loop, you should put a check in place to be able to break out of the loop.
I need a solution to find the current used line in text file. I opened it with: ``` FILE *fp; fp=fopen(“data.txt”, “ r+“); ```
To keep track of which line in a file containing lines of text that you're currently processing, you could use a count variable. Here's a simple example ``` while (fgets(buffer, BUFLEN, fp) != NULL) { printf("Line %d: %s", line, buffer); if (buffer[strlen(buffer)-1] != '\n') // fgets didnt read an entire line, so increment the file pointer to // the start of the next line. also, output the newline since it wasn't // part of buffer above { int ch; do { ch = fgetc(fp); } while (ch != '\n' && ch != EOF); putchar('\n'); } line++; } ```
``` #include <stdio.h> int main() { int num[] = { 6, 8, 4, -5, 7, 9 }; int sum = 0; for (int i = 0; i < 6; i++) { for (int j = i + 1; j < 6; j++) { sum = num[i] + num[j]; if (sum == 15) { printf("%d\n%d", num[i], num[j]); } } } return 0; } ``` I'm trying to find a pair of numbers in the array with a sum of 15. The expected output is 6 & 9. But I'm getting output as 6, 98, 7. What is wrong? EDIT: The issue was not giving a new line after the first result. Sorry.
The issue was not giving a new line after the first result. replace printf("%d\n%d",num[i],num[j]); by ``` printf("%d,%d\n",num[i],num[j]); ```
Apple LLVM version 10.0.0 (clang-1000.10.44.4)Target: x86_64-apple-darwin18.0.0 ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #define _GNU_SOURCE #define __USE_GNU 1 #include <fcntl.h> int main() { int fd = open("./test.txt", O_WRONLY|O_DIRECT); close(fd); return 0; } ``` I useclang -o out test.cand get the following result: ``` test.c:14:39: error: use of undeclared identifier 'O_DIRECT' int fd = open("./test.txt", O_WRONLY|O_DIRECT); ``` How can I solve the problem? Thank you.
With this snippet it is impossible to tell what you are trying to do, but in general do not use nonstandard stuff in applications intended to be portable. The portable way to accomplish your task isprobablyfsync.
Using SWIG 2.0 to execute C code from python testing framework, pytest in my case. Is there a way to configure SWIG to generate code coverage reports of the executed C code? some integration withbullseye,gcovor other similar tools? Tried to look on the web and in SWIG documentation. Didn't find any useful resources. If there are any, please point me.
Eventually compiled the code withgcovinstrumentation and usedgcovrto generate the coverage report. All worked fine. To make this work, compile the code with the following flags (enables gcov instrumentation) ``` CFLAGS_VAL += -O0 --coverage ``` Then, execute the test,.gcnoand.gcdafiles should be generated. To create the report, run ``` gcovr -r . --filter="<src path>" --html --html-details -o coverage/coverage.html ``` GCOV docs,here Same can create with lcov, follow an example in thiswikipage
This question already has answers here:Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?(19 answers)Is it possible to modify a string of char in C?(9 answers)Closed4 years ago. I was looking at tutorials for C and pointers on the internet and found a debugging example and am wondering how to fix this block of code? I have been looking for a while and can't find out how to make it work. I want to replace the'i'in"Harris"with an"a". ``` char * ptr = (char *) "Harris"; ptr[4]="a"; ```
While you can assign a constant to a char pointer, you can't normally write to it. Fix your code: ``` char ptr []= "Harris"; ``` For not-your-legacy code use -fwritable-strings.
I have this error : warning: assignment makes integer from pointer without a cast[-Wint-conversion]TabPart[0].nom[20]="alami"; while compiling this code : ``` typedef struct { char nom[20]; char prenom[30]; int dej; int din; int hot; int num; }Participant; Participant TabPart[10]; TabPart[0].nom[20]="alami"; TabPart[0].prenom[30]="iliass"; TabPart[0].dej=0; TabPart[0].din=1; TabPart[0].hot=2; TabPart[0].num=1; ```
``` TabPart[0].nom[20]="alami"; ``` You should replace this by ``` strcpy(TabPart[0].nom, "alami"); ``` TabPart.nom[0] is achar, while "alami" is achar*(i.e. apointer to a char). You cannot assign to acharapointer to a char, as they are not compatible.
Do C pointer (always) start with a valid address memory? For example If I have the following piece of code: ``` int *p; *p = 5; printf("%i",*p); //shows 5 ``` Why does this piece of code work? According to books (that I read), they say a pointer always needs a valid address memory and give the following and similar example: ``` int *p; int v = 5; p = &v; printf("%i",*p); //shows 5 ```
Do C pointer (always) start with a valid address memory? No. Why does this code work? The code invokes undefined behavior. If it appears to work on your particular system with your particular compiler options, that's merely a coincidence.
This question already has answers here:Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?(19 answers)Is it possible to modify a string of char in C?(9 answers)Closed4 years ago. I was looking at tutorials for C and pointers on the internet and found a debugging example and am wondering how to fix this block of code? I have been looking for a while and can't find out how to make it work. I want to replace the'i'in"Harris"with an"a". ``` char * ptr = (char *) "Harris"; ptr[4]="a"; ```
While you can assign a constant to a char pointer, you can't normally write to it. Fix your code: ``` char ptr []= "Harris"; ``` For not-your-legacy code use -fwritable-strings.
I have this error : warning: assignment makes integer from pointer without a cast[-Wint-conversion]TabPart[0].nom[20]="alami"; while compiling this code : ``` typedef struct { char nom[20]; char prenom[30]; int dej; int din; int hot; int num; }Participant; Participant TabPart[10]; TabPart[0].nom[20]="alami"; TabPart[0].prenom[30]="iliass"; TabPart[0].dej=0; TabPart[0].din=1; TabPart[0].hot=2; TabPart[0].num=1; ```
``` TabPart[0].nom[20]="alami"; ``` You should replace this by ``` strcpy(TabPart[0].nom, "alami"); ``` TabPart.nom[0] is achar, while "alami" is achar*(i.e. apointer to a char). You cannot assign to acharapointer to a char, as they are not compatible.
Do C pointer (always) start with a valid address memory? For example If I have the following piece of code: ``` int *p; *p = 5; printf("%i",*p); //shows 5 ``` Why does this piece of code work? According to books (that I read), they say a pointer always needs a valid address memory and give the following and similar example: ``` int *p; int v = 5; p = &v; printf("%i",*p); //shows 5 ```
Do C pointer (always) start with a valid address memory? No. Why does this code work? The code invokes undefined behavior. If it appears to work on your particular system with your particular compiler options, that's merely a coincidence.
I am trying to setup my eclipse to run some C but there is this long tool in the toolbar which i am not even using and I do not know how to disable it. Can someone help me please?
This isWindow|perspective|customise|Tool Bar Visibility Perhaps this is a clue (photon launch bar): https://www.eclipse.org/forums/index.php/t/1095011/ They suggest it is on the launch bar preference page.
I wanna have characters 'ab' for each element in a table, but in console I have this: ``` tab[0] = argvab tab[1] = argvabab tab[2] = argvababab tab[3] = argvabababab ``` This is a part of my code: ``` char **tab = (char**)malloc((n) * sizeof(char*)); for (int i = 0; i < n; i++) { tab[i] = argv[1]; strcat(tab[i], "ab"); printf("tab[%d] = %s\n", i, tab[i]); } ```
``` tab[i] = argv[1]; strcat(tab[i], "ab"); ``` You're not allowed to append things to theargvstrings. They're fixed size blocks with no extra space. Appending invokes undefined behavior. Also even if you could you'd be appending toargv[1]each time rather thanargv[i]. Solution:(a) Changeargv[1]toargv[i], and (b) copy each argument before you append to it.
Here are the structure declarations: ``` typedef struct line { int width; char *theLine; } Line; typedef struct screen { int width; int height; Line *theScreen; } Screen; ``` Here is what I am using to try an initialize the Screen structure: ``` int main() { Screen b = {20, 40, {40, "-"}}; } ``` When I compile the above the result is: ``` warning: braces around scalar initializer [enabled by default] Screen b = {20, 40, {40, "-"}}; ^ ``` What am I doing wrong in the structure initialization? Also, once I am able to compile the code above, how would I access each member of the Line variable withing the struct screen? Any help is greatly appreciated, thank you.
You've defined the 3rd member as a pointer. WithLine theScreen;instead ofLine *theScreen;, your initialization code would work.
``` void main() { int sum=0; printf("%d",add(sum)); } int add(int x) { (x<=100) ? x=x+add(x+1) : x=0; return x; } ``` In the function, I am trying to print sum of first 100 natural numbers using recursion.But I'm getting error as "lvalue required as left operand of assignment". Can anyone help me solve this error and explain the concept behind it?
Since you're always settingx, putxon the left hand side. So instead of ``` (x<=100) ? x=x+add(x+1) : x=0; ``` use ``` x = (x <= 100) ? x + add(x + 1) : 0; ``` Alternately, since you're immediately returning that, you might just immediately return it: ``` return (x <= 100) ? x + add(x + 1) : 0; ``` The()in that expression are unnecessary, as well: ``` x = x <= 100 ? x + add(x + 1) : 0; // or return x <= 100 ? x + add(x + 1) : 0; ```
I am trying to compare two specific characters in two strings,but I want to make the comparingwithout case sensitivity. How can I do this? right now I am using a code like that: ``` if (str1[i]==str2[j]) printf("Equal"); ``` but I want to do this without case sensivity. Thank you in advance for taking your time to help!
You can use low case for both chars, for example by using tolower function: ``` if (tolower(str1[i])==tolower(str2[j])) printf("Equal"); ``` Also keep in mind: tolower does not work for multibyte char. So for those chars you should use other function
Since realizing that a string data type inCis actually an array ofchardata type with aNULLbyte as a terminator... What else could an array ofchars be used for other than as a string? In theClanguage, is there anything that an array of chars is used for that ISN'T a string?
charis just a small integer in C. It's frequently used for printable characters, and that's how it's used when you use achararray as a string. But achararray can be used whenever you need an array of bytes. A common use is when reading binary data from files or the network. Since the signedness ofcharis implementation-dependent, you should generally be more specific, eithersigned charorunsigned char. Modern versions of the C standard have added typedefsuint8_tandint8_t, for unsigned and signed 8-bit integer types.
I wanna have characters 'ab' for each element in a table, but in console I have this: ``` tab[0] = argvab tab[1] = argvabab tab[2] = argvababab tab[3] = argvabababab ``` This is a part of my code: ``` char **tab = (char**)malloc((n) * sizeof(char*)); for (int i = 0; i < n; i++) { tab[i] = argv[1]; strcat(tab[i], "ab"); printf("tab[%d] = %s\n", i, tab[i]); } ```
``` tab[i] = argv[1]; strcat(tab[i], "ab"); ``` You're not allowed to append things to theargvstrings. They're fixed size blocks with no extra space. Appending invokes undefined behavior. Also even if you could you'd be appending toargv[1]each time rather thanargv[i]. Solution:(a) Changeargv[1]toargv[i], and (b) copy each argument before you append to it.
Here are the structure declarations: ``` typedef struct line { int width; char *theLine; } Line; typedef struct screen { int width; int height; Line *theScreen; } Screen; ``` Here is what I am using to try an initialize the Screen structure: ``` int main() { Screen b = {20, 40, {40, "-"}}; } ``` When I compile the above the result is: ``` warning: braces around scalar initializer [enabled by default] Screen b = {20, 40, {40, "-"}}; ^ ``` What am I doing wrong in the structure initialization? Also, once I am able to compile the code above, how would I access each member of the Line variable withing the struct screen? Any help is greatly appreciated, thank you.
You've defined the 3rd member as a pointer. WithLine theScreen;instead ofLine *theScreen;, your initialization code would work.
``` void main() { int sum=0; printf("%d",add(sum)); } int add(int x) { (x<=100) ? x=x+add(x+1) : x=0; return x; } ``` In the function, I am trying to print sum of first 100 natural numbers using recursion.But I'm getting error as "lvalue required as left operand of assignment". Can anyone help me solve this error and explain the concept behind it?
Since you're always settingx, putxon the left hand side. So instead of ``` (x<=100) ? x=x+add(x+1) : x=0; ``` use ``` x = (x <= 100) ? x + add(x + 1) : 0; ``` Alternately, since you're immediately returning that, you might just immediately return it: ``` return (x <= 100) ? x + add(x + 1) : 0; ``` The()in that expression are unnecessary, as well: ``` x = x <= 100 ? x + add(x + 1) : 0; // or return x <= 100 ? x + add(x + 1) : 0; ```
I am trying to compare two specific characters in two strings,but I want to make the comparingwithout case sensitivity. How can I do this? right now I am using a code like that: ``` if (str1[i]==str2[j]) printf("Equal"); ``` but I want to do this without case sensivity. Thank you in advance for taking your time to help!
You can use low case for both chars, for example by using tolower function: ``` if (tolower(str1[i])==tolower(str2[j])) printf("Equal"); ``` Also keep in mind: tolower does not work for multibyte char. So for those chars you should use other function
OS: Debian 9 (Linux 4.9) Compiler: GCC 8.2 Currently I am including<stddef.h>(wheresize_tis defined) and<stdint.h>(where most integral types are defined), but I still don't havessize_t. Where is it defined?
ssize_tis defined insys/types.h. Perthe POSIX documentation: NAMEsys/types.h - data typesSYNOPSIS#include <sys/types.h>DESCRIPTIONThe header shall define at least the following types:...ssize_tUsed for a count of bytes or an error indication.
For example ,we can use#include<stdio>instead of#include<stdio.h>in c , And can we used user defined function as a header file without specifying its extension,and add a file with .mp3 extension.
For example, [can we] use#include<stdio>instead of#include <stdio.h> In theory, yes, a compiler could provide that feature. In practice, no, I have never encountered a C compiler that let you do that. Why do you want to do that? can we used user defined function without specifying its extension I don't understand this question. and add a file with .mp3 extension Nothing stops you from saving your C programs into files with an.mp3extension, instead of.c, and if you then run a C compiler on those files it'll probably compile them. But if you try to run a C compiler on a file that actually contains an audio recording in MP3 format, I don't see how that could possibly accomplish anything useful.
I have a slight problem with a Linux module compilation. No matter where I put a -lhidapi-libusb library reference in the make command, the module just refuses to compile. I know I'm doing something wrong, please help me, if you have some time. Thanks ``` obj-m += light.o all: make -lhidapi -libusb -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -lhidapi -libusb -C /lib/modules/$(shell uname -r)/build M=$(PWD) ``` Output: ``` fatal error: hidapi/hidapi.h: No such file or directory #include <hidapi/hidapi.h> ```
What you're trying to do doesn't make sense, and will not work. libusb and HIDAPI are userspace libraries. They cannot be used within a kernel module.
I want to put the value of anarrayinto a float integer. ``` main(){ float a; char array[4]="12.1"; a=atoi(array); printf("%f",a); } ``` When I uses this program, it gives12.000000as output but I want12.100000as output. Thanks in advance.
Use of this : atof()— Convert Character String to Float : ``` #include <stdlib.h> double atof(const char *string); ``` This linkexplains about that.
Was working with some SASL code today and noticed the==in the below snippet. I'm no C expert but the only way I've ever used that operator was to test equality. Bug? ``` if ( !conn ) { rc == LDAP_SUCCESS; goto done; } ```
That statement does nothing. It's a bug. Now, you COULD assign (rc == LDAP_SUCCESS) to a variable, which would store the boolean result of that operation (1 if true, or 0 if false).
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.Closed4 years ago.Improve this question I saw this special macro when I read a source code. If I remember correctly, it is defined in the standard library. The name of this macro is related to the buffer size, and in my machine its implementation is 1024. Now I want to use it to initialize the buffer but I forgot what it is called. So is there any one who can help me make my code look more professional? If I don't know what I am looking for specifically, how can I clearly say what I need?
Are you talking aboutBUFSIZ? It's a macro provided by<stdio.h>and it expands to the size of the buffer used bysetbuf(). I'm not sure what use it has in your own code.
I use Windows Subsystems for Linux(WSL), Ubuntu. I try compile simple code. I get errors in WSL. But, it works well in Visual Studio.
gets_s()is a "secure" alternative togets()defined in the Microsoft C Runtime Library. It is not included in the GNU C library used in Linux. For portability usefgets()on thestdininput stream instead.
I have created an android project on windows with ndk template. I want to include ndk-build project into android studio. This ndk-build project is working fine separately when I run ndk-build command. My requirement is to convert and use it in android studio so that I can debug the code on android mobile. At this time I am just using share library (so file) and call the required function from adb shell. I have copied all the source files of my separate ndk project into my android studio project and also added them into native-lib(created by default by android studio) library. But, I am getting an exception on including glib.h. I am not sure actually how to resolve it. Please suggest something.
Read this:https://developer.gimp.org/api/2.0/glib/glib-compiling.html I usually use the following:[To complie] ``` gcc `pkg-config --cflags --libs glib-2.0 dbus-glib-1` progname.c ``` Hope this will help you.
I use Windows Subsystems for Linux(WSL), Ubuntu. I try compile simple code. I get errors in WSL. But, it works well in Visual Studio.
gets_s()is a "secure" alternative togets()defined in the Microsoft C Runtime Library. It is not included in the GNU C library used in Linux. For portability usefgets()on thestdininput stream instead.
I have created an android project on windows with ndk template. I want to include ndk-build project into android studio. This ndk-build project is working fine separately when I run ndk-build command. My requirement is to convert and use it in android studio so that I can debug the code on android mobile. At this time I am just using share library (so file) and call the required function from adb shell. I have copied all the source files of my separate ndk project into my android studio project and also added them into native-lib(created by default by android studio) library. But, I am getting an exception on including glib.h. I am not sure actually how to resolve it. Please suggest something.
Read this:https://developer.gimp.org/api/2.0/glib/glib-compiling.html I usually use the following:[To complie] ``` gcc `pkg-config --cflags --libs glib-2.0 dbus-glib-1` progname.c ``` Hope this will help you.
This question already has answers here:How are floating point numbers stored in memory?(7 answers)Closed4 years ago. If we create one variable of data type float and assign any value to it then how this is stored in memory? float var = 13.34;
Float is a 4-byte size type, which consist of sign, exponent and mantissa (described in IEEE 754). The last bit represents sign, 8 followed bits are exponent and rest are mantissa.
I found the following declaration in thelshsource: ``` int (*builtin_func[]) (char **) = { &lsh_cd, &lsh_help, &lsh_exit }; ``` I'm relatively new to C, but the(*builtin_func[]) (char **)looks very odd. What does it mean? (I'm more interested in the declaration, not the purpose of the code.)
int (*builtin_func[]) (char **) It means that the variable builtin_func is defined as Incomplete array of pointers to functions that take pointer to pointer to char and return integers. Next, = { &lsh_cd, &lsh_help, &lsh_exit }; the list of initializers will complete the array , making it of 3 such pointers -- supposing that all 3 functions follow a similar signature.
I have just started c-programming and I have a problem to replace the least significant bit (LSB) with the most significant bit (MSB). For example, the first key (key is 32 bit) is 11110000, and after the transformation, it would be 11100001, and then 11000011, and then 10000111, 00001111, 00011110 and so on. Here is my code that I have tried: ``` for (int i = 0; i < 5; i++) { uint32_t a = (1 << 31) & key; key = (key << 1); key &= ~(1 << 1); key |= (a << 1); } ```
Assumingkeyis also of typeuint32_t, you can try this ``` for (int i = 0; i < 5; i++) { uint32_t a = key >> 31; //convert MSB to LSB key <<= 1; // shift key 1 bit to the left, (discarding current MSB) making space for new LSB key |= a; // append LSB } ```
This question already has answers here:How are floating point numbers stored in memory?(7 answers)Closed4 years ago. If we create one variable of data type float and assign any value to it then how this is stored in memory? float var = 13.34;
Float is a 4-byte size type, which consist of sign, exponent and mantissa (described in IEEE 754). The last bit represents sign, 8 followed bits are exponent and rest are mantissa.
I found the following declaration in thelshsource: ``` int (*builtin_func[]) (char **) = { &lsh_cd, &lsh_help, &lsh_exit }; ``` I'm relatively new to C, but the(*builtin_func[]) (char **)looks very odd. What does it mean? (I'm more interested in the declaration, not the purpose of the code.)
int (*builtin_func[]) (char **) It means that the variable builtin_func is defined as Incomplete array of pointers to functions that take pointer to pointer to char and return integers. Next, = { &lsh_cd, &lsh_help, &lsh_exit }; the list of initializers will complete the array , making it of 3 such pointers -- supposing that all 3 functions follow a similar signature.
I have just started c-programming and I have a problem to replace the least significant bit (LSB) with the most significant bit (MSB). For example, the first key (key is 32 bit) is 11110000, and after the transformation, it would be 11100001, and then 11000011, and then 10000111, 00001111, 00011110 and so on. Here is my code that I have tried: ``` for (int i = 0; i < 5; i++) { uint32_t a = (1 << 31) & key; key = (key << 1); key &= ~(1 << 1); key |= (a << 1); } ```
Assumingkeyis also of typeuint32_t, you can try this ``` for (int i = 0; i < 5; i++) { uint32_t a = key >> 31; //convert MSB to LSB key <<= 1; // shift key 1 bit to the left, (discarding current MSB) making space for new LSB key |= a; // append LSB } ```
I am a currently learning C and am stuck on a problem I was assigned. I have to create a function with a parameter of a int pointer, where the user can input an int, and then print out the int in the main method. Currently, I am able to input data and print it out properly within the method itself. However, when the data passes to the main function, it always prints "32766". How can I approach this problem? Thanks for your help. ``` int main(void) { int a; funct2(&a); printf("Int is %d", a); } void funct2(int *a){ int d; printf("Enter an Integer:: "); scanf("%d", &d); printf("%d\n", d); a = &d; ``` }
You wrotea = &d;to try to return your integer via pointer. Unfortunately that sets a infunct2to point todinstead. What you want is*a = d;.
I am creating a trivia game and am running a random function with the question out of a function array but I don't want that function to get picked again. Is there a way to do this? Here is my array: EDIT: ``` void (*level1_sports_functionptr[3])(void) = { level1_sportstrivia1, level1_sportstrivia2, level1_sportstrivia3 }; void (*level1_usa_functionptr[3])(void) = { level1_usatrivia1, level1_usatrivia2, level1_usatrivia3 }; void (*level1_world_functionptr[3])(void) = { level1_worldtrivia1, level1_worldtrivia2, level1_worldtrivia3 }; ```
Create an array of integers initialised with 0, 1, 2, 3, ... up to the number of elements in your question array - in your example just 0, 1, 2. Then apply a shuffle algorithm to this array such that the order of values is randomised. Then select the questions by selecting an index from the shuffled array in the order they appear in that array.
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.Closed4 years ago.Improve this question Surprisingly I can't find an easy reference on this, I want to compute: ``` float x = /*...*/; float next = nextint(x); ``` where next is strictly greater thanx(ie ifxis an integer, return the next higher integer). Ideally without branches.
You seem to want floor + 1: ``` float next = floorf(x) + 1; // or std::floor ``` Note that this gives you the mathematically next integer, rounded to nearest representable value, which for largexmay bexitself. This does not produce a strictly larger representable integer in such case. You should consider whether this is what you intend.
I am creating a trivia game and am running a random function with the question out of a function array but I don't want that function to get picked again. Is there a way to do this? Here is my array: EDIT: ``` void (*level1_sports_functionptr[3])(void) = { level1_sportstrivia1, level1_sportstrivia2, level1_sportstrivia3 }; void (*level1_usa_functionptr[3])(void) = { level1_usatrivia1, level1_usatrivia2, level1_usatrivia3 }; void (*level1_world_functionptr[3])(void) = { level1_worldtrivia1, level1_worldtrivia2, level1_worldtrivia3 }; ```
Create an array of integers initialised with 0, 1, 2, 3, ... up to the number of elements in your question array - in your example just 0, 1, 2. Then apply a shuffle algorithm to this array such that the order of values is randomised. Then select the questions by selecting an index from the shuffled array in the order they appear in that array.