{"question": "I am writing software that needs to compare two _mm256 vectors for equality. However, I would like there to be a margin of error +/- 0.00001. Eg, 3.00001 should be considered equal to 3.00002. Is there a simple way to do this using SSE/AVX/AVX2 instructions?\n", "answer": "Subtract values being compared, mask out sign with*_and_*or*_andnot_*, compare with*_cmpgt_*against your margin populated with*_set1_*\n"} {"question": "I found the following answer:Convert void* to double\n\nHowever, I am getting segmetation fault. Why is that?\n\nCode:\n\n```\nvoid * p = (void *) 1234;\ndouble n = *(double *)p;\n```\n", "answer": "Pointerpis assigned to address 1234 that you chose atrandom?. You are then referencing arandomaddress. It does not correspond to a valid allocated chunk of memory.\n"} {"question": "```\nFILE* file = fopen(some file)\n\npcap_t* pd = pcap_fopen_offline(file)\n\npcap_close(pd)\n\nfclose(file)\n```\n\nThis code occurs double free error.\n\nCould you explain about this happening?\n\nMy Guess is that pd and file pointers are sharing some datas.\n", "answer": "As the documentation says, thepcap_closefunction closes the files associated with thepcap_tstructure passed to it. Closing the file again withfcloseis an error.\n"} {"question": "Many programs assumesizeof(int)==sizeof(unsigned int). IMO it is not and I cant find anything in the Standard which guarantees it. Am I right or wrong?\n", "answer": "C11 6.2.5.6 (Types) says \"For each of the signed integer types, there is a corresponding (but different) unsigned integer type (designated with the keyword unsigned) that uses the same amount of storage (including sign information) and has the same alignment requirements.\"\n"} {"question": "I have trouble understanding the difference between bitwise concatenate and or.\nFor example, I have to bianry values which is 1111 and 0000.\nIf I do 1111 | 0000, will I get 1111 or 11110000?\nAnd if I get 11110000 as the result, when should I use | as or operation?\n", "answer": "1111 | 0000is1111. There is no bitwise concatenate operator. You can use left shift<> PD4;\n```\n\nI use STM32CubeIDE\n", "answer": "Assuming pin4 on port D.\n\n```\ndata_in = !!(GPIOD -> IDR & (1 << 4));\n```\n"} {"question": "I have the following piece of code:\n\n```\n#include \nint main() {\n printf(\"%c\",\"ACEGIK\"[3] - 1); \n return 0; \n}\n```\n\nI know that the result is F.\n\nWhat does the [3] -1 mean ?\n", "answer": "\"AGECIK\"is an array of chars\n\nyou're taking the third element (counting from 0)\"ACEGIK\"[3]that'sG\n\nsubtracting 1'G' - 1and getting characterF\n\n\n\n[3]is applied to the array\n\nwhile-1is applied to character/value got from the array\n"} {"question": "I have the following piece of code:\n\n```\n#include \nint main() {\n printf(\"%c\",\"ACEGIK\"[3] - 1); \n return 0; \n}\n```\n\nI know that the result is F.\n\nWhat does the [3] -1 mean ?\n", "answer": "\"AGECIK\"is an array of chars\n\nyou're taking the third element (counting from 0)\"ACEGIK\"[3]that'sG\n\nsubtracting 1'G' - 1and getting characterF\n\n\n\n[3]is applied to the array\n\nwhile-1is applied to character/value got from the array\n"} {"question": "Suppose that we have\n\n```\nint arr[3]; \nchar str[20] = \"{10,20,30}\";\n```\n\nIs it possible to initialise arr with str?\n", "answer": "You can't do that specifically, statically, but you can kind of do the reverse.\n\nYou can create a \"to string\" macro like this:\n\n```\n#define __STR(x) #x\n#define STR(x) __STR(x)\n```\n\nThen you can use it like this:\n\n```\n#define NUMS {10,20,30}\nint arr[3] = NUMS;\nchar str[] = STR(NUMS);\n```\n"} {"question": "I have CodeBlocks 13.12 and I want to compile a c99 code on it. Is there any way I can do this. If there is any other way to compile a c99 code, that is okay as well.\nThanks!\n", "answer": "From the option of add new flag I added-std=c99in the tab for compiler flag and it works.\n"} {"question": "Is there any way to store a glut color in a variable, like instead of doing this:glColor3f(1.0, 1.0, 1.0);being able to do this:\n\n```\nglColor white = glColor(1.0, 1.0, 1.0);\nglColor3f(white);\n```\n\nwhich in turn creates much more readable code\n", "answer": "I suggest to store the color in an array and set the color withglColor3fv:\n\n```\nfloat white[3] = {1.0f, 1.0f, 1.0f};\n```\n\n```\nglColor3fv(white);\n```\n"} {"question": "I want to create the following looking 2D array of \"-\"\n\n\n\nI attempted something like this but it did not work (for 10 by 10)\n\n```\nchar table[10][10];\n\nfor (int i = 0; i < 10; i ++){\n for (int j = 0; j < 10; j++)\n {\n strcpy(table[10][i], \"-\");\n }\n}\n```\n", "answer": "The whole 2D array?\n\nIf not strings, usememset(table, '-', sizeof table);to fill every byte with'-'. Noforloop needed.\n"} {"question": "I would like a method of flushing the instruction cache similar to__builtin___clear_cachein GCC but for clearing the instruction cache independent of the compiler. Is there any POSIX + C Standard compliant way to do this?\n", "answer": "There is no C Standard method of flushing the instruction cache.\n"} {"question": "Consider the following pointer declarations.\n\n```\nint *p[10];\n\nint (*q)[10];\n```\n\nWhat is the difference between 1st and second. How to read them in plain English?\n\nExample:\n\n```\nint *p; // it will be read as \"p is a pointer to an int\"\n\nint **p; // p is a pointer to an integer pointer.\n```\n", "answer": "int *p[10]is an array of10pointers toint.int (*q)[10]is1pointer to an array of 10ints.\n"} {"question": "Once I have enabledO_NONBLOCK, and then call a non-blocking function, and after it returns some I/O error happens, how may I get to know that something bad has happened, and how to handle it?\n", "answer": "You get the errors when they are ready for you to see them and you are ready to receive them.\n\nsooner or later you end up calling read() or close() or whatever and that will give you the error.\n"} {"question": "This question already has answers here:How to escape the % (percent) sign in C's printf(13 answers)Closed9 months ago.\n\n```\nprintf(\"%d \\% %d = %d\", 4, 3, 1);\n```\n\nI was expecting this to print \"4 % 3 = 1\", but instead it prints \"4 %d = 3\". How can I make this print the expected result? Does \"\\\" not disable the \"%\" following it?\n", "answer": "%%is the pattern to escape a%, so writeprintf(\"%d %% %d = %d\")\n"} {"question": "I have been looking through the documentation offopenandifstream, and what I cannot find is whether I need to seek to the beginning of a file after opening it. IthinkI can assume I don't need to, and experiments I have done support this hypothesis, but I find it safer to check.\n", "answer": "https://en.cppreference.com/w/c/io/fopen\n\nsays that it depends on the mode you open your file with. For example, if it's \"append\" -- the pointer is set to EOF.\n"} {"question": "I'm trying to print non-printable characters in C files, but I can't print the given character because I don't know its meaning. I noticed this when I compared my program with cat.\n\ncat -nt file.txt:\n\n```\n134 is 127 7f\n```\n\ncat -n file.txt:\n\n```\n134 ^? is 127 7f\n```\n", "answer": "In theCaret Notation(whichcatuses when-vor-tis specified)^?representsthe DEL character(Unicode U+007F, ASCII encoding 127 decimal, 0x7f in hex).\n"} {"question": "I need to write a recursive function with 2 parameters that calculate the result of their multiplication byonly using addition\n\nexemple :\nmult(2,5)=>10\n\nI wrote the function but I think that I'm missing something in the return\n\n```\nint mult(unsigned int num1, int num2) {\n if (num1 == 0) return 0;\n return mult(num1 - 1, num2);\n}\n```\n", "answer": "You should return:\n\n```\nreturn num2 + mult(num1 - 1, num2);\n```\n"} {"question": "What is a merit for the signed int return value of memcmp compared to say bool?\n\nI don't think I've ever used the return value of memcmp other than to compare it against zero.\n", "answer": "What is a merit for the signed int return value of memcmp\n\nUseful for sorting objects based on their binary representation.\n\nNote:memcmp()returns a +,0,- based on the first mismatched byte as if bytes areunsigned char, notchar.\n"} {"question": "I use-Werror ... -Wno-unknown-pragmascompiler flags (cause I don't need unknown pragmas to cause an error).\n\nHowever, this silences all unknown pragma warnings.\n\nIs there a way to produce-Wunknown-pragmaswarnings while not turning them into errors, and to apply-Werrorto all other warnings.\n", "answer": "-Werror -Wno-error=unknown-pragmasshould do the trick.\n"} {"question": "I'm using GCC version 10.2.1 in Linux Debian (x86-64).\ni write this c code:\n\n```\n#include \n\nint main() {\n printf(\"Hello World!\");\n return 0;\n}\n```\n\nNow my question is how can compile and run this code forarmv7l?\nTarget system Is a evaluation board\nthank you\n", "answer": "you can usearm-linux-gnueabihf-gcc hello.c -o hellocommand . and befor you should install arm-linux-gnueabihf-gcc in your linux system .\n\nhere is full sample that work for me\n"} {"question": "This question already has answers here:How can I print a quotation mark in C?(9 answers)Closed11 months ago.\n\nHow to print\"inprintf(\"something equal \"x(as char)\" \")??\n", "answer": "```\n#include \n \nint main(void) {\n printf(\"something equal \\\"x(as char)\\\" \");\n return 0;\n}\n```\n\nIn C, the escape character is\\.\nSo to print a literal\", instead of using it to end a string, use\\\".\n"} {"question": "In my code I have two char pointer, one to a string and the other as an error indicator forstrtoumax()andstrtod(). I am currently using the typesize_t(aka unsigned long) to calculate the difference between them. Is there any type designed to specifically match pointer type size on every machine? Or do I have to check it myself with macros?\n", "answer": "For pointer difference useptrdiff_t. If you're just trying to store a pointer as an integer, useuintptr_t(orintptr_t).\n"} {"question": "I have an integer array:\n\n```\nint s3[] = {97, 115, 100, 102, 103, 49, 50, 51, 37, 36, 33};\n```\n\nand I need its string value like\"asdfg123%$!\"\n\nsomething like this:\n\n```\nprintf (\"%s\", s4); // and output should be => asdfg123%$!\n```\n", "answer": "Copy the array item by item in a loop and store each value in achar. Then null terminate thatchararray so that it becomes a string. Or alternatively don't declares3asintto begin with.\n"} {"question": "Now I'm developing some software in the embedded Linux platform, I have some physical push buttons which I can read their pressing event through the file/dev/input/event1, in some special cases, I have to clear all event data stored in/dev/input/event1, but I don't know how.\n", "answer": "Open the file in non-blocking mode andread()until there is nothing more to read. Use a buffer of PAGESIZE or 4K for efficiency.\n"} {"question": "I have a code snippet to initialize a sockets in windows. How would I initialize the socket in Linux environment.\n\n```\nWSADATA wsa\n if(WAStartup(MkeWORD(2,2), $wsa) !=0 )\n {\n exit(0);\n }\n```\n", "answer": "On Linux you don't initialize a network environment like WSA. Sockets can be used out of the box.\nSeehttps://man7.org/linux/man-pages/man2/socket.2.htmlfor documentation.\n"} {"question": "I want to find all my c source files from parent directory, compile them and create a static library with them all at once. I tried thisar -rc libmylib.a < gcc -c < find ../ -type f -name '*.c'but it throws:\nbash: gcc: No such file or directory.\n", "answer": "gccdoesn't print the object file name so you'll have to divide it up into two command lines. Example:\n\n```\nfind .. -type f -name '*.c' -exec gcc -c {} \\;\nar -rc libmylib.a *.o\n```\n"} {"question": "In order to declare a struct in C, I have been using\n\n```\ntypedef struct Foo Foo;\n```\n\nand then defining it at some point below.\n\nWhy do I have to specify the name of the struct (Foo) twice?\n", "answer": "The format is\n\n```\ntypedef old_type new_type\n```\n\nso for\n\n```\ntypedef struct Foo Foo;\n```\n\nstruct Foois the old type andFoois the new type, so whenever you typeFooit is really an alias forstruct Foo.\n"} {"question": "How to compute the projection of a GNSS module at a heighthwithx, y, z, roll, pitch, yawdata on a flat ground?\n\nI searched online and couldn't find anything about how to handle such question.\n", "answer": "A place to start might be equation 1.78 in 'GPS for Geodesy' Edited by Kleugsberg and Teunissen which you can take a look at in pdfdrive.\n"} {"question": "The signature of the JNI_OnLoad function is this:\n\njint JNI_OnLoad(JavaVM *vm, void *reserved);\n\nWhat is the void *reserved parameter?\n", "answer": "Although the documentation doesn't explicitly say so, this parameter is reserved for future use and should be set toNULLin all cases.\n"} {"question": "I am studying C. How is this answer 110?\n\n```\n#include \n void main()\n\n {\n char c1,c2,sum ;\n c1='5';\n c2='9';\n sum= c1+c2;\n printf(\"sum=%d\",sum);\n\n }\n```\n", "answer": "The character'5'has an ascii value of 53.The character'9'has an ascii value of 57.\n\n53 + 57 == 110.\n"} {"question": "This question already has answers here:Getting a weird percent sign in printf output in terminal with C(3 answers)Closedlast year.\n\nwhen I useprintffunction in Visual Studio Code\nthere is always%character at the end of the line in terminal.\nwhy dose this happen??\n", "answer": "That is your terminal's shell prompt. You have not printed a newline character, so the prompt appears immediately after your program's output.\n\n```\nprintf(\"hello\\n\");\n```\n"} {"question": "I have two questions for you;\n\nIs there any way to just build and run c code internal terminal when I press to button given figure below. Just there is build and debug options.\n\n\n\nIs there any way to open debug in internal terminal not new pop-up window like figure below.\n\n\n\nHere is my task and json files.\n\n\n\n\n", "answer": "I handle this problem with code runner extension. First I added extension then from settings enabled run code in terminal.\n\n\n"} {"question": "I have two questions for you;\n\nIs there any way to just build and run c code internal terminal when I press to button given figure below. Just there is build and debug options.\n\n\n\nIs there any way to open debug in internal terminal not new pop-up window like figure below.\n\n\n\nHere is my task and json files.\n\n\n\n\n", "answer": "I handle this problem with code runner extension. First I added extension then from settings enabled run code in terminal.\n\n\n"} {"question": "I took a job interview and the following algorithm was asked and I didn’t manage to find out it’s purpose.\n\n```\nint func(int a, int b)\n{\n int c = b;\n while (c <= a)\n c <<= 1;\n int d = a;\n while (d >= b)\n {\n c >>= 1;\n if (c<= d)\n d -= c;\n }\n return d;\n}\n```\n", "answer": "This function returns the modulo (a%b).\n"} {"question": "When running a \"make\" command, fatal errors are returned due to missing linux headers.\n\nExample:\nfatal error: file not found\n", "answer": "I resolved this issue by creating aUbuntuvirtual machine (VM) usingVirtualBox.\n\nInstalled required softwareMounted shared folder\n\nThe make commands ran successfully in the vm.\n"} {"question": "i have a sensor\n\nThe datasheet says you can divide the data from the sensor by 100 to get the data you want.\nAnd for example, 0xff97 is -1.05km/h\n\nHow does 0xff97 become -1.05 km/h?\n", "answer": "0xFF97is-105in 16-bittwo's complement integer representation.\n\nIf you divide that number by100, then you get-1.05 km/h.\n"} {"question": "I'm attempting to use ptrace to manipulate registers on aarch64. Looking at sys/user.h in my aarch64 toolchain (android-ndk-r10e), I see\n\n```\n#elif defined(__aarch64__)\n\n// There are no user structures for 64 bit arm.\n\n#else\n```\n\nPerhaps I'm missing something obvious but how do I get/set registers for an aarch64 program?\n", "answer": "struct user_pt_regsis defined in asm/ptrace.h which is (eventually) included by sys/ptrace.h.\n"} {"question": "In openSSL I used functionSSL_CTX_set_verifywithverify_mode= SSL_VERIFY_PEERandverify_callback= NULL.\n\nWhat does it mean? The client will verify the server certificates chain or not?\n", "answer": "Reworded answer bySteffen Ullrich: The optional callback can be used to possibly override the built-in validation.\n"} {"question": "```\n#include\nint main()\n{\n int i = 577;\n printf(\"%c\",i);\n return 0;\n}\n```\n\nAfter compiling, its giving output \"A\". Can anyone explain how i'm getting this?\n", "answer": "%cwill only accept values up to 255 included, then it will start from 0 again !\n\n577 % 256 = 65; // (char code for 'A')\n"} {"question": "Im trying to make a widgets application inCwithSDL2and I've been wondering if there is anyway of making an SDL2 window not show up on the menu/window bar?\n\nTo hide something like this\n\nThanks!\n", "answer": "Take a look toSDL_WindowFlags,SDL_WINDOW_SKIP_TASKBARis what you are looking for.\n\n```\nUint32 flags = SDL_WINDOW_SKIP_TASKBAR;\nSDL_Window * window = SDL_CreateWindow(\n /* ... */\n flags\n);\n```\n"} {"question": "Doestmp = malloc(sizeof(x));the same automatically astmp = malloc(sizeof(x)); *tmp = x;?\n\nMore specifically, is malloc instantly initialising my variable or is it just allocating memory and I have to initialise it myself?\n", "answer": "No.\n\nThe memory returned by malloc isn't initialized.\n\nQuotingcppreference,\n\nAllocates size bytes of uninitialized storage.\n"} {"question": "Doestmp = malloc(sizeof(x));the same automatically astmp = malloc(sizeof(x)); *tmp = x;?\n\nMore specifically, is malloc instantly initialising my variable or is it just allocating memory and I have to initialise it myself?\n", "answer": "No.\n\nThe memory returned by malloc isn't initialized.\n\nQuotingcppreference,\n\nAllocates size bytes of uninitialized storage.\n"} {"question": "How can I get the Windows Hostname (NetBIOS) while coding a windows 10 kernel driver?\n\nI know GetComputerNameExA works in User mode, but how do I do the same in kernel mode?\n", "answer": "You can get hostname through the following registry path:\nHKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ActiveComputerName\n\nRead the registry.\n"} {"question": "So I have this script and I want to replace printed \"Dont\" with \"Lets\". I don't want to use system() since the effect is different.\n\n```\n#include \n\nint main(){\n printf(\"Dont do this\");\n /* Replace printed \"Dont\" with \"Lets\" */\n return 0; \n}\n```\n", "answer": "Try\\r:\n\n```\n#include \n\nint main(){\n printf(\"Dont do this\");\n printf(\"\\rLets\");\n printf(\"\\n\");\n return 0; \n}\n```\n"} {"question": "What are the different ways to find the number of elements in a int array pointer which is allocated with malloc?\n\nint* a = malloc(...)\n", "answer": "There are zero ways to do that outside of keeping track of it separately from the allocation.\n"} {"question": "I am doing all my assignments in a single .c file by writing functions, but now it seems that it affects the run time. Does it mean that if I do not call a function but define it then the function is also compiled and hence it slows down the program?\n", "answer": "No.\nThe only thing it affects is compile and link time and to some degree startup/load time (becauese of larger binary)\n\nMost compilers will strip (i.e. remove) unused code when optimizations are turned on.\n"} {"question": "Let's say I have this struct\n\n```\ntypedef struct \n{\n int AM;\n char* name, surname;\n}Item;\n```\n\nand I want to define a constant NULLitem with AM = -1 and NULL name/surname. Is there a way to do it with #define?\n", "answer": "```\n#define NULLitem (const Item){ .AM = -1, .name = NULL, .surname = NULL }\n```\n\nThat's a C99compound literal.\n"} {"question": "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\n\nFor example:\n\ntemp->next = NULLis same as(*temp).next = NULLlist->next->next = tempis same as ??\n", "answer": "It's the same as(*(*list).next).next = temp\n"} {"question": "I am facing problem to understand this line of code.\n\n```\nprintf(\"\\033[2J\\033[1;1H\");\n```\n\nThis printf statement is used to clear the terminal in c.\nCan anybody explain this to me?\n\nThanks.\n", "answer": "Take a look at the list of ANSI escape sequences:https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797\n\nESC[2J: erases the entire screen\n\nGeneral information:https://en.wikipedia.org/wiki/ANSI_escape_code\n"} {"question": "In the MDR32(similar with STM32) microcontroller, there is a 16-bit STAT register that describes the ethernet status, the documentation says that 7..5 bits indicate the number of received packets, how can I get this value and save it inuint16_tvariable?\n", "answer": "Depending on how you read your notation, to get bits 5, 6 and 7 from an integer you can simply do:\n\n```\nauto ethStatus = (stat >> 5) & 7;\n```\n"} {"question": "This question already has answers here:How to read a line from the console in C?(14 answers)Closedlast year.\n\nI have a string that I want to execute in C file and I'd like to get the string from standard input.\n\n```\necho \"Here is some random text.\\n\" | ./main.c\n```\n", "answer": "Read fromstdinlike any otherFILEstream.\n\n```\n#include\n\nint main()\n{\n char line[BUFSIZ];\n fgets(line, sizeof(line), stdin);\n printf(\"stdin: %s\", line);\n}\n```\n"} {"question": "I'm using the C SQLite library.\n\nI need to obtain the value of a blob from a row. The row is in a table that does not have any row id.\n\nThis causes sqlite3_blob_open to return an error - that rowid is not present in the table.\n\nSoftware like DB Browser for SQLite is able to query the value of these blobs, so there must be a way to do it.\n", "answer": "The answer is to use sqlite3_step() in conjunction with sqlite3_column_blob()\n"} {"question": "In the document, I found thatfgets_unlocked()is not thread-safe.\nHowever, I am not sure that can I usefgets_unlocked()without using any lock in a multi-threaded code, but ensure that each thread will access a different file (no two threads will access the same file)?\n", "answer": "If each thread usesfgetsof any kind to read from different files and write to different buffers, you're safe. There's nothing shared between threads in that case.\n"} {"question": "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?\n", "answer": "What you say isn't true. Usingsem_opento open an existing semaphore doesn't change its value.\n\nSo, to answer you question,\n\n```\nsem_t *sem = sem_open( name, O_RDWR );\nif ( sem == SEM_FAILED ) {\n perror( NULL );\n exit( EXIT_FAILURE );\n}\n```\n"} {"question": "I would like to run ansi C unit tests in VS by mean of Test Explorer (not only with Console).\n\nI 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.\n\nIs it feasable? And in case how? Thx.\n", "answer": "Yes, it is. See myexample.\n(To avoid LNK2019 error you shall include *.c to your test project, not *.h).\n"} {"question": "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?\n", "answer": "This is just how pointer arithmetic works in C.\n\nSubtracting 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).\n"} {"question": "please see attached image, where the stack and data area are nicely shown in the gdb as text:\n\n\n\noriginally found in herehttps://www.youtube.com/watch?v=KAr2cjLPufA&t=1390sat 24:30\n\nthe audio is not good so I didn't get the name for the extension.\n\ndoes somebody know and would be so kind to indicate a source?\n\nmuch appreciated.\n\ncheers.\n", "answer": "mammon . The guess ishttps://github.com/mammon/gdbinit, see the comments below the video.\n"} {"question": "```\n#define BIT(n) ( 1<<(n) )\n#define A BIT(0)\n\nvoid main(void)\n{\n if(A == 0)\n {\n }\n}\n```\n\nI 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?\n", "answer": "This is aknown bugin the C/C++ extension, which (seems like) will be fixed in the upcoming release 1.10\n"} {"question": "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.\n", "answer": "The source and target are clearly overlapping. So, yes, this counts.\n"} {"question": "```\n#include \nint main() \n{ \n printf(\"%d\", \"123456\"[1]);\n return 0;\n}\n```\n\nThe expected output is 123456, but it actually outputs 50. Why is that?\n", "answer": "\"123456\"[1]gives the character'2'. That character's ascii value is50.\n\nTo print the full number do:printf (\"%d\", 123456);orprintf (\"%s\", \"123456\");\n"} {"question": "I am trying to remove a route in Contiki if attack is detected. I am usingstruct route_entry *e; route_remove(e);\n\nBut I am getting the following error:undefined reference to 'route_remove'.\n", "answer": "route_removeis a Rime network stack function. By default, Contiki is built with uIP (IPv6) network stack, which does not have this function.\n\nTo remove a route when the IPv6 network stack is used,call this function:\n\nvoid uip_ds6_route_rm (uip_ds6_route_t *route).\n"} {"question": "Basically the title. I've been reading the manual pages and can't seem to make it work. Help would be much appreciated.\n", "answer": "Usegetopt_long()for function names.\n\nA detailed explanation is givenhere.\n\nThanks @Barmar for the suggestion!\n"} {"question": "I'm often using C code to take some input and manipulate it; for example, I want to scan a full phrase like \"hello world\" but as it contains a space, I find myself forced to use \"gets\" to include the spaces or even tabs sometimes.\n", "answer": "you cant usescanf()orfgets, just remember use thestdinas input stream\n"} {"question": "i only found K_ANY event in thedoc(Events and Callbacks -> Common -> K_ANY).\n\nhow do i handle keypress and keyrelease events separately?\nis it possible in this library?\n\ncan anyone help?\n", "answer": "Only on IupCanvas and derived controls using the KEYPRESS_CB callback. It has an extra parameter that indicates if the key is being pressed or released.\n"} {"question": "i only found K_ANY event in thedoc(Events and Callbacks -> Common -> K_ANY).\n\nhow do i handle keypress and keyrelease events separately?\nis it possible in this library?\n\ncan anyone help?\n", "answer": "Only on IupCanvas and derived controls using the KEYPRESS_CB callback. It has an extra parameter that indicates if the key is being pressed or released.\n"} {"question": "I am writing a code for Dots and boxes game in C and I need a function that exit the game and close the window based on an input from the user for example when he presses the letter 'e' on keyboard the game should close and I have no idea how to do that\n", "answer": "There are also predefined exit codesEXIT_SUCCESSandEXIT_FAILURE\n\n```\n#include \n\n...\n exit(0);\n...\n```\n\ne.g.exit(EXIT_SUCCESS);\n"} {"question": "I am writing a code for Dots and boxes game in C and I need a function that exit the game and close the window based on an input from the user for example when he presses the letter 'e' on keyboard the game should close and I have no idea how to do that\n", "answer": "There are also predefined exit codesEXIT_SUCCESSandEXIT_FAILURE\n\n```\n#include \n\n...\n exit(0);\n...\n```\n\ne.g.exit(EXIT_SUCCESS);\n"} {"question": "Alpine is a Linux distribution that I guess it must have the header files. How to solve it in alpine container?\n", "answer": "linux-headersshould be installed exlicitly in alpine linux.\n\n```\napk add linux-headers\n```\n"} {"question": "Alpine is a Linux distribution that I guess it must have the header files. How to solve it in alpine container?\n", "answer": "linux-headersshould be installed exlicitly in alpine linux.\n\n```\napk add linux-headers\n```\n"} {"question": "Trying to compile a c project then encountered error like below\n\n```\nundefined reference to `__llvm_profile_instrument_target'\nundefined reference to `llvm_gcda_start_file'\nundefined reference to `llvm_gcov_init'\n```\n", "answer": "It works withllvmcompiler too, just add--coverage.\n\nhttps://clang.llvm.org/docs/SourceBasedCodeCoverage.html\n"} {"question": "Trying to compile a c project then encountered error like below\n\n```\nundefined reference to `__llvm_profile_instrument_target'\nundefined reference to `llvm_gcda_start_file'\nundefined reference to `llvm_gcov_init'\n```\n", "answer": "It works withllvmcompiler too, just add--coverage.\n\nhttps://clang.llvm.org/docs/SourceBasedCodeCoverage.html\n"} {"question": "How can I copy a file without using standard C library functions in Linux? In other words, I would like to copy a file directly with system calls. Is it possible?\n", "answer": "file directly with system calls. Is it possible?\n\nIn pseudocode, usingsendfile:\n\n```\nint in = open(\"input\", ...);\nfstatat(in, &stat);\nint out = open(\"output\", ...);\nsendfile(in, out, NULL, stat.st_size);\n```\n"} {"question": "Is there any built-in for this operation (in C) ?\n\n```\nlock or QWORD [...], ...\n```\n\nIn fact, I'm searching forlock orin C.\n\nIf there isn't any built-in, how can I write it in C inline-asm ?\n\nI'm using GCC (C version 11).\n", "answer": "The standard C11 way of doing this is with andatomic_fetch_or. You can do things like:\n\n```\n#include \n\natomic_int var;\n\nint res = atomic_fetch_or(&var, 0x100);\n```\n"} {"question": "What is the use of thestat.hheader incat.c?\n\nHere you have thecat.c\n\nhttps://github.com/mit-pdos/xv6-riscv/blob/riscv/user/cat.c\n\nHere you have thestat.h\n\nhttps://github.com/mit-pdos/xv6-riscv/blob/riscv/kernel/stat.h\n\nI do not see any direct use of thestatstruct in thecat.cso I wonder if there is an indirect one.\n", "answer": "It was added inthis commitprobably becauseuser.huses thestruct stat *datatype\n"} {"question": "I've tried different types of string input(scanf, getchar, gets), but none of them can finish input with Enter. Do you guys have any ideas?\n", "answer": "As Cheatah said, the function you looking for isfgets(). Always try to avoidgets()as it offers no protections against a buffer overflow vulnerability and can cause big problems in your program. You can read some of the answers to this question to clarify the utility of each functionScanf() vs gets() vs fgets()\n"} {"question": "I've tried different types of string input(scanf, getchar, gets), but none of them can finish input with Enter. Do you guys have any ideas?\n", "answer": "As Cheatah said, the function you looking for isfgets(). Always try to avoidgets()as it offers no protections against a buffer overflow vulnerability and can cause big problems in your program. You can read some of the answers to this question to clarify the utility of each functionScanf() vs gets() vs fgets()\n"} {"question": "I just want to know if a line break (i.e. '\\n') can only be written to the stdout if 1 byte is used for such, I mean, does a line break have to be called like this?\n\n```\nwrite(1, \"\\n\", 1);\n```\n\nor can it be called like this?\n\n```\nwrite(1, \"\\n\", 0);\n```\n", "answer": "Bytes are bytes. There's nothing magical about\\nthat makes it not count. It has to be the former.\n"} {"question": "\"undefined reference to 'func~'\" error..\n\nI'm new to that program, so I can't figure out the reason for the error.\n\nenter image description here\n", "answer": "You need to add#include \n"} {"question": "I can only use POSIX standard library functions. I want to usesplicefunction. Is it POSIX or not? How can I find out?\n", "answer": "You can check man-pages:\n\n```\n$ man splice\n```\n\nItsays:\n\n```\nCONFORMING TO\n This system call is Linux-specific.\n```\n\nSo it is not in POSIX.\n"} {"question": "I can only use POSIX standard library functions. I want to usesplicefunction. Is it POSIX or not? How can I find out?\n", "answer": "You can check man-pages:\n\n```\n$ man splice\n```\n\nItsays:\n\n```\nCONFORMING TO\n This system call is Linux-specific.\n```\n\nSo it is not in POSIX.\n"} {"question": "\n\nwrite the post order of the above BST\n\nI,m confusing it starts with 50 or 60\n", "answer": "\"Post order\" means that a parent is always visitedafter(\"post\") its children are visited.. So if you would start with 50, you cannot visit 60 anymore, as that would violate that rule.\n\nThe post order thus starts like this: 60, 50, 80, ...\n\nAs this is an assignment, please figure out the rest yourself, just making sure you always abide to the above rule.\n"} {"question": "I usedffigento generate bindings from a C header file.\nOne of the methods in C isopen(const char *path), and ffigen generated a binding methodopen(ffi.Pointer path).\nIf I want to have a dart methodopen(String path)that access this binding method how can I convert the String parameter to ffi.Pointer?\n", "answer": "Try\n\n```\n\"Your message\".toNativeUtf8().cast()\n```\n\nAlso see erjo's comment inhttps://github.com/dart-lang/ffigen/issues/72\n"} {"question": "If I compile a C program on Windows 10, can that program run on Windows 7?\n\nIf I compile a C program on Windows 10 Home, can that program run on Windows 10 Pro?\n", "answer": "yes , you can run your program in any windows.I think knowing aboutcompile processcan help you.\n"} {"question": "I know that c works in two's complement but still i can't undrstand how the program below gives me 2147483647 as output.\n\n```\n#include\nint main(){\n\nint a=-2147483648;\na-=1;\nprintf(\"%d\",a);\n\n}\n```\n", "answer": "Becuase anintcan't contains the value-2147483648 - 1, so it result in an integer overflow, which leads to undefined behaviour. Undefined behaviour can result in anything.\n"} {"question": "```\n(gdb) print inputInfo\n$8 = (SObjectRecInput *) 0x7fffffffced0\n```\n\nFor example, when I want to check the value of inputInfo, it prints out:\n\n```\n0x7fffffffced0\n```\n\nAnd its type is 'SObjectRecInput'.\n\nHow to actually print out its value?\n", "answer": "inputInfoappears to have a pointer type, so dereference it:\n\n```\n(gdb) print *inputInfo\n```\n"} {"question": "I have an array of int pointers\n\n```\nint * arr[3];\n```\n\nIf I want to define a pointer toarr, I can do the following:\n\n```\nint * (*p)[] = &arr;\n```\n\nHowever, in my code, I need to first declare that pointer:\n\n```\nint *(*p)[];\n```\n\nMy question is, how to assign&arrto it after it has been declared. I have tried(*p)[] = &arr;but that didn't work.\n", "answer": "You can simply dop = &arr.\n\nTryhere.\n"} {"question": "This question already has answers here:Can a const variable be used to declare the size of an array in C?(5 answers)Closed1 year ago.\n\n```\n#include \nconst int TAILLE_MAX = 10; \nint iTableau[TAILLE_MAX]={3,6,0,8,97,0,5,6,0,8};\n```\n", "answer": "const int TAILLE_MAX = 10;is not a compile-time expression in C, so it cannot be used as a compile-time array size. Replace the expression with a macro:#define TAILLE_MAX 10\n\nSee alsothis StackOverflow question.\n"} {"question": "This question already has answers here:Can a const variable be used to declare the size of an array in C?(5 answers)Closed1 year ago.\n\n```\n#include \nconst int TAILLE_MAX = 10; \nint iTableau[TAILLE_MAX]={3,6,0,8,97,0,5,6,0,8};\n```\n", "answer": "const int TAILLE_MAX = 10;is not a compile-time expression in C, so it cannot be used as a compile-time array size. Replace the expression with a macro:#define TAILLE_MAX 10\n\nSee alsothis StackOverflow question.\n"} {"question": "How do i get this snippet of code to break the while loop with both \"a\" and \"A\"?\nI can't get the OR function right. Thanks in advance for the help.\n\nwhile((product = getchar()) !='a')\n", "answer": "If you want to break the loop whenproductisaorA, you need to check ifproductis notaandnotAin your loop condition:\n\n```\nwhile((product = getchar()) !='a' && product != 'A')\n```\n"} {"question": "When I compile the extension I've got, I'm getting\n\n```\nerror: ‘work_mem’ undeclared (first use in this function)\n 17 | Tuplestorestate *tupstore = tuplestore_begin_heap(true, false, work_mem);\n```\n\nWhat header includeswork_mem?\n", "answer": "Thework_memsymbol is provided bymisadmin.hyou will have to add that header into your.cfile.\n\n```\n#include \"miscadmin.h\"\n```\n"} {"question": "When I compile the extension I've got, I'm getting\n\n```\nerror: ‘work_mem’ undeclared (first use in this function)\n 17 | Tuplestorestate *tupstore = tuplestore_begin_heap(true, false, work_mem);\n```\n\nWhat header includeswork_mem?\n", "answer": "Thework_memsymbol is provided bymisadmin.hyou will have to add that header into your.cfile.\n\n```\n#include \"miscadmin.h\"\n```\n"} {"question": "Why this code doesn't printА?\n\n```\nint main() {\n char str[] = {0x0, 0x4, 0x1, 0x0};\n write(1, str, 4);\n}\n```\n\nInstead ofAit just print nothing and exit. This is strange because hexadecimal value ofAisU+0410.\n", "answer": "Follow this answerhttps://stackoverflow.com/a/6240184/14926026, you will see that the cyrillic A is not{0x0, 0x4, 0x1, 0x0}, but actually{ 0xd0, 0x90 }\n\n```\nint main()\n{\n char str[] = { 0xd0, 0x90 };\n write(1, str, 2);\n}\n```\n"} {"question": "enter image description here\n\nhow can I do this using scanf funtion ranging form -1000 to 1000 ?\njust %d numbers\n", "answer": "Try dooing a loop with ascanfand aprintfinside, like this:\n\n```\nint num = 0;\nfor(int i = 0; i < 5; i++){\n scanf(\"%d\", &num);\n printf(\"%d\", num);\n}\n```\n\nYou just need to change the5to the number of iterations you need.\n"} {"question": "enter image description here\n\nhow can I do this using scanf funtion ranging form -1000 to 1000 ?\njust %d numbers\n", "answer": "Try dooing a loop with ascanfand aprintfinside, like this:\n\n```\nint num = 0;\nfor(int i = 0; i < 5; i++){\n scanf(\"%d\", &num);\n printf(\"%d\", num);\n}\n```\n\nYou just need to change the5to the number of iterations you need.\n"} {"question": "Specifically \"the uri parameter may be a comma- or whitespace-separated list of URIs containing only the schema, the host, and the port fields\" what does this mean?\n\nWorking with openLDAP in c.\n", "answer": "It is simple list of URIs. The list can be separated by whitespace or comma:\n\nExample:\n\nhttp://myhost.com:4567,http://myhost1.com:45,http://myhost2.com:34545\n\nor\n\nhttp://myhost.com:4567 http://myhost1.com:45 http://myhost2.com:34545\n"} {"question": "This question already has answers here:Returning an array using C(8 answers)Closed1 year ago.\n\nHow do I return a char array with any length in C?\n\n```\nchar string[](int, int);\n```\n\ndoesn't work; is there a way to return a char array?\n", "answer": "You are unable to do that in C.\nInstead, return a pointer.\n\n```\nchar *string(int length, int unused) {\n char *s = calloc(x, sizeof(char));\n return s;\n}\n```\n"} {"question": "is it possible to buildpjsipwithopus-codecforwindowsas dll?\nI built pjsua2.dll alone but seems no way to use opus with it.\n", "answer": "I downloaded opus and pjsip , opened pjsip from visual studio solution, added opus projects to solution and made reference to them from libpjpproject, then build it using this linklink\n"} {"question": "```\nprintf(\"%f %.3f %.2f %.1f\", 4.5678, 4.5678, 4.5678, 4.5678);\n```\n\nI tried putting \\n at the end of the series of floats to separate the line\n\n```\nprintf(\"%f %.3f %.2f %.1f\", 4.5678, 4.5678, 4.5678, 4.5678)\\n;\n```\n", "answer": "That \\n should be inside the strings of printf not after it\n\n```\nprintf(\"%f %.3f %.2f %.1f \\n\", 4.5678, 4.5678, 4.5678, 4.5678);\n```\n"} {"question": "I am usingntdll.libfunctions in my code to set the system timer to a higher resolution.\n\nBut when I build my project I get this error:\n\n```\n...\n.../bin/ld.exe: ... undefined reference to `__imp_NtSetTimerResolution'\ncollect2.exe: error: ld returned 1 exit status\n...\n```\n\nHow do I tell the linker to link withntdll.libin my CMake?\n", "answer": "This worked for me:\n\n```\nif (WIN32)\n target_link_libraries(executable ntdll)\nendif()\n```\n"} {"question": "There are two floating point numbers 23.54 and 33.22 have to make a program to add them with just left side integral value like 23+33=56.\n\nHere's the code that I tried:\n\n\n", "answer": "```\nint sum;\nsum=(int)num1+(int)num2;\nprintf(\"%d\",sum);\n```\n\nor\n\n```\nprintf(\"%d\",(int)num1+(int)num2);\n```\n\nThe datatype of num1 is float and I'm using (int) to typecast to integer type.Since we typecast the datatype this is called explicit typecasting!\n"} {"question": "There are two floating point numbers 23.54 and 33.22 have to make a program to add them with just left side integral value like 23+33=56.\n\nHere's the code that I tried:\n\n\n", "answer": "```\nint sum;\nsum=(int)num1+(int)num2;\nprintf(\"%d\",sum);\n```\n\nor\n\n```\nprintf(\"%d\",(int)num1+(int)num2);\n```\n\nThe datatype of num1 is float and I'm using (int) to typecast to integer type.Since we typecast the datatype this is called explicit typecasting!\n"} {"question": "when I run the command\n\n```\npidof lh\n```\n\nfor lh program, I get two values. what are they. I was looking of pid oflhrunning program so I can increase the number of open files limithttps://unix.stackexchange.com/a/422732/211761\n\nWhy i am getting two values, if one is pid then what is the other\n\nOUTPUT\n\n```\n37354 7968\n```\n\nwhich one above is pid and what is the other number. please tell\n", "answer": "Both. You have two lh processes running.\n"} {"question": "From thispostand thiscodebase, I know that there are pointers for\n\nYoungest childYoungest siblingOldest sibling.\n\nSo withOldest child, how do I get?\n\nI am thinking of access \"children\" pointer (current->children) and traverse to the end of that doubly linked list.\n", "answer": "Get the oldest sibling of the youngest child:\n\n```\ncurrent->p_cptr->p_osptr\n```\n"} {"question": "I have a code that uses std=c++20.\n\nI want to use a C library that was build with old gcc version.\n\nShould I recompile the C library using the same compiler ?\n\nIf no, how could you judge that the 2 ABIs are compatible?\n", "answer": "There should be no problem using the library as it is. Don't forget to addextern \"C\"around the function prototypes.\n\nMore info:Using C Libraries for C++ Programs\n"} {"question": "From thispostand thiscodebase, I know that there are pointers for\n\nYoungest childYoungest siblingOldest sibling.\n\nSo withOldest child, how do I get?\n\nI am thinking of access \"children\" pointer (current->children) and traverse to the end of that doubly linked list.\n", "answer": "Get the oldest sibling of the youngest child:\n\n```\ncurrent->p_cptr->p_osptr\n```\n"} {"question": "I have a code that uses std=c++20.\n\nI want to use a C library that was build with old gcc version.\n\nShould I recompile the C library using the same compiler ?\n\nIf no, how could you judge that the 2 ABIs are compatible?\n", "answer": "There should be no problem using the library as it is. Don't forget to addextern \"C\"around the function prototypes.\n\nMore info:Using C Libraries for C++ Programs\n"} {"question": "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.Closed1 year ago.Improve this question\n\nI want to know how can I see the functions and the contents of a library in C language?\n", "answer": "isnm libconfig.a | c++filtwhat you are looking for?\n"} {"question": "I am programming a microcontroller (PSoC5), which doesn't have a system time.\n\nWhat is the best way to generate a seed to initializesrand?\n\nTIA\n", "answer": "If the chip has ADCs, one option is to take advantage of noise picked up on the ADCs. Basically, you can take a few reads of the ADCs, then bitwise AND to keep the least significant bit. Then use the all of the least significant bits sampled to generate your seed.\n"} {"question": "I'm doing a shell from scratch. If I store all tokens in an arraychar**, what I supposed to put in a string of arraychar**when quote is empty?\n\nExample:\n\n```\ninput>echo \"\" \"\" \"\" | cat -e\noutput>(space)(space)(space)$\n```\n", "answer": "If you're mimicking POSIX shells then each\"\"would tokenize to an empty string. The pipeline as a whole should tokenize to:\n\n```\nchar *tokens[] = {\"echo\", \"\", \"\", \"\", \"|\", \"cat\", \"-e\"};\n```\n"} {"question": "This question already has answers here:Splitting string into two integers(4 answers)Closed2 years ago.\n\n```\nstring input = 1999-12-05\nint year=1999\nint month=12\nint day=05\n```\n\nI want to split input to new three variable.Thank you.\n", "answer": "You can usesscanf:\n\n```\nchar* input = \"1999-12-05\";\nint year;\nint month;\nint day;\nsscanf(input, \"%d-%d-%d\", &year, &month, &day);\nprintf(\"year: %d, month: %d, day: %d\\n\", year, month, day);\n```\n\ndemo\n"} {"question": "I want to read the source code of winsock, but I only see header which is winsock.h. where is winsock.c located I need to read the source code implementation so bad.\n", "answer": "As to my knowledge Microsoft never released source code for that library. The best you can do is use Ida pro or simillar software to decompileWs2_32.dllorWs2_32.lib. That is the closest you will get to the source code, but it will be in pseudo C.\n"} {"question": "```\nunion one\n{\n int *ui;\n int u;\n \n} yoo;\n\nvoid main() \n{\n printf(\"%d\\m\", sizeof(yoo))\n}\n```\n\nWhy is the sizeof union not 8 bytes but 4 bytes even if I am using pointer in my union?\n\nI am using a 64 bit machine.\n", "answer": "Its because you have compiled it as 32-bit executable.\n"} {"question": "I want to do something similar to the code below but usingptr[i]\n\n```\nprintf(\"%s\\t%d\\n\", (ptr + i)->subject, (ptr + i)->marks);\n```\n", "answer": "ptr->xis the same as(*ptr).x.\n\n*(ptr + i)is the same asptr[i].\n\nThus, by the transitive property,(ptr + i)->xis the same as:\n\n```\nptr[i].x\n```\n"} {"question": "I want to do something similar to the code below but usingptr[i]\n\n```\nprintf(\"%s\\t%d\\n\", (ptr + i)->subject, (ptr + i)->marks);\n```\n", "answer": "ptr->xis the same as(*ptr).x.\n\n*(ptr + i)is the same asptr[i].\n\nThus, by the transitive property,(ptr + i)->xis the same as:\n\n```\nptr[i].x\n```\n"} {"question": "I am wondering what happens for variables & their content after STM32 mcu enters low power mode or exit from it? for example in sleep mode or standby.\ndo their content remove or survived?\n\nbest!\n", "answer": "You can preserve or not - it is usually (depending on the mode) up to the programmer. Memory consumes power so very often it is more energy efficient to reinitialize RAM after wake up (I do it sometimes in my projects)\n\nExample: STM32L476:\n\n\n"} {"question": "I'm working with a C-functionfoo(FILE* file)that outputs some text to a file.\n\nRather than write to a .txt file, I'd likefooto write to the console.\n\nIs there a way to pass 'the console' as a FILE*? (And if so, how) ?\n\n(foois part of a library and I can't edit the source code directly)\n", "answer": "There's a special file object calledstdoutthat will write to the console (assuming the shell didn't redirect anything).\n\n```\nfoo(stdout);\n```\n"} {"question": "I'm working with a C-functionfoo(FILE* file)that outputs some text to a file.\n\nRather than write to a .txt file, I'd likefooto write to the console.\n\nIs there a way to pass 'the console' as a FILE*? (And if so, how) ?\n\n(foois part of a library and I can't edit the source code directly)\n", "answer": "There's a special file object calledstdoutthat will write to the console (assuming the shell didn't redirect anything).\n\n```\nfoo(stdout);\n```\n"} {"question": "My Code:-\n\n```\n#include\nstruct Demo{\n int value;\n};\nint main(){\n struct Demo *l;\n l->value=4;\n}\n```\n\nGetting Segmentation fault (core dumped)\n", "answer": "because L object doesn't point something.\nuse this :\n\n```\n#include \nusing namespace std;\nstruct Demo\n{\n int val; \n};\nint main()\n{\n Demo* a = new Demo();\n a->val = 10;\n cout<val;\n}\n```\n\n\n"} {"question": "why my code is not printing all values of the array?\n\n```\n#include\n#include\nint main()\n{\n int arr[5]={1,2,3,4,5};\n int *a;\n a=&arr[0];\n int i=0;\n for(i=arr[i];i<5;i++){\n printf(\"%d\",*a);\n a=a+1;\n }\n}\n```\n", "answer": "I guess this is homework, correct? Check the index of your loop. What you want to do is that yourforloops five times, regardless of the content of your array.\n"} {"question": "Why 10.5 become 10.0 after swap ?\n\n```\n#define swap(a,b) {int aux; aux=a; a=b; b=aux;}\nfloat x=10.5, y=3.75;\n\nswap(x,y);\n\n// x=3.75, y=10.0;\n```\n", "answer": "auxis of typeint, which will drop the decimal part of the argumentapassed toswap. In this case,swap(x, y)drops the decimal part ofxbefore it is assigned toyat the end.\n"} {"question": "Why 10.5 become 10.0 after swap ?\n\n```\n#define swap(a,b) {int aux; aux=a; a=b; b=aux;}\nfloat x=10.5, y=3.75;\n\nswap(x,y);\n\n// x=3.75, y=10.0;\n```\n", "answer": "auxis of typeint, which will drop the decimal part of the argumentapassed toswap. In this case,swap(x, y)drops the decimal part ofxbefore it is assigned toyat the end.\n"} {"question": "Let's imagine I have\n\n```\nString x = \"hello there\";\n```\n\nSo I can print it from index e.g. 1 as:\n\n```\nSerial.println(x.substring(1));\n```\n\nello there\n\nI wanna do the same with\n\n```\nchar x[] = \"hello there\";\n```\n\nAny ideas?(Except using loops to print char by char)\n", "answer": "You can use the & operator to get the string after the desired index like this:\n\n```\nSerial.println(&x[1]);\n```\n"} {"question": "For debugging purposes, when there are many make file inclusions, it's useful to print the full path of the makefile where a particular variable in the current makefile was first defined. Is there a way to do that?\n", "answer": "Just runmake -p. Make will print its internal database including all targets and variables that were seen along with the filename and linenumber where they were set.\n"} {"question": "given that\n\n```\nint w = 1;\nint x = 6;\nint y = 5;\nint z = 0;\n \nz = !z || !x && !y;\nprintf(\"%d\\n\", z);\n\nz = x-- == y + 1;\nprintf(\"%d\\n\", z);\n```\n\nCould someone explain how the line below would evaluate to 1 if x-- is 5 and y+1 is 6?\n\n```\nz = x-- == y + 1;\n```\n", "answer": "The expressionx--evaluated to the value ofxbeforebeing decremented.\n\nSox-- == y + 1is the same as6 == 5 + 1which is true, then the value 1 is assigned toz.\n"} {"question": "given that\n\n```\nint w = 1;\nint x = 6;\nint y = 5;\nint z = 0;\n \nz = !z || !x && !y;\nprintf(\"%d\\n\", z);\n\nz = x-- == y + 1;\nprintf(\"%d\\n\", z);\n```\n\nCould someone explain how the line below would evaluate to 1 if x-- is 5 and y+1 is 6?\n\n```\nz = x-- == y + 1;\n```\n", "answer": "The expressionx--evaluated to the value ofxbeforebeing decremented.\n\nSox-- == y + 1is the same as6 == 5 + 1which is true, then the value 1 is assigned toz.\n"} {"question": "I am a bit rusty in programming, so I came here to ask what's the meaning of this line?\n\n```\nint (*f)(int, int)\n```\n", "answer": "Usehttps://cdecl.org/to translate thigs like that.\n\nint (*f)(int, int)=> declare f as pointer to function (int, int) returning int.\n"} {"question": "If I put an inline function in a .h file, then include that in the bridging header, can I invoke it in Swift? (Answer: Yes) But will it still be inline when invoked in Swift?\n", "answer": "The compiler will do what it wants but generally the answer isyes. This is part of why the atomics libraries and math shims that go down to C use header only inlined modules. So at least in release builds it can be fully optimized.\n\nSeethisfor example.\n"} {"question": "Using clang or clang++ the command ofclang -S -emit-llvm ./source.cwill create a llvm ir document. However debugging information is missing. So when you test and compile things you lose debugging information.\n\nHow does one can make clang emit human readable llvm ir document with debug information ?\n", "answer": "The standard option to add debug info is-g. So, runningclang -g -S -emit-llvm source.cwill emit necessary information\n"} {"question": "Using clang or clang++ the command ofclang -S -emit-llvm ./source.cwill create a llvm ir document. However debugging information is missing. So when you test and compile things you lose debugging information.\n\nHow does one can make clang emit human readable llvm ir document with debug information ?\n", "answer": "The standard option to add debug info is-g. So, runningclang -g -S -emit-llvm source.cwill emit necessary information\n"} {"question": "Imagine I havefile1.c,file2.c. First I compile one file withgcc -c file1.c -o file1.o. Is it OK to compile them together withgcc file1.o file2.c -o prog? I tried it and no errors are shown, but should I compilefile2.ofirst? Is it correct to mix.cand.ofiles?\n", "answer": "Yes, you can dogcc file1.o file2.c -o prog. You can also dogcc file1.c file2.c -o prog.\n\nGCC will handle compiling file2.c behind the scenes.\n"} {"question": "I'm getting the following error message from Clang 10:\n\n```\nerror: expected value in expression\n#if FOOBAR\n ^\n1 error generated.\n```\n\nNo further info. What could be the cause for this?\n", "answer": "What could be the cause for this?\n\nWhen the macro is defined to nothing\n\n```\n#define FOOBAR\n```\n\nthen\n\n```\n#if FOOBAR\n```\n\nexpands to just:\n\n```\n#if\n```\n\nAnd compiler prints an error -ifneeds an expression#if something-here.\n"} {"question": "\n\nif I write data to the middle of the allocated address space, will the file size increase. just likefseekdoes ?\n\nor it will write to the beginning of the file ?\n", "answer": "The answer is no. writeto mmap will not grow the file or create sparse file.\nI have to allocate the file manually.\n"} {"question": "In my rooted Android device,\n\n```\njint fd = open(\"/dev/ashmem\",O_RDWR);\n```\n\ngives -1 and fopen results in error 13. I've tried changing the permissions as well with chmod 777, but to no avail.\n\nAny ideas? Thank you for your help.\n", "answer": "Apps targeting Android 10 cannot directly use ashmem (/dev/ashmem) and must instead access shared memory via the NDK’s ASharedMemory class\n"} {"question": "In my rooted Android device,\n\n```\njint fd = open(\"/dev/ashmem\",O_RDWR);\n```\n\ngives -1 and fopen results in error 13. I've tried changing the permissions as well with chmod 777, but to no avail.\n\nAny ideas? Thank you for your help.\n", "answer": "Apps targeting Android 10 cannot directly use ashmem (/dev/ashmem) and must instead access shared memory via the NDK’s ASharedMemory class\n"} {"question": "I have a problem when comparing wchar_t with hex value.\n\n```\nwchar_t c;\nFILE *f = fopen(\"input1.txt\", \"r\");\nfwscanf(f, L\"%lc\", &c); // c is 'ệ'\nprintf(\"%d\", c == L'\\0x1ec7');\n```\n\n'ệ' is 0x1ec7 hex. But the result is 0. And how to compare wchar_t with hex value?\n", "answer": "The correct notation isL'\\x1ec7', notL'\\0x1ec7':\n\n```\n#include \n\nint main() {\n wchar_t const c = L'ệ';\n printf(\"%d\", c == L'\\x1ec7'); // prints 1\n}\n```\n"} {"question": "Like\n\n```\npri\nntf(\"hi\");\n```\n\nI can use \\ in macro but I think that doesn't work here :'(\n", "answer": "You can use\\\n\n```\npri\\\nntf(\"hi\");\n```\n\nDemo\n\nFrom draft N1570 of the C standard, section 5.1.1.2 Translation phases:\n\nEach instance of a backslash character ( \\ ) immediately followed by a new-line\ncharacter is deleted, splicing physical source lines to form logical source lines.\n"} {"question": "I need to create a matrix with 2 columns and unknown number of rows. I know I have to use malloc but I can't find how to declare such matrix. it should hold integers in the first column and doubles in the second. How do I do that?\n", "answer": "```\nstruct item {\n\n int i;\n double d;\n};\n\nstruct item matrix = malloc(sizeof(struct item) * number_of_rows)\n\nmatrix[0].i = 544343;\nmatrix[0].d = 0.3434343;\n```\n\nIs that the code you are looking for?\n"} {"question": "I need a macro that puts \"**\" before and after the string value, it should work someway like this:\n\n```\n#define M(x) \nputs(M(\"abc\"))\n```\n\nOutput:\n\n```\n**abc**\n```\n\nI've tried things like\n\n```\n#define M(x) \"**x**\"\n```\n\nbut it doesn't work :/Thanks in advance! :)\n", "answer": "Try\n\n```\n#define M(x) \"**\" x \"**\"\n```\n\nIt uses a feature that C compiler concatenates sequence of string literals.\n"} {"question": "if I have two header files\n\na.handb.h\n\ncan I include \"a.h\" in b.h\n\nand also include \"b.h\" in \"a.h\" ?\n", "answer": "You can, but it's not a very good idea. If you really must, you can prevent recursion with the use of include guards (which are a good idea regardless).\n\nIna.h:\n\n```\n#ifndef A_H\n#define A_H\n\n#include \"b.h\"\n\n#endif\n```\n\nandb.h\n\n```\n#ifndef B_H\n#define B_H\n\n#include \"a.h\"\n\n#endif\n```\n"} {"question": "How to call an executable C in script shell ?\nI did echoname_of_executable_filebut it didnt works\n", "answer": "You call it like this:\n\n```\n/path/to/name_of_executable_file\n```\n\nOr if it's in the current directory, like this:\n\n```\n./name_of_executable_file\n```\n"} {"question": "How to get RI pin status of serial port on a windows platform? I want to read the current state (ON or OFF) , when i get a call on a modem\n\nI can set the DTR pin with :\n\nEscapeCommFunction(hSerial,SETRTS);\n\nBut cant find an answer online on how to check the RI pin STATUS\n", "answer": "You have to useGetCommModemStatusfunction.\n"} {"question": "How to get RI pin status of serial port on a windows platform? I want to read the current state (ON or OFF) , when i get a call on a modem\n\nI can set the DTR pin with :\n\nEscapeCommFunction(hSerial,SETRTS);\n\nBut cant find an answer online on how to check the RI pin STATUS\n", "answer": "You have to useGetCommModemStatusfunction.\n"} {"question": "```\nfloat lgt = light.read();\nif(isnan(lgt)){\n printf(\"Failed to read light!\");\n}\n else{\n printf(\"%f\\n\",lgt);\n}\n```\n\nSecond printf always print '%f' in the console instead of 'lgt' value. Why could this happen? I'm using Mbed Studio.\n", "answer": "Why floating point formats in Mbed Studio don't work?\n\nBecause you are compiling your program with newlib nano version that does not support floating point format inprintffamily.\n"} {"question": "```\nfloat lgt = light.read();\nif(isnan(lgt)){\n printf(\"Failed to read light!\");\n}\n else{\n printf(\"%f\\n\",lgt);\n}\n```\n\nSecond printf always print '%f' in the console instead of 'lgt' value. Why could this happen? I'm using Mbed Studio.\n", "answer": "Why floating point formats in Mbed Studio don't work?\n\nBecause you are compiling your program with newlib nano version that does not support floating point format inprintffamily.\n"} {"question": "I use C language and I have problem with malloc\n\n```\ndouble** matrix = malloc(matrixSize * sizeof(double*));\n\n for (size_t i = 0; i < matrixSize; i++) {\n matrix[i] = malloc(matrixSize * sizeof(double));\n }\n\n return matrix;\n}`\n```\n", "answer": "malloc returns a void-pointer\n\nvoid*malloc(size_t size);\n\nso you will have to typecast this to double**\n\n```\ndouble** matrix = (double**)malloc(matrixSize * sizeof(double*));\n```\n"} {"question": "As mentioned by the title, I would like to achieve something like this:\n\n```\nvoid my_exit(int status)\n{\n#ifdef _GCOV\n __gcov_flush();\n#endif\n _exit(status);\n}\n```\n\nBut I do not know if there is a_GCOV(or something similar) defined when compiling with--coverage. Any idea will be appreciated!\n", "answer": "Doesn't seem to be:\n\n```\n$ true | gcc -E - -dM > no-coverage.h\n$ true | gcc -E - -dM --coverage > coverage.h\n$ diff no-coverage.h coverage.h\n```\n"} {"question": "```\nvoid Setup() {\n gameover = false;\n dir = STOP;\n\n x = width / 2;\n y = height / 2;\n\n fruitX = rand() % width; //display fruit in a random place\n fruitY = rand() % height; score = 0;\n}\n```\n", "answer": "Please use#include at the top of c code.\n"} {"question": "We have the variablea, that is the typechar*, that storeschars in an array. How are*(a + 2)anda[1]related?\n\na[1]points to the second element in the array and*(a + 2)points to the second element following the element pointed at to bya. So would the values of these two be the same?\n", "answer": "These arenotthe same.\n\nThe syntaxE1[E2]is exactly equivalent to*((E1) + (E2)). So*(a + 2)is the same asa[2]. It should now be clear that this is not the same asa[1].\n"} {"question": "We have the variablea, that is the typechar*, that storeschars in an array. How are*(a + 2)anda[1]related?\n\na[1]points to the second element in the array and*(a + 2)points to the second element following the element pointed at to bya. So would the values of these two be the same?\n", "answer": "These arenotthe same.\n\nThe syntaxE1[E2]is exactly equivalent to*((E1) + (E2)). So*(a + 2)is the same asa[2]. It should now be clear that this is not the same asa[1].\n"} {"question": "I am using windows 10 and MinGW-x64 gcc 8.1.0. I was trying to take a long double as input using scanf. Here is the code:\n\n```\n#include\n#include\n\nint main(int argc, char const *argv[])\n{\n long double a;\n scanf(\"%Lf\",&a);\n printf(\"%Lf\",a);\n\n return 0;\n}\n```\n\nthe output on the console is 0.000000.\nWhy is that so?\nIs it a windows issue?\n", "answer": "i guess in c mingw does not support long double datatype\n"} {"question": "I need to save a user input into a 2D array in a way where the user inputs something like '123456789' and I save that input into an array so that array[0][0] == 1, array[1][2] == 6 etc. Is there something like getchar() that I could use, but for numbers?\n", "answer": "You can use getchar() itself, and convert it to integer using:\n\n```\nchar c = getchar();\nint arr[3][3];\narr[0][0] = c - '0';\n```\n\nReferthisstackoverflow answer.\n"} {"question": "I know that a pointer points to a memory address, but is it possible to just use the&symbol instead of a pointer?\n", "answer": "&vwill get you the address of the variablev, but&vis an r-value, not an l-value.\n\nIn order to have an l-value containing the address of a variable you would have to use the*syntax, as inT *p = &v;.\n"} {"question": "I want to calculate a number to the powerp, gotSegmentation faultas a result.\nThis code is supposed to work:\n\n```\n#include \n\nint my_power(int nb, int p)\n{\n if (nb != 0){\n return nb*my_power(nb, p-1);\n }\n return 1;\n}\n\nint main(int argc, char argv[]){\n\n printf(\"%d\\n\", my_power(5, 3));\n return 0;\n}\n```\n", "answer": "In your code, your recursion never ends.\nChange the base case topb<=0and it will work.\n"} {"question": "I am trying to deep copy from one structure to another structure\nHowever structure has many pointers,how do I copy it in single statement?\nDo I have to manually copy each structure pointer member?\n", "answer": "You have to manually copy everything if you want a deep copy.\n"} {"question": "Follow-up question forthisanswer.\n\nIs there any hosted C implementations (__STDC_HOSTED__is 1) which haveCHAR_BIT > 8?\n\nIf so, then which ones?\n\nUPD. Fix typo: before:__STDC_HOSTED__is0, after:__STDC_HOSTED__is1.\n", "answer": "I don't know if there was ever a post-standardisation version, but various Cray 64-bit vector supercomputers had a C compiler in whichsizeof(long) == sizeof(double) == 1, a.k.a.everything is 64 bits wide.\n"} {"question": "```\n#include \n\nint main() {\n if (~0 == 1) \n printf(\"yes\\n\");\n else\n printf(\"no\\n\");\n}\n```\n\nwhy is theifstatement false? can anyone explain?\n", "answer": "~Binary One's Complement Operator is unary and has the effect of 'flipping' bits.\n\nSo when you do~0 == 1it will check for-1 == 1which is false\n"} {"question": "I'm trying to format a string like this:\n\n```\nprintf(\"%d%c\", buffer[i], i == num_ints-1? '': ',');\n```\n\nSo that the numbers print like this:\n\n```\n123,929,345\n```\n\nYet doing''is invalid. Is it possible to simulate a 'nothing-char' or just not do anything in the ternary?\n", "answer": "You can't have an empty char, but you can have empty strings. So use%s.\n\n```\nprintf(\"%d%s\", buffer[i], i == num_ints-1? \"\": \",\");\n```\n"} {"question": "I see that when I use that code:\n\n```\nchar c,d;\nscanf(\"%s\",&c);\nscanf(\"%s\",&d);\nprintf(\"%c%c\",c,d);\n```\n\nseems fix the problem of save ENTER character indvariable.\n\nIt's a good way or compiler add the string terminator in the memory address next tocvariable (equals fordvariable)?\n", "answer": "No, because it will also want to null-terminate the string. In other words, write to*(d + 1)(at least!), and that's undefined behavior (namely, overflow).\n"} {"question": "i am trying to find out how the Number of expected bytes is calculated with Function Code 2 in Modbus RTU.\n\nI am querying registers from 0 to 71, but as a response i am getting expected bytes as 9\nBelow is the Query and response.\n\nquery : 33 02 00 00 00 47 3C 2A\nresp : 33 020900 08 00 FE FF FF FF FF 03 FA 68\n", "answer": "You queried for 71 bits, the response has 9 bytes containing 8 bits per byte, any excess bits are ignored.\n"} {"question": "i am trying to find out how the Number of expected bytes is calculated with Function Code 2 in Modbus RTU.\n\nI am querying registers from 0 to 71, but as a response i am getting expected bytes as 9\nBelow is the Query and response.\n\nquery : 33 02 00 00 00 47 3C 2A\nresp : 33 020900 08 00 FE FF FF FF FF 03 FA 68\n", "answer": "You queried for 71 bits, the response has 9 bytes containing 8 bits per byte, any excess bits are ignored.\n"} {"question": "This is the algorithm to retrieve values from a2D array, what will be thetime complexityof this algorithm?\n\n```\nfor(i=0;i\nvoid main(){\n printf(\"hello\")\n}\n```\n\nMany thanks !\n", "answer": "After fixing the errors you can compile the code withgcc main.cand run the binarya.out.\nErrors as already mentioned:\n\nstudio.h->stdio.h...hello\")->...hello\");\n"} {"question": "I am new to C language but I useGitpodfor other languages. I would like to know how to run this simple \"hello world\" main.c program from the Gitpod interface step by step?\n\n```\n#include \nvoid main(){\n printf(\"hello\")\n}\n```\n\nMany thanks !\n", "answer": "After fixing the errors you can compile the code withgcc main.cand run the binarya.out.\nErrors as already mentioned:\n\nstudio.h->stdio.h...hello\")->...hello\");\n"} {"question": "I have a small project in C language and I want to implement the program, the program cuts off the WiFi network\n", "answer": "You can for example disconnect through a terminal command.\n\ne.g. in Windows OS\n\n```\nsystem(\"netsh wlan disconnect\");\n```\n\nexample.c\n\n```\n#include \n#include \n#include \n\nint main(void)\n{\n system(\"netsh wlan disconnect\");\n system(\"echo Wifi disconnected!\");\n return 0;\n}\n```\n"} {"question": "Whenever I create a.hfile, Airline interprets it as acppfile (in the filetype section). How do I set it toc?\n\nI couldn't find an answer online, and I don't know in where to change the source code of Airline to do what I want.\n", "answer": "Filetype is set by standard Vim ftplugin. To change the default\n\n```\nlet g:c_syntax_for_h = 1\n```\n\nSee:h c.vimfor more options.\n"} {"question": "I have a following line in C:\n\n```\nprintf(\"size of sizeof is %d\\n\", sizeof(printf(\"lol!\\n\")));\n```\n\nAm I getting the size of a function pointer here?\n", "answer": "Here,sizeofevaluates the return type ofprintf. (Here anint)\n"} {"question": "Actually my options are :\"C_Cpp.clang_format_fallbackStyle\": \"{ BreakBeforeBraces: Linux, IndentWidth: 4, ColumnLimit: 80, UseTab: Never, SortIncludes: false, AlignAfterOpenBracket: DontAlign }\"\n\nI have:\n\n```\nfor (int i = 0; i < 5; i++)\n ;\n```\n\nI want:\n\n```\nfor (int i = 0; i < 5; i++);\n```\n", "answer": "This is a known issue and it make a warning. The only way is to write this:\n\n```\nfor (int i = 0; i < 5; i++) {}\n```\n"} {"question": "Actually my options are :\"C_Cpp.clang_format_fallbackStyle\": \"{ BreakBeforeBraces: Linux, IndentWidth: 4, ColumnLimit: 80, UseTab: Never, SortIncludes: false, AlignAfterOpenBracket: DontAlign }\"\n\nI have:\n\n```\nfor (int i = 0; i < 5; i++)\n ;\n```\n\nI want:\n\n```\nfor (int i = 0; i < 5; i++);\n```\n", "answer": "This is a known issue and it make a warning. The only way is to write this:\n\n```\nfor (int i = 0; i < 5; i++) {}\n```\n"} {"question": "I want to initialize a value of all array members to their index.\n\n```\nint main()\n{\n int i;\n int arr[10];\n\n for (i = 0; i <= 9; i++)\n arr[i] = i;\n}\n```\n\nShould I consider the sequence point in this case?Isarr[i] = ilegal and portable?\n", "answer": "You need to consider sequence points if you modify something more than once in one place,orif you both read and modify something in one place.\n\nYou're not doing any of that, so your code is fine.\n"} {"question": "I have an array that I want to have in global scope. Its size however is determined during runtime, so I can't initialize it where I define it.\n\nHow can I declare it in global scope and assign its size in themainfunction?\n", "answer": "```\n#include // for malloc\n\nint *globalarray;\n\nint main()\n{\n ...\n globalarray = malloc(thesizeyouwant * sizeof(*globalarray));\n ...\n globalarray[0] = foo;\n ...\n free(globalarray);\n}\n```\n"} {"question": "I have an array that I want to have in global scope. Its size however is determined during runtime, so I can't initialize it where I define it.\n\nHow can I declare it in global scope and assign its size in themainfunction?\n", "answer": "```\n#include // for malloc\n\nint *globalarray;\n\nint main()\n{\n ...\n globalarray = malloc(thesizeyouwant * sizeof(*globalarray));\n ...\n globalarray[0] = foo;\n ...\n free(globalarray);\n}\n```\n"} {"question": "I have a C++ project, and the main file with the main function is a.c, but when I include my.hthat is supposed to be C++, I think I am getting errors because it thinks it is C. How can I tell it that my header should be C++ and not C, like my main?\n", "answer": "You cannot#includeC++ header in a C source file. A header is not compiled separately. All that#includedoes - it makes the compiler work as if the header was a part of the file.\n"} {"question": "How could I write it in C language? I tried many things, but it seems that I cannot understand the exp and sin functions.\n\n\n", "answer": "A direct implementation could be:\n\n```\ndouble y = exp(pow(sin(x),3)) + pow(x,6) - 2*pow(x,4) - pow(x,3) - 1.0;\n```\n"} {"question": "I would like to convert a double into character string and I findgcvt()and_gcvt(). I just wondering what is the difference between them. Both return withchar*and both need value, number of digits and buffer as a given parameters\n", "answer": "As per thegoogle search result\n\nThe_gcvt()function is identical togcvt(). Use_gcvt()for ANSI/ISO naming conventions.\n"} {"question": "Why doesthis functionin the Linux kernel take avoid *unusedparameter that serves no purpose in the body of the function?\n", "answer": "Because it is a callback.\nThe prototype of all callbacks used in this context must be equal, sometimes may have an unused parameter.\n\nkthread_runresquires a function like this in the first parameter:\n\n```\nint cb(void *param);\n```\n"} {"question": "The function was written to free a list i created earlier...\n\n```\nrekord *felszab(rekord *el)\n{\n rekord *temp;\n for(rekord *mozgo=eleje;mozgo=!NULL;mozgo=temp)\n {\n temp=mozgo->kov;\n free(mozgo);\n }\n return el;\n}\n```\n", "answer": "You call it without the prototype. Compiler assumes int as parameter and return value. Then it sees the definition having other types. Thus conflicting types\n"} {"question": "The function was written to free a list i created earlier...\n\n```\nrekord *felszab(rekord *el)\n{\n rekord *temp;\n for(rekord *mozgo=eleje;mozgo=!NULL;mozgo=temp)\n {\n temp=mozgo->kov;\n free(mozgo);\n }\n return el;\n}\n```\n", "answer": "You call it without the prototype. Compiler assumes int as parameter and return value. Then it sees the definition having other types. Thus conflicting types\n"} {"question": "```\nprintf(\"%i\\n\",2&2==2);\n```\n\nThis should print out a 1 but I get a 0, why is this?\n\n```\nint ans=2&2;\nprintf(\"%i\\n\",ans==2);\n```\n\nThis prints a 1, how come the first way does not work?\nThis is the case with if statements as well\n", "answer": "The order of operations is different than you think it is. A correct way to write it in a single line would be:\n\n```\nprintf(\"%i\\n\", (2 & 2) == 2); // Prints 1\n```\n"} {"question": "```\nint main() {\n x=5;\n printf(\"%d\",x+3);\n}\n```\n\nxcould be either5or8after this example (I know that the output on the screen would be 8.)\n", "answer": "The value at the address ofxremains unchanged in this example. Inside theprintf, we first get the value at the address ofxand then add it to 3 and output it to the screen.\nThis is why we use statements likex=x+3to change the value.\n"} {"question": "I've use cURL command-line tool with --libcurl and a url of mine(the url works in normal C), however I get the error \"curl.h\" does not exist, although it is in the same directory. I can't figure out how to include headers in emscripten. All of the supposed documentation on this usually ends up being about something else entirely.\n", "answer": "I figured it out, I was being dumb\n"} {"question": "If I have the following lines of code, why is b-a = 2?\n\n```\nint a[] = {1,2,3,4,5}; \nint *b = &(a[2]);\n```\n", "answer": "To elaborate slightly on Eugene's answer,ais a pointer to the beginning of the array, anda[2]is the same as*(a+2).\n\nSo you could say that the&\"cancels\" the*as you dereference the pointer and then look at the address of the element that it points to. So*b = &(a[2]) = &(*(a+2)) = a+2.\nThereforeb-a=2\n"} {"question": "I can use GCC to convert assembly code files into reallocatable files.\n\n```\ngcc -c source.S -o object.o -O2\n```\n\nIs the optimization option effective? Can I expect GCC to optimize my assembly code?\n", "answer": "No.\n\nGCC passes your assembly source through the preprocessor and then to the assembler. At no time are any optimisations performed.\n"} {"question": "My input is: 1 + 2\n\nI found that the value stored inargv[2][1]andoparen't the same, I just want to see if they are both the \"+\" operand.opstores the ascii value of \"+\" whileargv[2][1]stores some random value. How would I compare them?\n\n*I don't want to use \"strcmp\"\n\n\n", "answer": "Array indexes start at0, so you need to use[0]to compare the first character of the argument.\n\n```\nif (argv[2][0] != c) {\n```\n"} {"question": "```\nunsigned int file = open(argv[1], O_RDONLY);\n\nprintf(\"%u\\n\", file);\nprintf(\"%u\\n\", elf.offset);\n\nlseek(file, elf.offset, SEEK_SET);\n\nprintf(\"%u\", file);\n```\n\nOutPut:\n\n```\n3\n52\n3\n```\n\nShouldn'tfilebe set to52?\n", "answer": "Upon successful completion, the resulting offset, as measured in bytes from the beginning of the file, shall be returned.\n\ntry thisprintf(\"lseek_offset: %d\\n\", lseek(file, elf.offset, SEEK_SET));\n"} {"question": "```\nunsigned int file = open(argv[1], O_RDONLY);\n\nprintf(\"%u\\n\", file);\nprintf(\"%u\\n\", elf.offset);\n\nlseek(file, elf.offset, SEEK_SET);\n\nprintf(\"%u\", file);\n```\n\nOutPut:\n\n```\n3\n52\n3\n```\n\nShouldn'tfilebe set to52?\n", "answer": "Upon successful completion, the resulting offset, as measured in bytes from the beginning of the file, shall be returned.\n\ntry thisprintf(\"lseek_offset: %d\\n\", lseek(file, elf.offset, SEEK_SET));\n"} {"question": "This question already has answers here:What is the meaning of a dot (.) after an integer in c?(2 answers)Closed2 years ago.\n\nI read a code online and the next line caught my attention since I don't know why does it have a \".\" after the 0:\n\n```\nvariable=0.;\n```\n\nI couldn't find the answer after looking for it. Could you please tell me what is the dot for?\n\nThanks!!\n", "answer": "The dot makes it adouble. A clearer way to write it is0.0.\n"} {"question": "As far as I know, ~0x00 equals to:\nFirst step, change 0's to 1 and 1's to zero, Second step, add 1\nStep 1: 11111111111111111111111111111 (count =32)\n\nStep 2: 11111111111111111111111111111+1=0\n\nWhere am I doing wrong?\n", "answer": "The~operator does not perform 2's complement negation. You can do that with the unary-operator (assuming your machine uses 2's complement representation).\n\nWhat~does is invert all bits. That's all it does, no adding 1.\n"} {"question": "As far as I know, ~0x00 equals to:\nFirst step, change 0's to 1 and 1's to zero, Second step, add 1\nStep 1: 11111111111111111111111111111 (count =32)\n\nStep 2: 11111111111111111111111111111+1=0\n\nWhere am I doing wrong?\n", "answer": "The~operator does not perform 2's complement negation. You can do that with the unary-operator (assuming your machine uses 2's complement representation).\n\nWhat~does is invert all bits. That's all it does, no adding 1.\n"} {"question": "When I use the following code I tried to replicate the idea thatsqrt(x)of something equalsX^(1/2)\n\n```\npow(x, (1/2);\n```\n\nIt returned 1 no matter what value I entered. I already solved this issue with the sqrt function but wanted to know why this is happening for the future.\n", "answer": "In it's original form,1/2is integer division, producing a result of0.\n\nMath 101: Anything raised 0, is 1.\n"} {"question": "Within C how can I name a function? Just the name.\n\ntypedef strlen StringLengthfails to compile with:strlen does not name a type.\n", "answer": "A function pointer is a solution\n\nstatic Integer(*StringLength)(const Byte*) = strlen;\n"} {"question": "Why am I getting an error when using theatoi()function?\n\n```\n#include \n#include \nint main()\n{\n char s1[10], s2[10];\n int x=5, y=6, z;\n sprintf(s1, \"%d\", x);\n sprintf(s2, \"%d\", y);\n strcat(s1, s2);\n z = atoi(s1);\n printf(\"%d, %s\", z, s1);\n return 0;\n}\n```\n", "answer": "```\n#include \n```\n\nWill fix it.\n"} {"question": "Here's my code:\n\n```\n#include \nint main (void)\n{\n BIO* bo = BIO_new(BIO_s_mem());\n}\n```\n\nI'm compiling my code by doinggcc -lcrypto test.c.\n\nAny idea what's wrong?\n", "answer": "You have the arguments in the wrong order, trygcc test.c -lcrypto\n\nSeewhy order matters\n"} {"question": "When I received packet withrecvat linux, is the kernel did de-fragmentation so I will get de-fragmentation data? Or should I take care of it on user-space?\n", "answer": "When receiving UDP data via a socket of typeSOCK_DGRAM, you'll only receive the complete datagram (assuming your input buffer is large enough to receive it).\n\nAny IP fragmentation is handled transparently from userspace.\n\nIf you're using raw sockets, then you need to handle defragmentation yourself.\n"} {"question": "When analyzing core on different machine, that binary was built for I ran into:\n\n```\nwarning: .dynamic section for \"/lib64/libc.so.6\" is not at the expected address (wrong library or version mismatch?)\n```\n\nIs there a way to change which libc gdb is looking for?\n", "answer": "Thanks to@Kevin Boone!\n\nset sysroothelped I set it to./and put desired libc in./lib64and then loaded core usingcore-file\n"} {"question": "I use theMin-GW GCC compileronWindows 10. Every time I compile, I need to make a.exeand then run it. Could there be any way to do the whole thing in one step?\n", "answer": "You can combine commands in windows like you do on linux or macos!\n\n```\ngcc compilefile && c:/executefile.exe\n```\n\n(you need to replace that stuff with min-gw and your exe path)\n\nlinks:\n\nHow do I run two commands in one line in Windows CMD?How to run an executable in Windows Terminal?\n"} {"question": "When analyzing core on different machine, that binary was built for I ran into:\n\n```\nwarning: .dynamic section for \"/lib64/libc.so.6\" is not at the expected address (wrong library or version mismatch?)\n```\n\nIs there a way to change which libc gdb is looking for?\n", "answer": "Thanks to@Kevin Boone!\n\nset sysroothelped I set it to./and put desired libc in./lib64and then loaded core usingcore-file\n"} {"question": "I use theMin-GW GCC compileronWindows 10. Every time I compile, I need to make a.exeand then run it. Could there be any way to do the whole thing in one step?\n", "answer": "You can combine commands in windows like you do on linux or macos!\n\n```\ngcc compilefile && c:/executefile.exe\n```\n\n(you need to replace that stuff with min-gw and your exe path)\n\nlinks:\n\nHow do I run two commands in one line in Windows CMD?How to run an executable in Windows Terminal?\n"} {"question": "Let's say I have aforloop and an array of ints. In myforloop, I sayif (array[i] == 2)then I want to skip all the rest of theforloop and go to the next instance. now I can't use thebreakkeyword as that will exit out of the entire loop.\n\nWhat can I use to exit out of only one instance?\n", "answer": "You have to use continue to go to the next iteration:\n\n```\nif (array[i] == 2) continue;\n```\n"} {"question": "Let's say I have aforloop and an array of ints. In myforloop, I sayif (array[i] == 2)then I want to skip all the rest of theforloop and go to the next instance. now I can't use thebreakkeyword as that will exit out of the entire loop.\n\nWhat can I use to exit out of only one instance?\n", "answer": "You have to use continue to go to the next iteration:\n\n```\nif (array[i] == 2) continue;\n```\n"} {"question": "Imagine I have a struct for a linked list:\n\n```\nstruct node{\n int data;\n struct node* next;\n struct node* prev;\n};\n```\n\nI free the last node; does thenextpointer of the node before it becomeNULLautomatically?\n\nBecause I noticed I didn't do it in a program but everything runs fine..\n", "answer": "No.\n\nAs for why your program appeared to run OK even if you forgot to reset a pointer, it could be you just got lucky.\n"} {"question": "Can anyone explain how does this work the output is A3 but how come it print 3\n\n```\n#include \n\nint main() {\n int i;\n if(printf(\"A\"))\n i=3;\n else\n i=5;\n printf(\"%d\",i);\n}\n```\n", "answer": "printf()returns the number of characters upon success and negative values on failure.\n\nTherefore, ifprintf(\"A\")succeeds, it will return1.\n\nIn C, values other than0is treated as true, soi=3;is executed.\n"} {"question": "I want to print my string which is \"Something\"without the first N lettersinside theprintfstatement.\n\nExample 1: I can do the \"opposite\" (printfjust N first letters):\n\n```\n#include \nint main() {\n char str[] = \"Something\";\n printf(\"%5s\", str);\n}\n```\n\nOutput:Somet\n\nExpected Output:hing\n", "answer": "Start the printing in the middle:\n\n```\nprintf(\"%s\", &str[5]);\n```\n"} {"question": "I have problem with NVIC registers in Keil.\nin my data sheet NVIC starts with NVIC_ISERx\n\n\n\n\n\nBut in keil starts with ICTR register\n\n\n\nSo I have problem with matching addresses\n", "answer": "the order of the properties is not the same as the order in the peripheral.\n\nIt is clearly visible here:\n\n\n\n\n"} {"question": "I would like to figure out the memory address of the following:\n\n```\n>>> ($rbp + $rdi*2 - 8)\n```\n\nAnd then once I have that value, inspect that memory address with:\n\n```\n>>> x/wx $address\n```\n\nHow would I do this in gdb?\n", "answer": "You can type this in directly after thep(rint) command. For example:\n\n```\n>>> p/x ($rbp + $rdi*2 -8)\n$2 = 0x7fffffffe43e\n\n>>> x/hx $\n0x7fffffffe43e: 0x001b # 27\n```\n\nThe$symbol stores the last value.\n"} {"question": "I would like to figure out the memory address of the following:\n\n```\n>>> ($rbp + $rdi*2 - 8)\n```\n\nAnd then once I have that value, inspect that memory address with:\n\n```\n>>> x/wx $address\n```\n\nHow would I do this in gdb?\n", "answer": "You can type this in directly after thep(rint) command. For example:\n\n```\n>>> p/x ($rbp + $rdi*2 -8)\n$2 = 0x7fffffffe43e\n\n>>> x/hx $\n0x7fffffffe43e: 0x001b # 27\n```\n\nThe$symbol stores the last value.\n"} {"question": "Does C have a#includesimilar to C++ ? I have been looking for the past week. I can't find a equivalent directive preprocessor!\n", "answer": "No, it does not. There are, however, ways to implement what you are looking for (or at least some sort of approximation). Take look at:http://c-faq.com/misc/bitsets.html- I think it is going to be useful.\n"} {"question": "I want to scan a value, and print the value that was scanned\n\n```\nint main()\n{\n int n;\n printf(\"enter value: \");\n n = scanf(\"%d\",&n);\n printf(\"%d\",n);\n return 0;\n}\n```\n\nhowever, the printed result gave me 1 instead of 9 as shown below. Why is this so and how do i solve this?\n\n\n", "answer": "Becausenget override by the return value of scanf\n\nJust usescanf(\"%d\", &n);if you don't want the number of parsed items assigned ton.\n"} {"question": "I want to scan a value, and print the value that was scanned\n\n```\nint main()\n{\n int n;\n printf(\"enter value: \");\n n = scanf(\"%d\",&n);\n printf(\"%d\",n);\n return 0;\n}\n```\n\nhowever, the printed result gave me 1 instead of 9 as shown below. Why is this so and how do i solve this?\n\n\n", "answer": "Becausenget override by the return value of scanf\n\nJust usescanf(\"%d\", &n);if you don't want the number of parsed items assigned ton.\n"} {"question": "This question already has answers here:Why is the gets function so dangerous that it should not be used?(13 answers)Closed3 years ago.\n\nWhy is implicit declaration of gets() not allowed in C99?I had referred this question, which was how I came to know about it's deprecation.\n", "answer": "Yes, you should usefgets()instead.\n"} {"question": "This question already has answers here:Why is the gets function so dangerous that it should not be used?(13 answers)Closed3 years ago.\n\nWhy is implicit declaration of gets() not allowed in C99?I had referred this question, which was how I came to know about it's deprecation.\n", "answer": "Yes, you should usefgets()instead.\n"} {"question": "I'm trying to make changes and compile open source 3d printers firmware in eclipse. Added all the project related to firmware but it showing symbol could not be resolved error. The cause of error is IDE cannot find the symbols. How can I solve this. It's compiling properly and also working on board.\n", "answer": "Found the solution in indexer of the eclipse used active configuration settings and it solved all the Indexer error. Thanks for the help guys.\n"} {"question": "I'm trying to make changes and compile open source 3d printers firmware in eclipse. Added all the project related to firmware but it showing symbol could not be resolved error. The cause of error is IDE cannot find the symbols. How can I solve this. It's compiling properly and also working on board.\n", "answer": "Found the solution in indexer of the eclipse used active configuration settings and it solved all the Indexer error. Thanks for the help guys.\n"} {"question": "How would I simplify all of this into one line?\n\n```\nREG &= ~BITA;\n REG &= ~BITB;\n REG &= ~BITC;\n REG &= ~BITD;\n REG &= ~BITE;\n```\n", "answer": "You can use|(bitwise or) operator.\n\n```\nREG &= ~(BITA | BITB | BITC | BITD | BITE);\n```\n"} {"question": "Because FILE struct is depended on implementation, is there any fail-proof way to resolve FILE \"object\" to the path of the file it was create with?\n", "answer": "It seems it is either hard due toFILEstructure being implementation dependent, or a sign of improperly designed code. As it stands now,stdlibdoes not provide any way of checking this exact thing. There are ways to check file handles, but those are system dependent and are not practical.\n"} {"question": "How does one definecopyanddeepcopymethods for a Python type defined in a C extension?\n\nLooking at thedocumentation, there doesn't appear to be atp_slot for these methods.\n", "answer": "There's no slot. You just define the same methods you'd define in Python, but in C. (Typically, that means implementing__reduce__and getting the default__reduce__-basedcopy.copyandcopy.deepcopybehavior, but you can also implement__copy__and__deepcopy__if you want.)\n"} {"question": "i'm having process id from Task manager, i need to get the process name (complete with extension) from it.\nis it possible?\ni checked other questions, they are mostly command based.\n", "answer": "Do you mean 'get the .exe filename by process ID' from C code?\n\nIf so, you may have interesting inOpenProcess()and followingGetModuleFileNameEx().\nDon't forget toCloseHandle()after you get the exe filename. :)\n"} {"question": "i'm having process id from Task manager, i need to get the process name (complete with extension) from it.\nis it possible?\ni checked other questions, they are mostly command based.\n", "answer": "Do you mean 'get the .exe filename by process ID' from C code?\n\nIf so, you may have interesting inOpenProcess()and followingGetModuleFileNameEx().\nDon't forget toCloseHandle()after you get the exe filename. :)\n"} {"question": "I used a C / C++ code from the Internet, but my IDE gives me the following error on macos:\n\n```\nUse of undeclared identifier cfmakeraw\n```\n\nI now face the question, whether cfmakeraw is available on Macos / Unix ?\n\nThank you 🙏\n", "answer": "On your Mac, fire up Terminal and runman cfmakeraw.\n\n```\nSYNOPSIS\n #include <termios.h>\n\n void\n cfmakeraw(struct termios *termios_p);\n```\n\nSo it is available, but you must include.\n"} {"question": "I am looking for a way to set a background image in gtk + 3 with c language , I already search and all the answer are for other languages or don't work anymore . Does anyone know a proper way to do it ?\n", "answer": "For all problem encounter with the style in gtk i realize that using css for gtk wase the best answer , here some link that can be good to know\n\nCss + Gtk Overview\n\nGtk + Css Properties\n"} {"question": "I used a C / C++ code from the Internet, but my IDE gives me the following error on macos:\n\n```\nUse of undeclared identifier cfmakeraw\n```\n\nI now face the question, whether cfmakeraw is available on Macos / Unix ?\n\nThank you 🙏\n", "answer": "On your Mac, fire up Terminal and runman cfmakeraw.\n\n```\nSYNOPSIS\n #include <termios.h>\n\n void\n cfmakeraw(struct termios *termios_p);\n```\n\nSo it is available, but you must include.\n"} {"question": "I am looking for a way to set a background image in gtk + 3 with c language , I already search and all the answer are for other languages or don't work anymore . Does anyone know a proper way to do it ?\n", "answer": "For all problem encounter with the style in gtk i realize that using css for gtk wase the best answer , here some link that can be good to know\n\nCss + Gtk Overview\n\nGtk + Css Properties\n"} {"question": "I wrote this code in Sublime:\n\n```\nint main (int argc, char **argv)\n{\n printf(\"Hello World\");\n return 0;\n}\n```\n\nSaved it atC:\\cygwin64\\home\\userashelloworld.c.\n\nTyped in this on Cygwin64 Terminal:$ gcc -o helloworld helloworld.c\n\nBut I'm not seeing any output.Please help.\n", "answer": "The windows executable can be obtained by:$ ./helloworld\n"} {"question": "I am trying to get the contents of my adc register for debugging but I don't know how to print it with gdb. If the address register offset is0x08would I usep/x *0x08? I am getting a result but it is 64 bits and I'm expecting 32. Thanks.\n", "answer": "Turns out I was trying to find the wrong address and using a confusing hex to binary converter. Thanks to @Eugene Sh. for helping.\n"} {"question": "I am trying to get the contents of my adc register for debugging but I don't know how to print it with gdb. If the address register offset is0x08would I usep/x *0x08? I am getting a result but it is 64 bits and I'm expecting 32. Thanks.\n", "answer": "Turns out I was trying to find the wrong address and using a confusing hex to binary converter. Thanks to @Eugene Sh. for helping.\n"} {"question": "I have the following code snippet for a PIC controller:\n\n```\nvoid __interrupt() ISR(void\n{\n // do some stuff\n}\n```\n\nwhen I use PC-Lint I always get the error message:\n\nError 10: Expecting identifier or other declarator\n\nWhat can I do to handle the interrupt in PC-Lint?\n", "answer": "You can define a dummy preprocessor macro by using the option-d__interrupt()=\n"} {"question": "I foundthis example; here the two threads threadDefault and threadCustomized are terminated by using pthread_exit followed by return. Why did the author write both instructions?\n", "answer": "Mohith Reddy's answer is correct but misses the point. Of course the return statement is never executed sincepthread_exitdoesn't return, but it's there to suppress warnings from the compiler in case it's not aware thatpthread_exitdoesn't return.\n"} {"question": "I'd like to know where the function__cpuid_countis on osx. I'm assuming that it's inlibcbut running:\n\n```\nnm -g /usr/lib/libc.dylib\n```\n\nor\n\n```\nnm -g /usr/lib/libSystem.B.dylib\n```\n\nDoes not list the function in the outputs. Is there a better way to locate where it is?\n", "answer": "You can't find a__cpuid_countfunction because there isn't one. It's defined as a macro that expands to inline assembly incpuid.h.\n"} {"question": "What is the difference between this:\n\n```\nint num = 5;\nint* num1 = #\nprintf(\"%p\", num1);\n```\n\nand this:\n\n```\nint num = 5;\nint* num1 = #\nprintf(\"%p\", &num1);\n```\n", "answer": "In the first case,printf(\"%p\", num1);, you're printing the value ofnum1, which is the address ofnum.\n\nIn the second case,printf(\"%p\", &num1);, you're printing the address ofnum1.\n"} {"question": "In C, a directory is created like this:\n\n```\nmkdir(\"hello\");\n```\n\nbut what if we don't know the name of this directory (or it's told by user)? How can we define it to a computer? (%s is not working)\n", "answer": "I would recommend you to usesnprintfso you can take any type of input.\n\n```\n#include \n\nint main() {\n char name[50];\n int i = 5;\n snprintf(name, 50, \"dir.%i\", 5);\n mkdir(name, 0700);\n}\n```\n"} {"question": "I know thatPythonis platform independent, but I don't understand how that works forCPython. If the interpreter and some of the modules are written inC, aren't those going to be platform dependent?\n", "answer": "C is platform independent in the sense that it can be compiled for any machine for which a compiler is made to target that machine. That's why the Python source code is platform independent, even if a Python binary can only work on one platform.\n"} {"question": "Why *pointer is an integer but not the string content \"Hello from pointer\" Thanks!\n\n```\nint main(void) {\n char *pointer;\n pointer = \"Hello from pointer\";\n\n printf(\"*pointer is %d\\n\", *pointer);\n printf(\"\\n\");\n}\n```\n\nthe output is *pointer is 72\n", "answer": "It's because the ASCII code for'H'(which is the first element of the array) is72. It is completely normal.\n\nHere is the ASCII Code table\n"} {"question": "```\n#define len(a) if (a == 8) 1 \\\n else if (a == 3) 0 \\\n else -1\n```\n\nthis code is just an example how do we use nested if else.\nI don't want to use ternary operator as in that case i can't use else if statement.\n", "answer": "Don't abuse the preprocessor. Use a real function:\n\n```\nconstexpr auto len(int const a) {\n if (a == 8) return 1;\n if (a == 3) return 0;\n return -1;\n}\n```\n"} {"question": "I had tried running a program which I solved in codeblocks and using math.h library in cs50 ide by Harvard University(which is Ubuntu based). Its giving me an error that library is not included. How to include to my cs50 ide..?\n", "answer": "Are you including it in the compiling?\n\nEasiest way to do it is to compile with: make filename\n\nIf that doesn't work check you are adding it correctly: #include\n"} {"question": "I am trying to write Python C extensions and I'm on a mac. I know how to install thePython.hheader file on Linux, but I don't know how to do it on a Mac. How can I install it?\n", "answer": "The Python header file is a framework on Mac. You have to include it like this:\n\n```\n#include \n```\n"} {"question": "Is there a function to stretch an image's points to coordinates on the screen based on it's four points?\n\nIf not, is there a way I could do that using math?\n", "answer": "I mean something like a generalized texture-mapped quad.\n\nSDL_RenderGeometry()/SDL_RenderGeometryRaw()were added inSDL 2.0.18.\n"} {"question": "can someone please convert this line:\n\nstrcpy_s(this->name, SIZE_NAME, d.getName());\n\nto a strcpy function instead of strcpy_s?\n\nthank you\n", "answer": "```\nstrcpy(this->name, d.getName());\n```\n\nThat was easy\n"} {"question": "I found this structure in the slides of my professor:\n\n```\nstruct point{\n int x;\n int y;\n} p;\n```\n\nWhat does p mean? So far I used only the classical struct like this:\n\n```\nstruct point{\n int x;\n int y;\n};\n```\n", "answer": "```\nstruct point{\n int x;\n int y;\n} p;\n```\n\ndefines a variablepof typestruct point\n\nit is same as\n\n```\nstruct point{\n int x;\n int y;\n};\nstruct point p;\n```\n"} {"question": "If I have the follow code \" *k != (Queue *)0 * \", there is a violation of the rule 11.9. But why ?\n\nQich can I rewrite thise code for make it compliant to MISRA 11.9?\n", "answer": "You have to use the Keyword \"NULL\" to make it compliant:\n\n```\n*k != NULL\n```\n"} {"question": "Can anyone explain the meaning of the code and give an example how to use it?\nI can understandfoo[100], but notbar.\n\n```\ntypedef struct{\n int a,b;\n} CELL, *PCELL;\n\nCELL foo[100];\nPCELL bar(int x, CELL y);\n```\n", "answer": "```\nPCELL bar(int x, CELL y);\n```\n\nis a function declaration. It means thatbarwill take in anintand aCELLas parameters, and it will return a pointer to aCELLas a return value. The actual body of the function will be defined later.\n"} {"question": "I'm writing a header file in C and needstdlib.hfor it to work. But, when I check if_STDLIB_His defined, the pre-processor says it's not, even if I include the file. I have tried it on multiple compilers, where it works on most but not ontdm-gcc. How can I fix this?\n", "answer": "Looking atstdlib.hsource code, it seems like the macro to look for in tdm-gcc might be_TR1_STDLIB_H.So you can try something like:\n\n```\n#if defined _STDLIB_H || defined _TR1_STDLIB_H\n```\n"} {"question": "I'm writing a header file in C and needstdlib.hfor it to work. But, when I check if_STDLIB_His defined, the pre-processor says it's not, even if I include the file. I have tried it on multiple compilers, where it works on most but not ontdm-gcc. How can I fix this?\n", "answer": "Looking atstdlib.hsource code, it seems like the macro to look for in tdm-gcc might be_TR1_STDLIB_H.So you can try something like:\n\n```\n#if defined _STDLIB_H || defined _TR1_STDLIB_H\n```\n"} {"question": "i know that -> is a pointer |= is OR.\nwhat is the logical meaning of such line?\n\nTIMER0->ROUTELOC0 |= TIMER_ROUTELOC0_CC0LOC_LOC15\n", "answer": "|= does not mean OR. | means OR.\n\n|= is similar to +=, that is\n\nA |= B is the equivalent of A = A | B\n\nSo to answer your question:\nIt looks likeTIMER0is a structure with a memberROUTELOC0. The above expression is setting theROUTELOC0as the result whenROUTELOC0is ORed withTIMER_ROUTELOC0_CC0LOC_LOC15\n"} {"question": "Question 3 onCareer Ridesuggests that*(x+i)is the same as&x[i]. Can someone please explain whether this is correct?\n", "answer": "That answer is incorrect. Given a pointer variablexand an integer variablei,*(x + i)is the same asx[i]andx + iis the same as&x[i]. It looks like they took half from each side of that for their answer, but they didn't provide any explanation, so we'll never know.\n"} {"question": "When I try to compile my code, I am getting a c statement with no effect warning:\n\nI am trying to use the bitwise operation to shift a value to the left. This is the code I am trying to do:\n\n```\n*bits << 5\n```\n\nbits is a unsigned pointer.\n", "answer": "You are calculating a value, but not assigning it to anything.\n\nYou probably want to do this instead:\n\n```\n*bits <<= 5;\n// or equivalent\n*bits = *bits << 5;\n```\n"} {"question": "Question 3 onCareer Ridesuggests that*(x+i)is the same as&x[i]. Can someone please explain whether this is correct?\n", "answer": "That answer is incorrect. Given a pointer variablexand an integer variablei,*(x + i)is the same asx[i]andx + iis the same as&x[i]. It looks like they took half from each side of that for their answer, but they didn't provide any explanation, so we'll never know.\n"} {"question": "When I try to compile my code, I am getting a c statement with no effect warning:\n\nI am trying to use the bitwise operation to shift a value to the left. This is the code I am trying to do:\n\n```\n*bits << 5\n```\n\nbits is a unsigned pointer.\n", "answer": "You are calculating a value, but not assigning it to anything.\n\nYou probably want to do this instead:\n\n```\n*bits <<= 5;\n// or equivalent\n*bits = *bits << 5;\n```\n"} {"question": "A void function does not return any value as output and can take input values. The function below seems a void function, but there is the operator *, why?\n\n```\nvoid *function(){\n printf(\"hello\")\n}\n```\n", "answer": "That is not avoidfunction. That is a function that returns avoid*(pointer). But it seems incomplete, because theprintf()has no semicolon;and the function does not actually return avoid*.\n"} {"question": "A void function does not return any value as output and can take input values. The function below seems a void function, but there is the operator *, why?\n\n```\nvoid *function(){\n printf(\"hello\")\n}\n```\n", "answer": "That is not avoidfunction. That is a function that returns avoid*(pointer). But it seems incomplete, because theprintf()has no semicolon;and the function does not actually return avoid*.\n"} {"question": "I am currently working on a simulation using OpenMP. Whenever I try to execute with --trace to get the trace of the execution I get the following error\n\n```\nsrc/trace_graphics.c:5:10: fatal error: fut.h: No such file or directory\n5 | #include \n```\n\nI redownloaded easypap but the file doesn't seem to come with it.\n", "answer": "I friend of mine found the solution so I'm posting it\n\n```\nsudo apt-get install libfxt-dev\n```\n\nThis will do the trick\n"} {"question": "what is the meaning of \"D type qualifier is meaningless on cast type at this line of code\"\n\n```\n(*((volatile RCC_t * const)0x400FE060)).USESYSDIV = 1;\n```\n\nand how to solve it?\n", "answer": "volatile RCC_t * constsays the pointer (not the thing it points to) isconst. But this is for avalue, which is just a result used in an expression. Qualifiers likeconstare properties ofobjectsin memory. So it serves no purpose in this cast.\n"} {"question": "I need to get the size of a C/C++ executable at runtime in code. Unfortunately I cannot use /proc/self/exe as it's restricted on the target system.\n", "answer": "Actually, it's a lot simpler than my attempt in the comments. The executable is simply:\n\n```\n(const char *)getauxval(AT_EXECFN)\n```\n\nThat said, you should always try to open/proc/self/exefirst since the executable may have been deleted/moved/replaced while running.\n"} {"question": "While readinguname.c(in order to recreate it) I found a variable calledHOST_OPERATING_SYSTEM(line 371). It's never mentioned in the same file (as Strg+f told me) and not in the dependencies ofuname.c, as far as I could see.\n\nWhere is the variable initialized and how to access it?\n", "answer": "HOST_OPERATING_SYSTEMis defined at build time using autoconf modules defined ingnulib.\n"} {"question": "How can I determine the maximum file path length allowed in the system my program is running on?\nIs it inlimits.h? because I didn't find it there.\n", "answer": "It should be NAME_MAX defined in\n\nhttps://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html\n"} {"question": "How can I determine the maximum file path length allowed in the system my program is running on?\nIs it inlimits.h? because I didn't find it there.\n", "answer": "It should be NAME_MAX defined in\n\nhttps://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html\n"} {"question": "I know for sure there is a command for CUP that prints out the produced parse tree.\nIs there a similar command for Bison?\n", "answer": "No, there isn't.\n\nIf you want an AST or parse tree, you are responsible for building it, and the AST node objects should be able to print themselves out, as it were.\n"} {"question": "I know for sure there is a command for CUP that prints out the produced parse tree.\nIs there a similar command for Bison?\n", "answer": "No, there isn't.\n\nIf you want an AST or parse tree, you are responsible for building it, and the AST node objects should be able to print themselves out, as it were.\n"} {"question": "I'm running Debian on an x86_64 Intel processor.\n\ngcc (Debian 8.3.0) compiles the following program\n\n```\n#include \n#include \n#include \n\nint main(){\n printf(\"%zd\\n\",alignof(max_align_t));\n}\n```\n\nand outputs\n\n```\n16\n```\n\nWhat datatype requires a 16 byte alignment?\n", "answer": "On x86_64,_Alignof(long double)==16.\n"} {"question": "I am getting core dump by this little programm.\n\n```\n#include \nint main(void) {\n\n printf(\"process n%s\",(long)getpid());\n exit(0);\n}\n```\n\ncan you explain me why?\n", "answer": "You need to know where your functions come from, what they're returning and how to print the return value.\n\n```\n#include \n#include \n\nint main(void) {\n printf(\"process n%ld\", (long)getpid());\n}\n```\n"} {"question": "I was wondering whether clang's new amazing custom size (things like 13-bit int, or 70-bit int, etc.) will get added to gcc.\n", "answer": "Well. C23 has finally implemented them as_BigInt\n"} {"question": "I was wondering whether clang's new amazing custom size (things like 13-bit int, or 70-bit int, etc.) will get added to gcc.\n", "answer": "Well. C23 has finally implemented them as_BigInt\n"} {"question": "Is there any difference between\n\n```\nconst int* ptr[5];\n```\n\nand\n\n```\nconst int (*ptr)[5];\n```\n\n?\n\nI am trying to point to a const 5*5 2D int array, but I am not sure of the best way to do it\n", "answer": "```\nconst int* ptr[5];\n```\n\nThis is an array of five elements, each element is a pointer toconst int.\n\n\n\n```\nconst int (*ptr)[5];\n```\n\nThis is a pointer to an array of five elements, each element is aconst int.\n"} {"question": "```\nstruct sigaction act;\nmemset(&act,0,sizeof act);\nsigaction(SIGALRM, &act, NULL);\nalarm(any_seconds);\n```\n\nMy alarm code in linux.\n\nI met \"Alarm clock\" message. But I don't want met this message.\n\nHow can I do? please help.\n", "answer": "You can catch the signal\n\n```\nstatic void alarmHandler(int signo)\n{\n (void)signo;\n printf(\"Another message\\n\"); // or skip this line\n}\n\n...\nalarm(any_seconds);\nsignal(SIGALRM, alarmHandler);\n```\n"} {"question": "I declare double variables t and tau, and assign them values 1 and 0.00001\nThis line of code produces 536870912 in the console. What can be the reason?\n\nprintf(\"%i\\n\",round(t/(tau*double(2))));\n\nBy the way, I write code in a C++ compiler, but practically it's C.\n", "answer": "roundreturns adouble. Printing it with%iis undefined behaviour.\n\nUse%ffor printingdouble:\n\n```\nprintf(\"%f\\n\",round(t/(tau*double(2))));\n```\n"} {"question": "About Leap Year algorithm,\n\n```\nif( (year%4==0 && year%100!=0) || (year%400==0))\n```\n\nWhy does it use \"or\" instead \"and\"year%400==0?\n", "answer": "Are you sure about knowing the meaning of what leap year is?\n\n\n"} {"question": "About Leap Year algorithm,\n\n```\nif( (year%4==0 && year%100!=0) || (year%400==0))\n```\n\nWhy does it use \"or\" instead \"and\"year%400==0?\n", "answer": "Are you sure about knowing the meaning of what leap year is?\n\n\n"} {"question": "In my c programming homework I am asked toinitialize an array using an initializer list delimited by braces.I've googled every thing and I can't find an example of an initializer list delimited by braces. By the way, the array I am initializing is 2-D so if you could format your answer so that it is representative of a 2-D array, that would be very helpful. Thanks\n", "answer": "Here's an example:\n\n```\nint a[ 2 ][ 3 ] = { { 5, 6, 7 }, { 10, 20, 30 } };\n```\n"} {"question": "In my c programming homework I am asked toinitialize an array using an initializer list delimited by braces.I've googled every thing and I can't find an example of an initializer list delimited by braces. By the way, the array I am initializing is 2-D so if you could format your answer so that it is representative of a 2-D array, that would be very helpful. Thanks\n", "answer": "Here's an example:\n\n```\nint a[ 2 ][ 3 ] = { { 5, 6, 7 }, { 10, 20, 30 } };\n```\n"} {"question": "I want to create a file on/dev/mmcblk0, if it doesn't exist already, and then write to it. My question is how to check if there is already such file on the sdcard and then access it, does it show up like/dev/mmcblk0/somefile?\n", "answer": "/dev/mmcblk0points to a drive, so you will need to mount the drive first before you can see what files are available on it or create new files.\n"} {"question": "If we have a 32bit pattern of 1111 1111 1000 0000 0000 0000 0000 0000, which is -2^23 in int, when we convert int to float will this be -INF?\n", "answer": "Conversions in C operate onvalues, and the value -2^23 is representable infloat, so the result of the conversion is the value -2^23.\n"} {"question": "I'm trying to use the raylib on Visual Studio 2019, I followedthis tutorialI can build without anywarning, but when I run my program a error windows saying that it can't find \"raylib.dll\" apear. What can I do to solve this ?\n", "answer": "I solve my issue by placing the raylib.dll that's inthis raylib distributionin the folder where my executable is build\n"} {"question": "I got an assignment in which I can use any method, as long as it is part of the ANSI - c standard. I want to usefreopen, except I don't know if its part of the standard. I have looked at \"The C programming language\" book's list of methods and it doesn't seem to be there, but it was in C89 so I doubt it isn't in ANSI.\n", "answer": "freopen()functionconforms to C89.\n\nAnd C89 isANSI C.\n"} {"question": "Hello I am a complete beginner in a university course for C programming. I am trying to compare 4 inputs for exact matches using strcmp. The code only take into account the first two though. Is it possible to compare two strcmp values to compare 4 inputs?\n", "answer": "You can concatenate the results via&&.\n\n```\nif (strcmp(str1, str2) == 0 && strcmp(str1, str3) == 0 && strcmp(str1, str4) == 0) {\n printf(\"They match!\")\n}\n```\n"} {"question": "I have currently an issue with debugging with visual studio code . I want to attach GDB to a C (.so) shared library module that is called via a main python program that interfaces with the C shared library with F2PY.\n\nHow do I procede to create a launch configuration in vscode for gdb to debug that C shared library?\n", "answer": "Cross-language debugging from Python to C is only available in Visual Studio, not in VS Code.\n"} {"question": "```\nfor (unsigned i = 0; i < 3; i++) {\n if (i == 2) i = -1;\n}\n```\n\nI can't understand why this loop is infinite. I get that it wraps around wheni = -1but UINT_MAX is greater than 3.\n", "answer": "If I rewrite your code, then might more clear to see why\n\n```\nunsigned i = 0;\nwhile (i < 3) {\n if (i == 2) i = -1;\n i++;\n}\n```\n\ni++happens at the end of the loop soibecame0again.\n"} {"question": "I want to search and replace a pointer\n\n```\nchar* test\n```\n\nhowever, when I type\n\n```\n:%s/char* test/something/g\n```\n\nI get\n\n```\nE486: Pattern not found: char* test\n```\n\nI assume this is due to vim trying to use regex in search.\n\nHow can i tackle this issue? Is it possible to replace such text?\n", "answer": "You need to escape star symbol. This should work:\n\n```\n:%s/char\\* test/something/g\n```\n"} {"question": "```\nfor (unsigned i = 0; i < 3; i++) {\n if (i == 2) i = -1;\n}\n```\n\nI can't understand why this loop is infinite. I get that it wraps around wheni = -1but UINT_MAX is greater than 3.\n", "answer": "If I rewrite your code, then might more clear to see why\n\n```\nunsigned i = 0;\nwhile (i < 3) {\n if (i == 2) i = -1;\n i++;\n}\n```\n\ni++happens at the end of the loop soibecame0again.\n"} {"question": "I want to search and replace a pointer\n\n```\nchar* test\n```\n\nhowever, when I type\n\n```\n:%s/char* test/something/g\n```\n\nI get\n\n```\nE486: Pattern not found: char* test\n```\n\nI assume this is due to vim trying to use regex in search.\n\nHow can i tackle this issue? Is it possible to replace such text?\n", "answer": "You need to escape star symbol. This should work:\n\n```\n:%s/char\\* test/something/g\n```\n"} {"question": "How can I write following C expression using left-shift bit-wise operator (<<) and plus sign (+)?\n\n```\ny = x * 6;\n```\n", "answer": "x << nmeans x * 2nby definiton (C18 §6.5.7/4). Knowing that x * 6 means x * 2 + x * 4, which is x * 21+ x * 22, we can rewritey = x * 6;asy = (x << 1) + (x << 2);.\n"} {"question": "I just wrote a basic c program to run but compiler prompts the error (see attached image). I have installed Dev-C++ before where I did C++ Programming. But when I wrote C code it prompts error I have deleted it & reinstalled the Dev-C++ again but couldn't run please help.\nIDE Version: 5.11\n", "answer": "You must choose the right Project configuration (C project):\n\n\n\nRemarque : you must have a project path without space. Exemple :C:\\Ali\\untiled\\untiled.c\n"} {"question": "I just wrote a basic c program to run but compiler prompts the error (see attached image). I have installed Dev-C++ before where I did C++ Programming. But when I wrote C code it prompts error I have deleted it & reinstalled the Dev-C++ again but couldn't run please help.\nIDE Version: 5.11\n", "answer": "You must choose the right Project configuration (C project):\n\n\n\nRemarque : you must have a project path without space. Exemple :C:\\Ali\\untiled\\untiled.c\n"} {"question": "There is no re-negotiation in TLS1.3, will SSL_write yield SSL_ERROR_WANT_READ? And will SSL_read yield SSL_ERROR_WANT_WRITE?\n\nHere are openssl docs in SSL_write and SSL_read\n", "answer": "I created an issue in github, and got the developer's answer.\n\nhttps://github.com/openssl/openssl/issues/11211#event-3094172350\n\nIn TLS1.3, SSL_write can yield SSL_ERROR_WANT_READ, and SSL_read also can yield SSL_ERROR_WANT_WRITE\n"} {"question": "What happens when you call read() (or recv()) on an open socket, and you specify a length that is more the number of bytes ready to be read in the buffer (TCP) or the length of the next datagram (UDP)?\n", "answer": "In both cases, if the size of the buffer is larger than the amount of available data, what data is available is read and the number of bytes actually read are returned from the function. That return value is what you should use when operating on the data.\n"} {"question": "how to explain this right\n\n```\nchar*(*a)(int, int);\n```\n\njust explain what does this declaration means. I'm not sure how to explain it right.\nThank you very much!\n", "answer": "ais a pointer to a function with two parameters of typeintthat returns achar*.\n\nThe ``Clockwise/Spiral Rule''\n\ncdecl: C gibberish ↔ English\n"} {"question": "This question already has answers here:How do I determine the size of my array in C?(25 answers)Closed3 years ago.\n\nFor example a code like:\n\n```\nint arr[5] = {1, 2, 3, 4, 5}\n```\n\nIs there anyway to get the 5 in arr[5]?\nI haven't learnt C++ before.\n", "answer": "You can get it by getting the array size and divide it by the size of a single element:\n\n```\nint arr[5] = {1, 2, 3, 4, 5};\nsize_t lengthOfArr = sizeof(arr)/sizeof(arr[0]) ;\n```\n"} {"question": "With C igraph we can create a graph from an adjacency list withigraph_adjlist.\nIt there a way to create a graph from an incidence list ?\n", "answer": "Unfortunately no such functionality is implemented. Feel free to open an issue athttps://github.org/igraph/igraphto suggest such a feature. Alternatively, if you want to discuss it, theigraphproject recently opened a new forum to facilitate discussions, seehttps://igraph.discourse.group.\n"} {"question": "With C igraph we can create a graph from an adjacency list withigraph_adjlist.\nIt there a way to create a graph from an incidence list ?\n", "answer": "Unfortunately no such functionality is implemented. Feel free to open an issue athttps://github.org/igraph/igraphto suggest such a feature. Alternatively, if you want to discuss it, theigraphproject recently opened a new forum to facilitate discussions, seehttps://igraph.discourse.group.\n"} {"question": "Is there any way to get freetype man pages?\n\nI can't find them and have to use the documentation on the web.\nThe problem is when I don't have internet access.\n", "answer": "Freetype doesn't provide man pages. Only html documentation.\n\nYou can download it fromhere(see the archives that have \"-doc\" in their name).\n"} {"question": "What is a difference between((int) a)and(int(a))?\n\nIs the second expression valid in pure \"С\" (not \"C\" under \"C++\")?\n", "answer": "There's no difference between them in C++. However, C supports only the first cast operation.\n\nSee this example fromtutorial:\n\n```\ndouble x = 10.3;\nint y;\ny = (int) x; // c-like cast notation \ny = int (x); // functional notation\n```\n"} {"question": "This question already has answers here:Using true and false in C(15 answers)Closed3 years ago.\n\nI thought that C interpretedtrueas1but now I'm having doubts.\n\nFull code (compiled with GCC 5.1):\n\n```\nif(true && true) // Error: 'true' undeclared (first use in this function)\n{\n}\n```\n\nWhy does this happen?\n", "answer": "trueis not a keyword in C like it is in C++.\n\nTo access it you'll have to#include .\n"} {"question": "```\nint ch;\n scanf(\"%c\", &ch); //Read a character (%c)\n printf(\"You entered char %c %d\\n\", ch, ch);\n return 0;\n```\n\nexpected output: You entered char A 65Actual output: You entered char A 32577\n", "answer": "chis of type int andscanf(\"%c\", &ch)copies abytein to address location pointed by&ch.MachineEndiannessdecides where thecharvalue from iostream stored. ifchon stack garbage values present in remaining bytes ofch\n"} {"question": "I'm trying to access the whole array from a struct in a function, to compare two elements for no duplication. However, I am receiving anexpected expression errorinqueue.id[].\n\n```\nint count = sizeof(queue.id[]) / sizeof(queue.id[0]);\n```\n", "answer": "```\nint count = sizeof(queue.id[]) / sizeof(queue.id[0]);\n```\n\nshould be\n\n```\nint count = sizeof(queue.id) / sizeof(queue.id[0]);\n```\n"} {"question": "I have twouint64variablesvar_1andvar_2and I want to set the bits ofvar_1according to the low-order6bits ofvar_2. How can I do this in C language?\n", "answer": "Like so:\n\n```\nuint64_t mask = 0x3F;\nvar_1 &= (~mask);\nvar_1 |= (var_2 & mask);\n```\n"} {"question": "FILE *fopen(const char *filename, const char *mode);\n\nI saw that some people only put the name of the file inside the \"filename\" part, some others put the entire path\n\nexample\n\nFILE *fopen(\"mytext.txt\", r);FILE *fopen(\"/myfolder/mytext.txt\", r);\n\nwhich is the correct one?\n", "answer": "If the file is in current directory when you run the program - no.\n\nIf it's not - yes, you will need to specify the path (absolute or relative to current directory)\n"} {"question": "I have twouint64variablesvar_1andvar_2and I want to set the bits ofvar_1according to the low-order6bits ofvar_2. How can I do this in C language?\n", "answer": "Like so:\n\n```\nuint64_t mask = 0x3F;\nvar_1 &= (~mask);\nvar_1 |= (var_2 & mask);\n```\n"} {"question": "Is there any other way of passing user's parameters into a program other than through\n\n./program argument1 argument2\n\nwhereargument1andargument2will be passed on tomain'sargv[]?\n", "answer": "Your application could read the values from the standard input, a configuation file or even environnent variables.\n"} {"question": "I'm using theVIPS libraryfor manipulating images and adding text to them. I want to know how to add spacing to characters in text?\n\nThe following image is an example of what I'm talking about.\n\n\n", "answer": "You can usepango markup. For example:\n\n```\nvips text x.png 'Hello!' --dpi 300\n```\n\nTo make:\n\n\n"} {"question": "Is there any other way of passing user's parameters into a program other than through\n\n./program argument1 argument2\n\nwhereargument1andargument2will be passed on tomain'sargv[]?\n", "answer": "Your application could read the values from the standard input, a configuation file or even environnent variables.\n"} {"question": "I'm currently developing a piece of software on a Raspberry Pi. Because I have to control motors very precisely i developed a C script, that does that for me. My current problem is, that I didn't found any solid method to transfer a list of signed floats from a Python3 Script to a C script. It is really important, that the method is fast.\n", "answer": "You could use a socket to send data from one script to the another.\n"} {"question": "I'm currently developing a piece of software on a Raspberry Pi. Because I have to control motors very precisely i developed a C script, that does that for me. My current problem is, that I didn't found any solid method to transfer a list of signed floats from a Python3 Script to a C script. It is really important, that the method is fast.\n", "answer": "You could use a socket to send data from one script to the another.\n"} {"question": "I would like to do something like setting a macro name that activates portions of my code....\n\ng++ -DVERBOSE=1 main.cc\n\nduring the Bazel build command:\n\nbazel build //myproj:main\n\nIs it possible?\n", "answer": "bazel build //myproj:main --cxxopt=-DVERBOSE=1\n\nOr, use thecoptsattribute incc_*targets.\n\nhttps://docs.bazel.build/versions/master/user-manual.html#flag--cxxopt\n"} {"question": "Is the codeint const*const pointer1=&constantVariable;legal?\n\nIf it isn't, what is the correct way of specifying it?\n", "answer": "It's OK!\nInint const*const pointer1=&constantVariable, the firstconstindicates that you couldn't change the value by *pointer1; the secondconstindicates the value of pointer itself(an address) couldn't be changed too. Actually pointer1 can point to a constant integer, even a normal variable.But it can't be set twice.\n"} {"question": "Self explanatory question. Can we get multiple UDP packets in one socket recv call when using Multicast?\n", "answer": "When usingrecvfromorrecvon a UDP socket, you will only ever receive one complete packet at a time.\n\nThis applies to both unicast and multicast packets.\n"} {"question": "I triedlocate kmalloc_sizes.hbut didn't find the file. And I usedapt-fileto search but couldn't find the package. How can I get this header file?\n", "answer": "The file you're looking for is actually calledkmalloc_sizes.h.\n\nYou can get it by installing the Linux kernel headers:\n\n```\nsudo apt-get install linux-headers-$(uname -r)\n```\n\nRef:https://askubuntu.com/questions/75709/how-do-i-install-kernel-header-files\n"} {"question": "Is there any piece of code I can write or any other way to check which version of the C language my compiler is compiling?\n\nI was wondering if there was a way for me to see if the compiler in question is C89, C99, C11, C18 etc. Perhaps utilizing__STDC_VERSION__.\n", "answer": "You can look at the__STDC_VERSION__macro, which hast the format YYYYMM and from that deduce whether you run C89, C99, C11 or C18.\n\nSee alsoWhat is the __STDC_VERSION__ value for C11?\n"} {"question": "I want to code a matrix calculator, and for that I need to ask the user for it's size,but when I'm declaring a 2d array it won't let me put a variable as a size, so what can I do?\n\n```\nint main()\n{\n int n;\n print_enter_matrix_size();\n scanf(\"%d\", &n);\n int matrix[n][n];\n return 0;\n}\n```\n", "answer": "You can use dynamics arrays. For that you can use malloc to declare the size you want, Try this:allocate matrix in C\n"} {"question": "I have a really simple question:\n\n```\nconst char *y = \"string_test\";\nx = &y;\n```\n\nWhat type is x ?\n\nThanks in advance for your answers !\n", "answer": "Assuming you had a typo in your question, and the code is:\n\n```\nconst char *y = \"string_test\";\nx = &y;\n```\n\nx shall be defined as:\n\n```\nconst char** x; // x is a pointer(Address of) a pointer to a constant char/string\n```\n"} {"question": "I have a really simple question:\n\n```\nconst char *y = \"string_test\";\nx = &y;\n```\n\nWhat type is x ?\n\nThanks in advance for your answers !\n", "answer": "Assuming you had a typo in your question, and the code is:\n\n```\nconst char *y = \"string_test\";\nx = &y;\n```\n\nx shall be defined as:\n\n```\nconst char** x; // x is a pointer(Address of) a pointer to a constant char/string\n```\n"} {"question": "I am new to C.\nI just want to know why initializing the array of int with int is working and why initializing an array of char with char is not working. Oram I wrong thinking that \"1\" is a char?\n\n```\n#include \n\nint main()\n{\n int incoming_message_test[2] = {1, 2}; // why does this work?\n char incoming_message[2] = {\"1\", \"2\"}; // why does this not work?\n \n return 0;\n}\n```\n", "answer": "You must change\"1\", \"2\"with'1', '2'\n"} {"question": "I don't seem to understand what's happening here\n\n```\n#include \n\nint var = 5;\n\nint main(){\n int var = var;\n printf(\"%d\",var);\n return 0;\n}\n```\n\nWhy does this program print a garbage value when the value of var is assigned to be 5?\n", "answer": "the local var has priority on the global var.\nSo the compiler translate it as (local) var = (local) var\n"} {"question": "I don't seem to understand what's happening here\n\n```\n#include \n\nint var = 5;\n\nint main(){\n int var = var;\n printf(\"%d\",var);\n return 0;\n}\n```\n\nWhy does this program print a garbage value when the value of var is assigned to be 5?\n", "answer": "the local var has priority on the global var.\nSo the compiler translate it as (local) var = (local) var\n"} {"question": "I am trying to find \"python.exe\" in szExeFile after aProcess32NextWcall.\n\nI tried doing a\n\n```\nif(strcmp(lppe->szExeFile,\"python.exe\") == 0){\n //do stuff\n}\n```\n\nbut the check always fails despite the process running. \nI have also tried using strncmp but it does not change anything.\n\nWhat am I doing wrong?\n", "answer": "Process32NextW()seems to usePROCESSENTRY32Wstruct with wide character strings. Trywcscmp()instead ofstrcmp().\n"} {"question": "I am trying to find \"python.exe\" in szExeFile after aProcess32NextWcall.\n\nI tried doing a\n\n```\nif(strcmp(lppe->szExeFile,\"python.exe\") == 0){\n //do stuff\n}\n```\n\nbut the check always fails despite the process running. \nI have also tried using strncmp but it does not change anything.\n\nWhat am I doing wrong?\n", "answer": "Process32NextW()seems to usePROCESSENTRY32Wstruct with wide character strings. Trywcscmp()instead ofstrcmp().\n"} {"question": "I'm trying tocompare a llvm Type and a Type*. I'm using the LLVM C APIs. Is there any possible method to do this?\n\nI haveType*because I did LLVMTypeOf api to get the type from an LLVM Value. So if I can get theType from a Value, it would also fix the issue.\n", "answer": "Types are unique in LLVM world, so you could compare their addresses.\n"} {"question": "I'm trying tocompare a llvm Type and a Type*. I'm using the LLVM C APIs. Is there any possible method to do this?\n\nI haveType*because I did LLVMTypeOf api to get the type from an LLVM Value. So if I can get theType from a Value, it would also fix the issue.\n", "answer": "Types are unique in LLVM world, so you could compare their addresses.\n"} {"question": "Is there a way to calculate the maximum value representable byunsigned intwithout usinglimits.h(so noUINT_MAX) or without using\n\n```\nunsigned int z = 0;\nz = z - 1;\n```\n", "answer": "The simplest way to do this is to simply assign -1 to anunsigned int. You could also assign~0uto it.\n\nIf that's not acceptable, while inefficient, you could do something like this:\n\n```\nunsigned int i = 0;\nwhile (i+1 > 0) \n i++;\nprintf(\"i=%u\\n\", i);\n```\n"} {"question": "I have a file where I have saved C float arrays as binary data.\nIs it possible to load this binary data into a Python list now?\n", "answer": "It's possible to do that using Numpy.memmap. Something like this:\n\n```\nimport numpy as np\narr = np.memmap(\"filename\", dtype=\"int32\", mode=\"r\")\n```\n\nReplace \"filename\" with the path to your array file and \"int32\" with the type you used in your C array.\n"} {"question": "I have a file where I have saved C float arrays as binary data.\nIs it possible to load this binary data into a Python list now?\n", "answer": "It's possible to do that using Numpy.memmap. Something like this:\n\n```\nimport numpy as np\narr = np.memmap(\"filename\", dtype=\"int32\", mode=\"r\")\n```\n\nReplace \"filename\" with the path to your array file and \"int32\" with the type you used in your C array.\n"} {"question": "```\nint x = 0x76543210;\nchar *c = (char*) &x;\n\nBig endian format:\n------------------\nByte address | 0x01 | 0x02 | 0x03 | 0x04 | \n +++++++++++++++++++++++++++++\nByte content | 0x76 | 0x54 | 0x32 | 0x10 |\n```\n\nwhy does the byte address ox01 stores only 0x76 not 0x765?\n", "answer": "A byte is 8 bits, and in hex that goes from 0x00 --> 0xFF (0 -> 255).\n\n0x765 - which is hex - cannot possibly fit in 8 bits.\n"} {"question": "Let's say x=29 and y=13. What does this line of code actually do:\n\n```\nx%=y-3;\n```\n\nI just don't really know what does this mean?\n", "answer": "Modulo operator gives you remainder from division.\n\na % bis the remainder of division a by b\n\nx %= y - 3is equal tox = x % (y - 3)and gives you remainder from division x by (y - 3) expression.\n"} {"question": "I saw this code:\n\n```\nchar *str;\n// Some code\nif (! str || ! *str)\n return str;\n```\n\nWhy need to check! *str? Isn'tif (! str)enough?\n", "answer": "It depend on what you want to check:\n\nThe!strcheck is str is NULL.The!*strchecks that the first char instris NUL byte ('\\0')\n\nCombined, they will return 's' if s is NULL, or s point to a NUL char\n"} {"question": "I saw this code:\n\n```\nchar *str;\n// Some code\nif (! str || ! *str)\n return str;\n```\n\nWhy need to check! *str? Isn'tif (! str)enough?\n", "answer": "It depend on what you want to check:\n\nThe!strcheck is str is NULL.The!*strchecks that the first char instris NUL byte ('\\0')\n\nCombined, they will return 's' if s is NULL, or s point to a NUL char\n"} {"question": "I have 2 files:stack.handstack.c. Both of them have a undefined typeelem_type.\n\nSo my question is:Can I leave them undefined until I include the stack.h and then give it a definition depended on the need of the calling file ?\n", "answer": "You cannot leave undefined type in stack.c in C because when a compiler tries to compile stack.c it won't be able to determine the type.\n\nIn C++ this is feasible via template.\n"} {"question": "How do we add new line to output buffer using printf in C?\n\nLike in c++ we use endl, what do we use in C?\n\n```\ncout<\n\nint main(){\n int a[1] = {1};\n int b = 6;\n printf(\"%d\\n\", a[-1]);\n printf(\"%d\\n\", b);\n //printf(\"%d\\n\", (a-1 == &b));\n return 0;\n}\n```\n\nI wrote the above code and found out it didn't work properly when using gcc or mingw to compile it, but when I uncommented 8th line, everything is just fine. Could anyone explain the code for me?\n", "answer": "Thea[-1]is undefined memory space.\n"} {"question": "This question already has answers here:Multiplication and division: weird output in c(3 answers)Closed4 years ago.\n\nI am using c preprocessor directive. I want to know how does this program work?\n\n```\n#define PRODUCT(x) (x*x)\n main()\n {\n int i=3,j;\n j=PRODUCT(i+1);\n printf(\"\\n%d\",j);\n }\n```\n\nThe output is\n\n```\n7\n```\n", "answer": "Why do I get 7 withPRODUCT(i+1)?\n\nbecause3+1*3+1==3+3+1\n\n\n\nTry#define PRODUCT(x) ((x) * (x))\n"} {"question": "I'm looking for an example of eBPF to write a seccomp filter, but I can't find none. Could someone tell me if is possible to use eBPF to write seccomp filter?\n", "answer": "Seccomp does not work with eBPF at the moment (only cBPF).\n\nThere wasa discussionnot long ago on that topic on the Linux networking mailing list. The eBPF maintainer is against adding eBPF support to seccomp.\n"} {"question": "I'm looking to break up binary into blocks or 8 digits. Is there a way to do the following in C without doing a second print line?\n\n```\nprintf(\"%d%c\", number>>(i-1) & 1, (i%8==0) ? ' ' : '');\n```\n\nOr is it not possible to do the \"empty char\" and I should add a second line to check for that?\n", "answer": "There's no such thing as an empty char. You can use%swith strings.\n\n```\nprintf(\"%d%s\", number>>(i-1) & 1, (i%8==0) ? \" \" : \"\");\n```\n"} {"question": "Is it possible to execute C code in a C program? For instance when reading input from the user.\n", "answer": "There's nothing built in to do this.\n\nThis simplest thing to do is save the given code to a separate file, invoke GCC as a separate process to compile the code, then run the compiled code in a new process.\n"} {"question": "```\n#include \n\nint main()\n{\n int p=10,q=20,r;\n if(r = p = 5 || q > 20)\n printf(\"%d\",r);\n else\n printf(\"No output\");\n\n return 0;\n}\n```\n\nThe output is 1 but how?\nPlease explain\n", "answer": "Precedence. To be more clear:\n\n```\nif(r = p = 5 || q > 20)\n```\n\nis the same as\n\n```\nif(r = p = (5 || q > 20))\n```\n\n5 is truthy, so the boolean expression evaluates to 1, which is then assigned tor\n"} {"question": "I get 'Permission denied' whenever I try to compile and run a program in Visual Studio code, in my Mac. How do I solve this?\n\nNote the 'permission denied' in this picture\n", "answer": "You need to say something like\n\n```\ngcc -o film film.c\n```\n\nand then\n\n```\n./film\n```\n\nfilm.cis your source file. In the example I've shown, the-oflag asksgccto put its output -- the compiled program -- in filefilm(with no conventional suffix).That'sthe file you want to run.\n"} {"question": "Does using fopen(fileName, \"w\") overwrite the blocks being used by a file, or does it set the blocks that were once being used as free and then start writing to new blocks?\n", "answer": "The C standard doesn’t specify how it’s implemented. So, itmightoverwrite the blocks, but there’s no guarantee. On a Unix/Unix-like environment, for example, it’s most likely a wrapper aroundopen()with some internalFILE *manipulation that we need not worry about.\n"} {"question": "This question already has answers here:What is special about numbers starting with zero?(4 answers)Closed4 years ago.\n\nI was trying the following code\n\n```\nprintf(\"%d\", 010 % 10);\n```\n\nI was expecting it output be 0, but it is 8.\n\nWhy? Is there any way to get the last digit of an integer which is taken as input.\n", "answer": "Any numeric literal in c or c++ starting with a zero will be interpreted asoctal\n\nSo your calculation is 8 modulo 10, which is 8\n"} {"question": "In GTK3, how do I get a DrawingArea to respond keyboard events?\nShould I connect the DrawingArea with a signal or is it more compicated?\nI'm using GTK3 with the C language.\n", "answer": "I fianlly found the solutionhere. I only connected the signal, but the GTK_CAN_FOCUS also need to be set for the drawingrea.\n"} {"question": "Whenever I try to compile c/cpp files it gives this error:\n\n```\ngcc: fatal error: cannot execute ‘as’: execvp: No such file or directory\ncompilation terminated.\n```\n\nI have also tried to include full path of file while compiling but same error occured.\nJust to be sure of version mismatch I looked for both gcc and g++ version but both are same,\ngcc/g++ version: 9.1.0.\n\nHow can I fix this?\n", "answer": "ascommand is frombinutils. Have you installed this package?\n"} {"question": "I want a C macro that will expand into a function with an extra parameter based on a condition.\n\nSomething like this:\n\n```\n#define EXTRA 7\n#ifdef ADD_ONE_MORE_ARG\n#define dothis(...) dothat(EXTRA,...)\n#endif\n```\n\nSuch thatdothis(5);is expanded intodothat(EXTRA, 5);but I can't remember the syntax. TheanswerI found here didn't help. Thanks.\n", "answer": "```\n#define callx(...) call(EXTRA, __VA_ARGS__)\n```\n"} {"question": "Can someone explain me please what is RTL in the context of driver development for Windows ?\n\nDevelopment Tool : Visual studio 2019\nDriver Type: Kernel Mode (kmdf).\nProgramming Language : C.\n", "answer": "Many kernel API functions start with theRtlprefix - that's an abbreviation of Run Time Library.\n"} {"question": "For example we have a server-client application. If the server write a message on the socket and then close it before the client's read. Will the client be able to read the message?\n", "answer": "\"If the server write a message on the socket and then close it before the client's read. Will the client be able to read the message?\"\n\nYes. The client will get the data that was sent before the FIN packet that closes the socket.\n"} {"question": "Can someone explain me please what is RTL in the context of driver development for Windows ?\n\nDevelopment Tool : Visual studio 2019\nDriver Type: Kernel Mode (kmdf).\nProgramming Language : C.\n", "answer": "Many kernel API functions start with theRtlprefix - that's an abbreviation of Run Time Library.\n"} {"question": "For example we have a server-client application. If the server write a message on the socket and then close it before the client's read. Will the client be able to read the message?\n", "answer": "\"If the server write a message on the socket and then close it before the client's read. Will the client be able to read the message?\"\n\nYes. The client will get the data that was sent before the FIN packet that closes the socket.\n"} {"question": "What does this statement mean in C language (assuming s1 and s2 are character arrays)?\n\n```\n(s1[i] = s2[i]) != '\\0'\n```\n", "answer": "Consideringstrings are\\0terminated by the standard.\n\n```\n(s1[i] = s2[i]) != '\\0'\n```\n\nit will assigns2[i]tos1[i]then it will compare whether assigned value is\\0or not.\n\nIt is usually used to break the loop while copying contents from one string to another.\n"} {"question": "I'm trying to implement ElGamal cryptosystem and I decided to use OpenSSL to generate big primes. I've seen several functions that generate big random numbers but I haven't found a function to generate prime numbers. What function should I use?\n", "answer": "That's a function of the underlying Big Number (BN) implementation rather than a specific high level crypto function, so I guess you'd useBN_generate_prime_ex.\n"} {"question": "I have a binary mask which at some point I'm updating. It's ok for 1s in my old mask to become 0s but the other way around is not allowed. How can I assert using some binary operations that none of the 0s in the mask have turned into 1s?\n", "answer": "```\nif (~old & new)\n```\n\nIf you also want to know which bits changed from 0 to 1, just read each bit inbits = ~old & new;. If you just want to know if any 0s became 1s, that first line of code will do.\n"} {"question": "I have a binary mask which at some point I'm updating. It's ok for 1s in my old mask to become 0s but the other way around is not allowed. How can I assert using some binary operations that none of the 0s in the mask have turned into 1s?\n", "answer": "```\nif (~old & new)\n```\n\nIf you also want to know which bits changed from 0 to 1, just read each bit inbits = ~old & new;. If you just want to know if any 0s became 1s, that first line of code will do.\n"} {"question": "I'm running this code and getting some garbage value while printing *ptr. What could be the possible reason and how can I avoid getting that?\n\n```\n# include \nint main()\n{\n int test = 1; \n int *ptr = &test;\n *ptr++ = 10; \n test++; \n printf(\"\\nThe value is %d\", *ptr);\n}\n```\n", "answer": "You movedptrwithptr++. Why?\n\nDon't do that.\n"} {"question": "I know the C11 standard definesrsize_tassize_tin the optional Annex K, but in what header file(s)? Where does the C standard say this type should be defined?\n", "answer": "K.3.3 Common definitions\n\nThe headerdefines a type.The type isrsize_twhich is\n the typesize_t.\n\nQuoting thedraft.\n\nReading further, this is also defined in,,,and. There may be others.\n"} {"question": "I know the C11 standard definesrsize_tassize_tin the optional Annex K, but in what header file(s)? Where does the C standard say this type should be defined?\n", "answer": "K.3.3 Common definitions\n\nThe headerdefines a type.The type isrsize_twhich is\n the typesize_t.\n\nQuoting thedraft.\n\nReading further, this is also defined in,,,and. There may be others.\n"} {"question": "I'm looking atunsigned char(byte) arrays ingdb, i.e.\n\n```\n(gdb) p/x buf@4\n$76 = {0xac, 0xa, 0xb0, 0xa}\n```\n\nIs there a way of forcing the preceding 0s? i.e output like:\n\n```\n$76 = {0xac, 0x0a, 0xb0, 0x0a}\n```\n", "answer": "From the gdbdocumentation:\n\n'z'Like 'x' formatting, the value is treated as an integer and printed as hexadecimal, but leading zeros are printed to pad the value to the size of the integer type.\n\nSo...\n\n```\n(gdb) p/z buf@4\n```\n"} {"question": "I'm wondering if the fopen command is smart enough to stop reading a file if it's to large and then wait for some proceeding read command to continue reading.\n\nFor that matter, how large is _iobuf?\n", "answer": "fopen(...)doesn't do any size checks; it just returns a file pointer. Are you thinking offread(...), by any chance?\n\nYou can always find the size of the file that you are going to read by usingstat(...)system call.\n"} {"question": "I'm trying to get the most significant bit of an unsigned 8-bit type in C.\n\nThis is what I'm trying to do right now:\n\n```\nuint8_t *var = ...;\n...\n(*var >> 6) & 1\n```\n\nIs this right? If it's not, what would be?\n", "answer": "To get the most significant bit from a memory pointed to byuint8_tpointer, you need to shift by 7 bits.\n\n```\n(*var >> 7) & 1\n```\n"} {"question": "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.\n", "answer": "Well, \nIn C, the size ofcharit's 1.\nI think we can't know if it's 1 octet or more (or less).\n\nSo,\n\n```\nchar tab[3] = {'a','b','c'};\n```\n\ndoesn't work ?\n"} {"question": "When I build a simple console app with clang, it works fine:\n\nvoid main() { puts(\"HELLO\"); }\n\nBut when I create a Windows app withWinMain, I can't see stdout.\n\nThere must be a flag that fixes it, like MinGW's-mconsole\n", "answer": "A quick stdout-enabler for otherwise GUI apps:\n\n```\nif (AllocConsole())\n{\n FILE* fi = 0;\n freopen_s(&fi, \"CONOUT$\", \"w\", stdout);\n}\n```\n\nand thenstd::coutandprintfwork.\n"} {"question": "always the first line of my file is empty\n\nwhst can i do ?\n\n```\nprintf(\"donner n\");\nscanf(\"%d\",&n);\n\n for(int i=0;i\ndouble atof(const char *string);\n```\n\nThis linkexplains about that.\n"} {"question": "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?\n\n```\nif ( !conn ) {\n rc == LDAP_SUCCESS;\n goto done;\n}\n```\n", "answer": "That statement does nothing. It's a bug.\n\nNow, 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).\n"} {"question": "\n\n\n\n\n\nI use Windows Subsystems for Linux(WSL), Ubuntu. I try compile simple code.\n\nI get errors in WSL.\n\nBut, it works well in Visual Studio.\n", "answer": "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.\n\nFor portability usefgets()on thestdininput stream instead.\n"} {"question": "\n\n\n\n\n\nI use Windows Subsystems for Linux(WSL), Ubuntu. I try compile simple code.\n\nI get errors in WSL.\n\nBut, it works well in Visual Studio.\n", "answer": "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.\n\nFor portability usefgets()on thestdininput stream instead.\n"} {"question": "This question already has answers here:How are floating point numbers stored in memory?(7 answers)Closed4 years ago.\n\nIf we create one variable of data type float and assign any value to it then how this is stored in memory?\n\nfloat var = 13.34;\n", "answer": "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.\n"} {"question": "This question already has answers here:How are floating point numbers stored in memory?(7 answers)Closed4 years ago.\n\nIf we create one variable of data type float and assign any value to it then how this is stored in memory?\n\nfloat var = 13.34;\n", "answer": "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.\n"} {"question": "So I havechar **sentencewithsentence[0] = string0, sentence[1] = string1, etc. Is there a way I can print the entire array in lldb? So that it shows up as{string0, string1, ...}\n", "answer": "This is answered in:\n\nView array in LLDB: equivalent of GDB's '@' operator in Xcode 4.1\n\nparticularly, you can use theparraycommand in any recent lldb.\n\nThere isn't a way to do this in the Xcode Locals view, but you can do this in the Xcode Debugger Console.\n"} {"question": "So I havechar **sentencewithsentence[0] = string0, sentence[1] = string1, etc. Is there a way I can print the entire array in lldb? So that it shows up as{string0, string1, ...}\n", "answer": "This is answered in:\n\nView array in LLDB: equivalent of GDB's '@' operator in Xcode 4.1\n\nparticularly, you can use theparraycommand in any recent lldb.\n\nThere isn't a way to do this in the Xcode Locals view, but you can do this in the Xcode Debugger Console.\n"} {"question": "```\n(gdb) set disassemble intel\nAmbiguous set command \"disassemble intel\": disassemble-next-line, disassembler-options.\n```\n\nWhen i set the disassembly syntax to intel, it show this error.\n", "answer": "Please use:\n\n```\nset disassembly-flavor intel\n```\n\nseeGDB Manualfor more details\n"} {"question": "I have existing C program which i want to call from tibco bw6. Is there any direct approach, like bw allow to invoke java code.\n\nOne possible solution is to use java invoke and jni. Direct call will be more preferable if possible\n", "answer": "if you have the .exe file you can use External Command activity otherwise I do not see any other simple solutions than to use swig with jni.\n\nRegards\n"} {"question": "I was wondering if there is a way to run a random statement in C that I created, such as a function. I know how to run a random integer but not how to randomly pick from a list of statements that I created.\n", "answer": "you can do like this with yourrandomValuethat you got fromrand()function:\n\n```\nint statement = randomValue % nState;\n```\n\nin above code, I assume that your program havenSatestates and you can use this variable in yourswitch.\n"} {"question": "In system programming class, we are told that all system calls are made in c. For example opening a file for reading/writing. Does java run c codes behind?\n", "answer": "Yes java runs C Code behind the scene. Using the native keyword.\n\nFor Instance: System.currentTimeMillis() is a Native Method\n\nHere is a good explaination how to use Native code:https://www.baeldung.com/java-native\n"} {"question": "In system programming class, we are told that all system calls are made in c. For example opening a file for reading/writing. Does java run c codes behind?\n", "answer": "Yes java runs C Code behind the scene. Using the native keyword.\n\nFor Instance: System.currentTimeMillis() is a Native Method\n\nHere is a good explaination how to use Native code:https://www.baeldung.com/java-native\n"} {"question": "My code uses ZLIB, and it seems that there are problems in usingfmemopen()and ZLIB functions afterwards...\n\nIs there an equivalent offmemopen()in ZLIB? Or how can I create it if no equivalent exists?\n", "answer": "No there is not. Furthermore, there is no need for such a thing, since zlib provides in-memory functions for compression and decompression.\n"} {"question": "I'm reading the C Programming Language (chapter 5), and I'm confused by this example:\n\n```\nint n, array[SIZE], getint(int *);\n```\n\nWhy is this function call in here like that? Is this just some tricky example and invalid code?\n", "answer": "It's not calling the function; it's declaring its prototype.\nIt's equivalent to:\n\n```\nint n;\nint array[SIZE];\nint getint(int*);\n```\n"} {"question": "```\na[b]\n```\n\nIs equivalent to*(a + b), so...\n\n```\na[b & c]\n```\n\nWhere&has a lower operator precedence than+, would this result in*(a + b & c)or*(a + (b & c))?\n", "answer": "TheC Standard, § 6.5.2.1,Array Subscriptingsays:\n\nThe definition of the subscript operator[]is thatE1[E2]is identical to(*((E1)+(E2)))\n\nNote the brackets surroundingE2. The latter expression (*(a + (b & c))) is the correct outcome.\n"} {"question": "I'm currently creating a little game, and I need to create a condition.\n\nIn pseudo-code, it would look like something like this :\n\n```\nif (a < x with x included in [b -10; b +10]) \n{\n then c = 2\n}\n```\n\nIs there an easy way to do this ?\n\nI know it may not be really clear, so ask me further details if you didn't understand.\n", "answer": "```\nif(a < x && x >= b-10 && x <= b + 10){\n\n}\n```\n"} {"question": "I'm currently creating a little game, and I need to create a condition.\n\nIn pseudo-code, it would look like something like this :\n\n```\nif (a < x with x included in [b -10; b +10]) \n{\n then c = 2\n}\n```\n\nIs there an easy way to do this ?\n\nI know it may not be really clear, so ask me further details if you didn't understand.\n", "answer": "```\nif(a < x && x >= b-10 && x <= b + 10){\n\n}\n```\n"} {"question": "Is it bad practice when I assign new pointer to pointer without free?\n\n```\nchar **arr = malloc(sizeof(*arr)*9);\n\n...\n...\n\narr[5] = strdup(\"sys\");\narr[6] = strdup(\"var\");\narr[7] = strdup(\"home\");\narr[8] = NULL;\n\narr[5] = arr[6];\narr[6] = arr[7];\narr[7] = NULL;\n```\n", "answer": "Yes. Since that pointer you reassigned (e.g. arr[5]) is no longer accessible it's memory can't be free'd and it is a memory leak.\n"} {"question": "I just did this\n\n```\nprintf( (n==0) ? \" %d\" : \" %3d\", n );\n```\n\nbut is there a conditional format descriptor?\n\nSo, it would mean something like\"if this is very short use such and such padding, but, if this is longer use such and such padding.\"\n\nCan do?\n", "answer": "There's no conditional, but you can use * to specify the width in the arguments. e.g.:\n\n```\nprintf(\" %*d\", (n==0)?1:3, n);\n```\n"} {"question": "In a Windows application, I have aGetFirmwareEnvironmentVariableAfunction to read a firmware environment variable. Is there any way to write something in this variable in uefi driver and read from it later in Windows?\n", "answer": "The function to set an NVRAM variable is called SetVariable() and is available to UEFI drivers via EFI_RUNTIME_SERVICES table.\n\nTo know more about it's interface and usage, read chapter 7.2 Variable Services of theUEFI 2.6 specification.\n"} {"question": "Are there any different between those both (ptrfun1andptrfun2)?\n\n```\nint fun(int num){\n num *= num;\n return num;\n}\n\nint main(){\n int (*ptrfun1)(int num) = fun;\n int (*ptrfun2)(int num) = &fun;\n```\n\nDoes both point to the functionfun?\n", "answer": "There is no difference at all.\n\nA functiondecaysto a function pointer.\n"} {"question": "Are there any different between those both (ptrfun1andptrfun2)?\n\n```\nint fun(int num){\n num *= num;\n return num;\n}\n\nint main(){\n int (*ptrfun1)(int num) = fun;\n int (*ptrfun2)(int num) = &fun;\n```\n\nDoes both point to the functionfun?\n", "answer": "There is no difference at all.\n\nA functiondecaysto a function pointer.\n"} {"question": "What is the specifier%[^s]used for?\n\nsis a variable.\n\nIn which cases can I use this specifier?\n", "answer": "The%[format specifier toscanfwill match a sequence of characters matching those that are listed between[and]. If the first character is^, then it matches charactersexcludingthose characters.\n\nIn your case%[^s]means \"match any character besides the characters's'.sisnota variable in this case.\n"} {"question": "I don't fully understand how the \"-\" operator affects the following code:\n\n```\n#define COMP(x) ((x) & -(x))\n\nunsigned short a = 0xA55A;\nunsigned short b = 0x0400;\n```\n\nCould someone explain what COMP(a) and COMP(b) are and how they are calculated?\n", "answer": "(x) & -(x)is equal to the lowest bit set inxwhen using 2's complement for representing binary numbers.\n\nThis meansCOMP(a) == 0x0002;andCOMP(b) == 0x0400;\n"} {"question": "I'd like to look at the source code Apache uses to process .htaccess files. I've downloaded and grepped the Apache source files with no luck.\n", "answer": "I'm suspicious of your ability to grep.. I just downloaded the httpd source and it mentionshtaccesseverywhere. Why not start by looking at the functionap_parse_htaccessdefined inserver/config.c.\n"} {"question": "This question already has answers here:What does \"%3d\" mean in a printf statement?(8 answers)Closed4 years ago.\n\ncan someone explain what the 25 in front of d does in an printf command ?\nI have searched the web but don't find a good answer.\n\ne.g.: \n printf(\"%-30s %10lu %25d - %ud\\n\", \"unsigned int\", sizeof(unsigned int), 0, UINT_MAX);\n\nThanks in advance.\n", "answer": "%d indicates decimal value.25 total field width.\n\n\n"} {"question": "This question already has answers here:What does \"%3d\" mean in a printf statement?(8 answers)Closed4 years ago.\n\ncan someone explain what the 25 in front of d does in an printf command ?\nI have searched the web but don't find a good answer.\n\ne.g.: \n printf(\"%-30s %10lu %25d - %ud\\n\", \"unsigned int\", sizeof(unsigned int), 0, UINT_MAX);\n\nThanks in advance.\n", "answer": "%d indicates decimal value.25 total field width.\n\n\n"} {"question": "I have a MIDI controller with several knobs. Is it possible to query state of all values, which these knobs have, when I connect to the device usingmidiInOpenfunction without physically moving each of them?\n", "answer": "There is no standard MIDI message to inquire about the current state of a controller; messages are sent only when something changes.\n\nUnless your controller has a vendor-specific extension that does exactly what you want, this is not possible.\n"} {"question": "I want to print function names (imported, exported, normal/local functions) but not variable names and so on.\n\nSymEnumSymbolsExenumerates all symbols, but I only want functions.\nAlso can not find how to distinguish functions and variables insidecallbackfunction.\n\nIs there a way to enumerate only functions?\n", "answer": "SYMBOL_INFOpassed to your callback hasFlags, and there isSYMFLAG_FUNCTIONfor functions\n"} {"question": "I have an fmp4 file (using h264 and aac frame codes). When playing with VLC, only video has no audio, but the audio can be parsed with PotPlayer. \nThe AAC format is ADTS.The screenshot of my fmp4 audio-related box is as follows\n\n\n\n\n\n\n\n\n", "answer": "Mp4 should not have ADTS headers in the data. Just raw aac frames plus a configuration record in esds.\n"} {"question": "I have an fmp4 file (using h264 and aac frame codes). When playing with VLC, only video has no audio, but the audio can be parsed with PotPlayer. \nThe AAC format is ADTS.The screenshot of my fmp4 audio-related box is as follows\n\n\n\n\n\n\n\n\n", "answer": "Mp4 should not have ADTS headers in the data. Just raw aac frames plus a configuration record in esds.\n"} {"question": "I am writing a C program that does many comparisons and I was wondering if this actually saves memory.\n\nAny help appreciated\n", "answer": "No, it does not. Using a tricky syntax to do something that there's a well-known syntax for is never the right answer. You should use x==a.\n"} {"question": "\"Production compilers also exist for several other machines, including the IBM System/370, the Honeywell 6000, and the Interdata 8/32.\"\n", "answer": "Compilers which are production-ready. Ie. It conforms to all requirements to be used in a production environment. It generates stable, executable software for the platform it is designed to.\n\nThis is as opposed to an experimental compiler or an in-development compiler.\n"} {"question": "\"Production compilers also exist for several other machines, including the IBM System/370, the Honeywell 6000, and the Interdata 8/32.\"\n", "answer": "Compilers which are production-ready. Ie. It conforms to all requirements to be used in a production environment. It generates stable, executable software for the platform it is designed to.\n\nThis is as opposed to an experimental compiler or an in-development compiler.\n"} {"question": "\"Production compilers also exist for several other machines, including the IBM System/370, the Honeywell 6000, and the Interdata 8/32.\"\n", "answer": "Compilers which are production-ready. Ie. It conforms to all requirements to be used in a production environment. It generates stable, executable software for the platform it is designed to.\n\nThis is as opposed to an experimental compiler or an in-development compiler.\n"} {"question": "what does asterisk(*++argv) mean?\n\n```\nvoid main (int argc, char *argv[])\n{\n while (--argc) \n {\n printf (\"%s\\n\", *++argv);\n }\n\n}\n```\n", "answer": "hereargvis a pointer to a pointer ofchartype\n\n*argvpoints to the first argument string in the argv array, which is same asargv[0], similarly*(argv + 1)andargv[1]point to second argument string and so on..\n\nPointers in C: when to use the ampersand and the asterisk?\n"} {"question": "What is_ALPHA_macro?\nI found this macroin this code.\nWhat do you use this macro for?\nPlease tell me this macro or its references.\n", "answer": "I believe it is a macro that is#defined if the file is being compiled forDEC Alpha architecture. With Windows, of course, one must note that Alpha support was there for\n\nWindows NT (discontinued after NT 4.0; and pre-release Windows 2000 RC1)\n\nit means that in practice it is never#defined.\n"} {"question": "What is_ALPHA_macro?\nI found this macroin this code.\nWhat do you use this macro for?\nPlease tell me this macro or its references.\n", "answer": "I believe it is a macro that is#defined if the file is being compiled forDEC Alpha architecture. With Windows, of course, one must note that Alpha support was there for\n\nWindows NT (discontinued after NT 4.0; and pre-release Windows 2000 RC1)\n\nit means that in practice it is never#defined.\n"} {"question": "Is there function in a C library that iterates through an array and checks if two characters are next to each other?\n\nFor example :array[30] = \"example@.com\"Is it possible to go through the array and check if '@' and '.' are next to each other?\n", "answer": "Usestrstr:\n\n```\nif (strstr(array, \"@.\") || strstr(array, \".@\"))\n /* the characters are touching */\n```\n"} {"question": "Is there function in a C library that iterates through an array and checks if two characters are next to each other?\n\nFor example :array[30] = \"example@.com\"Is it possible to go through the array and check if '@' and '.' are next to each other?\n", "answer": "Usestrstr:\n\n```\nif (strstr(array, \"@.\") || strstr(array, \".@\"))\n /* the characters are touching */\n```\n"} {"question": "The question concerns implicit multiplication by the-operator.\nFor example\n\n```\nfloat a = 10;\nfloat b;\n```\n\nb = -a;Is this valid? doesb = -10?\n", "answer": "This isn't implicit multiplication, but use of the unary-operator.\n\nThe code is valid, since the operator works on all arithmetic types, including floating point.\n"} {"question": "I am attempting to use a variable to store a conditional statement's result:\n\n```\nint age = 40;\nint validAge = age > 40;\n\nif (validAge) { /* ... */ }\n```\n\nIs the above code example allowed in C? If so, what type should I set these conditional variables?\n", "answer": "This is valid.\n\nThe expressionage > 40evaluates to either 0 or 1, so you can use any integer type (char,short,int,long, either signed or unsigned) to store it.\n"} {"question": "I am attempting to use a variable to store a conditional statement's result:\n\n```\nint age = 40;\nint validAge = age > 40;\n\nif (validAge) { /* ... */ }\n```\n\nIs the above code example allowed in C? If so, what type should I set these conditional variables?\n", "answer": "This is valid.\n\nThe expressionage > 40evaluates to either 0 or 1, so you can use any integer type (char,short,int,long, either signed or unsigned) to store it.\n"} {"question": "How can I show theprintfstatements inrpl-of0.cin the mote output window like the way we can see theprintfstatements inrpl-icmp6.c? I have triedDEBUG_PRINTandDEBUG_FULLbut to no avail.\n", "answer": "replace#define DEBUG DEBUG_NONEwith#define DEBUG DEBUG_PRINT\n"} {"question": "Why does-fsanitize=undefinedthrow\n\nruntime error: left shift of 1 by 31 places cannot be represented in type 'int'\n\non this code\n\n```\nuint32_t z;\nz = 1 << 31;\n```\n\n?\n", "answer": "Make the 1 unsigned:\n\n```\nuint32_t z;\nz = UINT32_C(1) << 31;\n```\n"} {"question": "So, I'm trying to compile my C code using the command \"gcc -o file file.c\", but I get \"error: libnet.h: No such file or directory\" I included libnet.h (#include ) and I also installed libnet. I'm running CentOS 7.\n", "answer": "yum install libnetonly installs the precompiled library.\n\nYou need to install the headers usingyum install libnet-develbefore you can use it in your own software.\n"} {"question": "It's a long time since I did any coding of any sort.\n\nI'm trying to remember the name (in C) of an item you put at the beginning of your code that allows compilation to a constant for efficiency but can have its value adjusted before compilation if necessary.\n\nWhat is it called? (specifically the name in C and optionally the name in general)\n\nThanks.\n", "answer": "#definestatements allow you to define a constant at the beginning of your code.\n"} {"question": "So, I'm trying to compile my C code using the command \"gcc -o file file.c\", but I get \"error: libnet.h: No such file or directory\" I included libnet.h (#include ) and I also installed libnet. I'm running CentOS 7.\n", "answer": "yum install libnetonly installs the precompiled library.\n\nYou need to install the headers usingyum install libnet-develbefore you can use it in your own software.\n"} {"question": "It's a long time since I did any coding of any sort.\n\nI'm trying to remember the name (in C) of an item you put at the beginning of your code that allows compilation to a constant for efficiency but can have its value adjusted before compilation if necessary.\n\nWhat is it called? (specifically the name in C and optionally the name in general)\n\nThanks.\n", "answer": "#definestatements allow you to define a constant at the beginning of your code.\n"} {"question": "Is there a possibility to split large.afiles into multiple smaller ones?\n\nI'm currently having an issue with a.afile being multiple GiB large and GCC raises an error even with the flag-mcmodel=medium.\n", "answer": "Use binutils tool \"ar\":\n\n```\nar -x libbig.a\n```\n\nfor extracting the objects from the archive and\n\n```\nar -r libsmall.a obj1.o obj2.o obj3.o\n```\n\nfor creating a new archive.\n"} {"question": "Is there a possibility to split large.afiles into multiple smaller ones?\n\nI'm currently having an issue with a.afile being multiple GiB large and GCC raises an error even with the flag-mcmodel=medium.\n", "answer": "Use binutils tool \"ar\":\n\n```\nar -x libbig.a\n```\n\nfor extracting the objects from the archive and\n\n```\nar -r libsmall.a obj1.o obj2.o obj3.o\n```\n\nfor creating a new archive.\n"} {"question": "time_t t;\n\nprintf(\"%f\\n\",time(&t));\n\nit throws \"Can not print float number\"\n", "answer": "You may try\n\n#include \nprintf(\"%jd\\n\", (intmax_t) time(NULL));.\n"} {"question": "This is my code :\n\n```\nvoid render(char * world) {...} \nint main() { \n char world[HEIGHT * WIDTH]; \n render(&world); \n return 0; \n }\n```\n\nTell me if I have given enough information! \nThanks in Advance!\n", "answer": "You just need to passworld. Passing&worldis passing the address ofworld, which is already achar *, so you're passing achar **.\n"} {"question": "This is my code :\n\n```\nvoid render(char * world) {...} \nint main() { \n char world[HEIGHT * WIDTH]; \n render(&world); \n return 0; \n }\n```\n\nTell me if I have given enough information! \nThanks in Advance!\n", "answer": "You just need to passworld. Passing&worldis passing the address ofworld, which is already achar *, so you're passing achar **.\n"} {"question": "manpages of theprintfand online documentations often showprintf(3)when explaining the functionality ofprintf. What does the \"3\" denote?\n", "answer": "3denotes the section whichprintfis a part of. Section3corresponds to: Library calls (functions within program libraries).\n\nYou could also issueman
, eg.man 3 printfto look up a keyword in a specific section.man 1 printfwill show you theprintfshell command.\n"} {"question": "I compiled a program and get\n\n```\nformat_io.c:3:6: error: cannot combine with previous 'void' declaration specifier\nvoid int int int\n ^\nformat_io.c:3:10: error: cannot combine with previous 'void' declaration specifier\nvoid int int int\n ^\n```\n\nhow readformat_io.c:3:6:,when check line 6, do no t find the void error.\n", "answer": "filename:line:column\n\nColumn 6 of line 3. And column 10 of line 3.\n"} {"question": "I'm not sure about how to get an inverse index , index%size it's ok to a straight ring index but what I need it's if tou are in 0 index get the last index as the previous of 0.\n\n```\n[0][1][2][3] // the previous index of 0 should be 3\n```\n", "answer": "In the languageCthe remainder operator can be used as follows to get a true (positive) modulo result:\n\n```\n(index+n-1)%n\n```\n\nwherenis the length of your array.\n"} {"question": "I mean this | | not this %. \nLike let's say that I've got two integers x and y and and integer z.\nNow\n\n```\nz = x - y\n```\n\nIs there a way to express |z| so that if z is positive it stays positive and if z is negative it's turnt into its opposite? I don't mean to express it with an if, just a mathematical equation, symbol or something like that.\n", "answer": "You want theabs()function, provided in themath.hheader.\n\nExample:\n\n```\nz = abs(x - y);\n```\n"} {"question": "I found this question:\n\nWhat is the output ofprintf(\"%-x\", 2048);?\n\nI know that the\"%x\"is outputting the hexadecimal format of the number, but I can' quite understand what the minus sign does here, since the output is the same for bothprintf(\"%-x\", 2048);andprintf(\"%x\", 2048);.\n", "answer": "std::printf, std::fprintf, std::sprintf, std::snprintf:\n\n-: the result of the conversion is left-justified within the field (by default it is right-justified)\n"} {"question": "I found this question:\n\nWhat is the output ofprintf(\"%-x\", 2048);?\n\nI know that the\"%x\"is outputting the hexadecimal format of the number, but I can' quite understand what the minus sign does here, since the output is the same for bothprintf(\"%-x\", 2048);andprintf(\"%x\", 2048);.\n", "answer": "std::printf, std::fprintf, std::sprintf, std::snprintf:\n\n-: the result of the conversion is left-justified within the field (by default it is right-justified)\n"} {"question": "I came up on this question:\nI have the following instruction\n\n```\nfloat *f = (float*) malloc(5*sizeof(float));\n```\n\nand a consequence of this is that\n\n```\n&f is of type float**\n```\n\nI don't understand why it's like this.\n", "answer": "The type offisfloat*, i.e., a pointer to float. So&fis the address off, so its type is address to pointer of float, aka pointer to pointer of float, meaningfloat**.\n"} {"question": "I'm trying to pass a string to a function:\n\n```\nvoid PassString(unsigned char * value)\n{\n // ...\n}\n\nint main(void)\n{\n while(1)\n {\n PassString(\"TEST\");\n }\n}\n```\n\nI'm getting warning: (359) illegal conversion between pointer types.\n", "answer": "The string literal being passed is of typechar []but the argument is given asunsigned char *.\n\nSo change the type of the argument tochar[].\n"} {"question": "Let's say I have:\n\nfile1.c\n\n```\nuint8_t array[] = {1, 2, 3};\n```\n\nmain.c\n\n```\nextern uint8_t array[];\n```\n\nDoes this create a copy of the variable array in main.c?\n", "answer": "No, it tells the linker \"there's a variable somewhere with this name, please fill in a reference to it whenever it's mentioned\".\n"} {"question": "Is it possible to have a POSIX thread remain \"alive\" after executing the function given as an argument? As in reusing that thread for further work.\n\nFor example, given a queue of functions to execute, is it possible to have a pthread execute several of them? The alternative would be creating a pthread for every task.\n", "answer": "No.\n\nWhat you describe reminds me of athread pool, where a set of threads is waiting for work (your functions in this case) to execute.\n"} {"question": "I am creating a program that implements a tic-tac-toe game using a 2-D array with multiple functions. How would I create a function where it clears all 'x' and 'o' characters in each cell and have the cells reset it back to the underscore character '_'? An example along with your explanation would be much appreciated!\n", "answer": "You can usememsetto reset the array to_as below.\n\n```\nchar array[10][10];\nmemset(array, '_', sizeof(array));\n```\n"} {"question": "Is there any way to let CLion update the declaration in the .h file if I change the function definition in the .c file ?\n\nThe copy and pasting is such a repetitive task..\n", "answer": "It depends on changes I guess. I always useRefactor->Change Signatureto update function return type, name, arguments in both files (source and header).\n"} {"question": "I have no idea how to pass command like:\n\n```\necho -e \\\"\\E[1;3mHello!\"\n```\n\ntosystem(), since I have to put it in quotation marks cause it'sconst char, any help?\n", "answer": "Double quotes need to be escaped in strings, as do backslashes:\n\n```\nsystem(\"bash -c 'echo -e \\\"\\\\E[1;3mHello!\\\"'\");\n```\n"} {"question": "Does thegcc 166 compilerfor theSiemens C167micro controller exist in open source ?, or can I find it?\n", "answer": "According to the sitelinkI found thatGCC 166it is a compiler available for sale byRigel corp\n"} {"question": "Does thegcc 166 compilerfor theSiemens C167micro controller exist in open source ?, or can I find it?\n", "answer": "According to the sitelinkI found thatGCC 166it is a compiler available for sale byRigel corp\n"} {"question": "This question already has answers here:struct declaration(2 answers)Closed4 years ago.\n\nI read such a snippet code of in5.2.  The indirection:\n\n```\nstruct contact \n{\n int n1;\n float n2;\n char st[10];\n} d1;\n```\n\nWhat's the meaning of using d1 here? is it a recommended practice to define such a struct?\n", "answer": "That simply declare astruct contactvariable namedd1. That is not really readable and is not used generally.\n"} {"question": "I was given the task of writing a program that determines the maximum number of processes a user can have, just like the bash's \"ulimit -u\" built-in command butusing system calls and C. Any hint as to how achieve this?\n", "answer": "Theulimitbuiltin is just an interface to thegetrlimitandsetrlimitfunctions.\n\nSee thegetrlimit, setrlimit man page.\n\nIn particular, you are interested in theRLIMIT_NPROCresource.\n"} {"question": "I see that theapr_pool_*interface exposes\n\nvoid apr_pool_tag (apr_pool_t *pool, const char *tag)\n\nwhich lets me tag a pool.\n\nThat's all well and good, but how do I extract the tag from a pool at a later time? I can't find the \"getter\" for the above setter. How are these tags used?\n", "answer": "Trunk (aka 2.0) has anapr_pool_get_tag(), but in released branches pool tagging is meant as a debugging aid. In other words, post-mortem analysis with a debugger.\n"} {"question": "I see that theapr_pool_*interface exposes\n\nvoid apr_pool_tag (apr_pool_t *pool, const char *tag)\n\nwhich lets me tag a pool.\n\nThat's all well and good, but how do I extract the tag from a pool at a later time? I can't find the \"getter\" for the above setter. How are these tags used?\n", "answer": "Trunk (aka 2.0) has anapr_pool_get_tag(), but in released branches pool tagging is meant as a debugging aid. In other words, post-mortem analysis with a debugger.\n"} {"question": "I see that theapr_pool_*interface exposes\n\nvoid apr_pool_tag (apr_pool_t *pool, const char *tag)\n\nwhich lets me tag a pool.\n\nThat's all well and good, but how do I extract the tag from a pool at a later time? I can't find the \"getter\" for the above setter. How are these tags used?\n", "answer": "Trunk (aka 2.0) has anapr_pool_get_tag(), but in released branches pool tagging is meant as a debugging aid. In other words, post-mortem analysis with a debugger.\n"} {"question": "I have a UnsafeMutablePointer pointing at a C string, I want to convert the bytes at this pointer to a Swift String, the data is a C string, so UTF8.\n\nIs it possible to iterate byte by byte until NULL? Or some easier way?\n", "answer": "CChar is an alias for Int8, so you can useCChar-based methodshere.\n\n```\nlet str = String(cString: pointer)\n```\n"} {"question": "Let's say I have two variables.\n\n```\nint a = -10;\nint b = 10;\n```\n\nHow can I return 0 if they have different sign or 1 if they have same signs ?\nAgain without if statements\n", "answer": "Like this?\n\n```\nreturn ((a >= 0 && b >= 0) || (a < 0 && b < 0));\n```\n"} {"question": "For example:\n\n```\nvoid *p1 = someStringPointer;\nvoid *p2 = p1;\n```\n\nAlthough these are two unique pointers, given that they both point to the same value, are they still different memory objects?\n", "answer": "If you print the address ofp1andp2\n\n```\nprintf(\"%p\\n\", (void *) &p1);\nprintf(\"%p\\n\", (void *) &p2);\n```\n\nThey have different addresses, so yes they are different memory objects.\n"} {"question": "How can I create an array such that I could access the elementsa[1000000],a[1]anda[2]and not even using the size of 1000000?\n\nIf possible please provide the answer inC++.\n", "answer": "Usestd::unordered_map<>.\n\n```\nenum { N = 9 };\nint arr[N] = { 0 };\nstd::unordered_map m;\nfor (int i = 0; i < N; i++)\n{\n ++m[arr[i]];\n}\n```\n"} {"question": "In this code the person has to enter y if wishes to continue, but why does it ask him the question two times when he enters y.\n\n```\nchar c = 'y';\nwhile(c!='n'){\n printf(\"Do you wish to continue: (y or n):\");\n c = getchar();\n}\n```\n\nHere is the console\n", "answer": "why does it ask him the question two times when he enters y\n\nThe enter key the user hits is taken as another character (a new-line:\\n) as well.\n"} {"question": "In this code the person has to enter y if wishes to continue, but why does it ask him the question two times when he enters y.\n\n```\nchar c = 'y';\nwhile(c!='n'){\n printf(\"Do you wish to continue: (y or n):\");\n c = getchar();\n}\n```\n\nHere is the console\n", "answer": "why does it ask him the question two times when he enters y\n\nThe enter key the user hits is taken as another character (a new-line:\\n) as well.\n"} {"question": "I am following instructions to write a program of characters counting:\n\n```\n#include \nmain()\n{\n double nc;\n\n for (nc=0; getchar() != EOF; ++nc);\n printf(\"%.0f\\n\", nc);\n}\n```\n\nAfter it was compiled and run,\n\n```\n$ ./a.out\nff\nfdg\nfd\n\n\nfdr\n```\n\nIt did not print the counting.What's the problem with my code?\n", "answer": "I'm pretty sure you never enterEOF.\n\nUseControl+Zon Windows orControl+Don UNIX/Linux/OSX to getEOF.\n"} {"question": "I am struggling to understand if there is any overflow with the following equation using 8 bit signed integers.0b00000000 - 0b10000000\n", "answer": "This question is taggedc, and in C, all arithmetic in types lower-rank thanintgets promoted toint, andinthas at least 16-bit range, so(signed char)0-((signed char)-128)is just 128.\n"} {"question": "I was getting wrong values fromlog(), so I wrote this program just for testing:\n\n```\n#include \n#include \nvoid main()\n{\n printf (\"%1f\", log(10));\n}\n```\n\nThis should print \"1\", but I get \"2.302585\"\n\nWhy is this and how can I fix it?\n", "answer": "Thelogfunction is for thenaturallogarithm with basee.\n\nIt seems you wantlog10instead.\n"} {"question": "```\nstruct Node *prevX = NULL, *currX = *head_ref; \n while (currX && currX->data != x) \n { \n prevX = currX; \n currX = currX->next; \n }\n```\n\nWhy was currX placed here? How can it affect the outcome?\n", "answer": "while (currX)tests the truthiness ofcurrX. It's effectively short forwhile (0!=currX).\n"} {"question": "```\nstruct Node *prevX = NULL, *currX = *head_ref; \n while (currX && currX->data != x) \n { \n prevX = currX; \n currX = currX->next; \n }\n```\n\nWhy was currX placed here? How can it affect the outcome?\n", "answer": "while (currX)tests the truthiness ofcurrX. It's effectively short forwhile (0!=currX).\n"} {"question": "I have a rather odd situation where I will have multiple interfaces connected to the same network. When I receive a broadcast or multicast message, I would like to know what interface it came from. It there a way to do that in C or ideally Python?\n\nThanks!\n", "answer": "The most obvious one would be to bind several sockets, each toone interface only- do not listen to0.0.0.0.\n"} {"question": "What is the intention to set handle to an object as pointer-to pointer but not pointer? Like following code:\n\n```\nFT_Library library;\nFT_Error error = FT_Init_FreeType( &library );\n```\n\nwhere\n\n```\ntypedef struct FT_LibraryRec_ *FT_Library\n```\n\nso&libraryis aFT_LIBraryRec_handle of typeFT_LIBraryRec_**\n", "answer": "It's a way toemulatepass by reference in C, which otherwise only have pass by value.\n"} {"question": "What is the intention to set handle to an object as pointer-to pointer but not pointer? Like following code:\n\n```\nFT_Library library;\nFT_Error error = FT_Init_FreeType( &library );\n```\n\nwhere\n\n```\ntypedef struct FT_LibraryRec_ *FT_Library\n```\n\nso&libraryis aFT_LIBraryRec_handle of typeFT_LIBraryRec_**\n", "answer": "It's a way toemulatepass by reference in C, which otherwise only have pass by value.\n"} {"question": "If there is a broken VHD chain (for example the parent VHD was modified, that's why the child no longer mounts), there's a way to fix it by using Hyper-V \"Reconnect\" feature. How do I do the same programmatically?\n", "answer": "I think you wantAttachVirtualDisk, but I'm not sure if that's what you are after with regards to VHD chains.\n"} {"question": "If there is a broken VHD chain (for example the parent VHD was modified, that's why the child no longer mounts), there's a way to fix it by using Hyper-V \"Reconnect\" feature. How do I do the same programmatically?\n", "answer": "I think you wantAttachVirtualDisk, but I'm not sure if that's what you are after with regards to VHD chains.\n"} {"question": "```\nint pop(STA* stack)\n{\n if (!isEmpty(stack))\n return stack->array[stack->top--] ;\n return '$';\n}\n```\n\nWhat is the useage of the (return'$') in this function?\nWhat kind of value will it return?\n", "answer": "It seems like it's just default return value in case stack is empty (which should not really happen, precondition of callingpop()should be for stack not to be empty. )\n\nIt will return 36 ( code of$)\n"} {"question": "I noticed thatprintf()has specifiers%Fand%f.\n\nWhat are the differences? The link above says%Fwill give \"Decimal floating point, uppercase\".\n\nI fail to see what an uppercase floating point is.\n\nThanks!\n", "answer": "Per the C 2018 standard, clause 7.21.6.1, paragraph 8:\n\nThe F conversion specifier produces INF, INFINITY, or NAN instead of inf, infinity, or nan, respectively.\n"} {"question": "I have a portion of the code as:\n\n```\n__weak void TimingDelay_Decrement(void) {\n\n}\n```\n\nand it keeps throwing up the captioned error. I checked the web and couldn't find relevant content for the__weakcase. Any help is appreciated.\n", "answer": "Because it is ARM Cortex gcc toolchain so the__weakis a definition of__attribute__((weak)).\n\nThe easiest way to add is to amend thegcccommand line arguments:-D__weak=__attribute__((weak))\n"} {"question": "If I have multiple if-statements nested inside each other which are all in a for-loop, will a break statement on the inner-most if-statement break out of the for-loop or just into the next if statement?\n", "answer": "It will break the loop (the inner most loop that the if contains in) no matter how many if statments are nested inside. Abreakbreaks from a loop and not from if statement.\n"} {"question": "This program gives output as 4 3 2 1.\nWhy does it stop at 1 when no condition is given for i?\nDo main(10) and main(i) differ?\n\n```\n#include \nint main()\n{\n static int i = 5;\n if (--i){\n printf(\"%d \", i);\n main(i);\n }\n}\n```\n", "answer": "You actually have a condition:\n\nif (--i)is equivalent toif(--i != 0)\n"} {"question": "I typed this program on code blocks but it is showing error on int main line\nHere's the program\n\n```\n#include \n\nint main()\n{\n printf(\"Hello\");\n return 0;\n }\n```\n\nThe message return is \" multiple definition of main\"\n", "answer": "The sample code is correct. It might be an IDE configuration error. Usegccto compile your code on Linux and on Windows you can installMinGWand execute from a command window.\n"} {"question": "I am a beginner to ffmpeg and libavcodec in c programming on a linux machine. I want to know the difference between these API's.\n", "answer": "av_register_allregisters absolutely everything - i.e. muxers, demuxers and protocols + it calls toavcodec_register_all.avcodec_register_allonly registers codecs. Bare codecs are seldom useful as such.\n"} {"question": "```\nmain()\n{\nchar a1='=';\nchar a2='=';\nprintf(\"%d\",a1+a2);\n}\n```\n\nCode is as above , it simply perform '='+'=' and printing the value 122.(why??)..\n", "answer": "Because ASCII value of'='is61\n\nASCII Values\n"} {"question": "the following short code snippet results in a invalid initializer error, and as a beginner in C, I do not understand why.\n\n```\nunsigned char MES[] = { 0x00, .... };\nunsigned char *in[] = &MES;\n```\n\nIs this not the correct way to do it?\n", "answer": "&MESis a pointer to an array ofunsigned char.\n\ninis an array of pointers tounsigned char.\n\nTry instead :\n\n```\nunsigned char (*in)[] = &MES;\n```\n\nwhich makesinalso a pointer to an array ofunsigned char.\n"} {"question": "All I can find on this topic is mentions ofFSMoveObjectToTrashSyncfunction, which is nowdeprecated and no alternative is listed for it.\n\nHow to do it from C or Objective-C code?\n", "answer": "Use NSFileManager:\n\nhttps://developer.apple.com/documentation/foundation/nsfilemanager\n\ntrashItemAtURL:resultingItemURL:error:\n Moves an item to the trash.\n"} {"question": "This question already has answers here:How to check the value of errno?(3 answers)Closed5 years ago.\n\nI'm using syscallstat, it returns 0/-1. When -1 is returned it means, error occurred and errno is set as it should be (source:man 2 stat).\n\nBut I want to access errno and print it, how to do that?\n", "answer": "You can get it fromerrno.\n\nAlso you can print the error usingstrerror\n"} {"question": "i'm recording with VUG and receive this error when click a button to acces to another page.\n\nhere is my configuration:\n\n\n\n\n\n\n\n\n\nIf someone know how to solve it, thanks in advance.\n", "answer": "go under recording options and set a new connection. \nAny server, all Ports (value 0) and go further with the settings (direct/proxy etc.). If you are not sure which settings you should use just try and edit them as long as the record is empy\n"} {"question": "i'm recording with VUG and receive this error when click a button to acces to another page.\n\nhere is my configuration:\n\n\n\n\n\n\n\n\n\nIf someone know how to solve it, thanks in advance.\n", "answer": "go under recording options and set a new connection. \nAny server, all Ports (value 0) and go further with the settings (direct/proxy etc.). If you are not sure which settings you should use just try and edit them as long as the record is empy\n"} {"question": "What I'm trying to do would look like this in Python\n(wherenis float/double):\n\n```\ndef check_int(n):\n if not isinstance(n, numbers.Integral):\n raise TypeError()\n```\n\nSince C/C++ are typestrong, what kind of cast-and-compare magic would be the best for this purpose?\n\nI'd preferably want to know how it's done in C.\n", "answer": "Usefloor\n\n```\n#include \n\nif (floor(n) == n)\n // n is an integer (mathematically speaking)\n```\n"} {"question": "Is it possible to create a window without it showing up on taskbar in X11 using c?\n", "answer": "That depends on GUI toolkit you are using. For example, GTK+ providesgdk_window_set_skip_taskbar_hintfunction.\n\nIf you don't use any GUI toolkit and directly interface X11, you need to add_NET_WM_STATE_SKIP_TASKBARatom to_NET_WM_STATEproperty.\n"} {"question": "Is it possible to create a window without it showing up on taskbar in X11 using c?\n", "answer": "That depends on GUI toolkit you are using. For example, GTK+ providesgdk_window_set_skip_taskbar_hintfunction.\n\nIf you don't use any GUI toolkit and directly interface X11, you need to add_NET_WM_STATE_SKIP_TASKBARatom to_NET_WM_STATEproperty.\n"} {"question": "```\nconst int rxBytes = uart_read_bytes(UART_NUM_0, data, RX_BUF_SIZE, 10 / portTICK_RATE_MS);\n```\n", "answer": "To flush input data you can read from the uart repeatedly with a timeout of 0 until zero bytes are returned.\n"} {"question": "void TraverseList(const List *l , void (*Visit)(ListEntry)) { // }\n\nI confused about the above function call within the argument of a function,how it is working?\n", "answer": "Visitis a function pointer parameter passed to theTraverseListfunction. It should point to a function with the format\n\n```\nvoid func (ListEntry);\n```\n\nLikely,TraverseListwill call the passed function for every item in the list.\n"} {"question": "void TraverseList(const List *l , void (*Visit)(ListEntry)) { // }\n\nI confused about the above function call within the argument of a function,how it is working?\n", "answer": "Visitis a function pointer parameter passed to theTraverseListfunction. It should point to a function with the format\n\n```\nvoid func (ListEntry);\n```\n\nLikely,TraverseListwill call the passed function for every item in the list.\n"} {"question": "When we have :\n\n```\nstruct node {\n char...\n int....\n struct node *....\n}\n\ntypedef struct node Node;\n```\n\nand then we have a function like this:\n\n```\nint function(Node f){...}\n```\n\nWhat is thisf?\n", "answer": "fis an input argument of the typeNode. The typeNodeis synonym of the typestruct node.\n"} {"question": "```\n#include \nint main()\n{\n int i=0;\n while(i++,i<=8);\n printf(\"%d\\n\",i);\n return 0;\n}\n```\n\nWhy is the increment ofidone after the comparison in each test case?\n", "answer": "i <= 8succeeds for the last time wheni = 8.\n\nIn the last iteration,i++is executed, theni <= 8fails becausei = 9.\n\nNote that the,is asequence point, soi++is absolutely guaranteed to be executed beforei <= 8.Not so for similar constructs.\n"} {"question": "```\n#include \nint main()\n{\n int i=0;\n while(i++,i<=8);\n printf(\"%d\\n\",i);\n return 0;\n}\n```\n\nWhy is the increment ofidone after the comparison in each test case?\n", "answer": "i <= 8succeeds for the last time wheni = 8.\n\nIn the last iteration,i++is executed, theni <= 8fails becausei = 9.\n\nNote that the,is asequence point, soi++is absolutely guaranteed to be executed beforei <= 8.Not so for similar constructs.\n"} {"question": "I have this code\n\n```\nif(orden[i]==1)\n for(i=0; i\n#include \n\nint main(int argc, char const *argv[])\n{\n int sum = 0;\n int i = 1;\n for(;i\n#include \n\nint main(int argc, char const *argv[])\n{\n int sum = 0;\n int i = 1;\n for(;i> pos;\n}\n```\n"} {"question": "I'm wondering if someone know effective approach to calculate bits in specified position along array?\n\n\n", "answer": "Assuming that OP wants to count active bits\n\n```\nsize_t countbits(uint8_t *array, int pos, size_t size)\n{\n uint8_t mask = 1 << pos;\n uint32_t result = 0;\n\n while(size--)\n {\n result += *array++ & mask;\n }\n return result >> pos;\n}\n```\n"} {"question": "I am making calculator for physics, but when I was coding the focal length equation I needed to find the reciprocal of the fraction found for the focal length.\n", "answer": "```\ndouble eqn_reciprocal= pow(eqn,-1);\n```\n\nthis would do the trick\n"} {"question": "PVS-Studio gave me a warning about this :\n\n```\nchar c;\nsscanf(line, \"%d\", &c);\n```\n\nI changed %d to %c but this created a bug because \"c\" now contains the ASCII value of the number and not the decimal one, so I went back to \"%d\".\n\nSo what's the correct specifier to ? is there another solution ?\n", "answer": "cis achar. You asked to scan anint. PVS-Studio did right in warning you. Change the type ofctointand scan for a%d.\n"} {"question": "I am facing difficulty in converting a binary array to a decimal number:\n\n```\nbin[8] = {10,00,00,10};\n```\n\nI want the equivalent of this array element as a decimal number, i.e.130.\n", "answer": "A standard solution goes like this:\n\n```\nint f(char s[])\n{\n int n = 0;\n int i;\n\n for (i = 0; i < 8; ++i) {\n n <<= 1;\n n += s[i] - '0';\n }\n\n return n;\n}\n```\n"} {"question": "I am facing difficulty in converting a binary array to a decimal number:\n\n```\nbin[8] = {10,00,00,10};\n```\n\nI want the equivalent of this array element as a decimal number, i.e.130.\n", "answer": "A standard solution goes like this:\n\n```\nint f(char s[])\n{\n int n = 0;\n int i;\n\n for (i = 0; i < 8; ++i) {\n n <<= 1;\n n += s[i] - '0';\n }\n\n return n;\n}\n```\n"} {"question": "I'm new to C and wanted to know, what does a bitwise shift 1 << 9 in an enum definition do in this case below:\n\n```\nstatic enum {\n DEAD, LIVE\n} state[1 << 9];\n```\n", "answer": "The expression1<<9is the same as 29, which is 512.\n\nSo an array of 512 enums is declared.\n"} {"question": "Code to receive message like \"hi i am man\" and convert it to upper case \"HI I AM MAN\".\n\n```\nn = read(newsockfd, buffer, 255);\nprintf(\"Here is the message: %s\\n\", buffer);\n```\n", "answer": "```\n#include \n#include \n\n n = read(newsockfd, buffer, 255);\n for(int i = 0; i < n; i++)\n buffer[i] = toupper(buffer[i]);\n printf(\"Here is the message: %s\\n\", buffer);\n```\n"} {"question": "I am confused as to how to set the \"editable\" property to a specific child of a GtkTreeView, instead of the entire cell renderer.\n\n```\n| Column |\n[+] Parent\n |__ Child\n |__ Child2 <-- Press to edit\n```\n\n\n\nI didn't seem to find a way to do that.\n", "answer": "You add another boolean column to your ListStore. Then set your Renderer editable property to that extra column.\n\nSorry, I don't know the C code for a short example.\n"} {"question": "The elements of an uninitialized char array in C all have the value 'Ì' (or -52 as an integer; 0xCC or 204 as char). Is this another type of null character? Or is it just a value that fills in the values of an uninitialized char array?\n\n(In case it makes any difference, I am using visual studio)\n", "answer": "Uninitialized variables have indeterminate values. They can make the behavior of your program undefined if the value is used to be a trap representation.\n"} {"question": "For example, I have two digit bits:\n\n```\n0b0111111\n0b0000110\n```\n\nI want to shift a state variable by 7 digits and combine them together.\n\n```\n0b00001100111111\n```\n\nCan I accomplish by shifting?\n", "answer": "You do this by shifting the bottom number left 7 digits, then performing a bitwise OR of the result and the first number.\n\n```\nunsigned int a = 0x3f;\nunsigned int b = 0x06;\nunsigned int result = (b << 7) | a;\n```\n"} {"question": "I feel like I've been searching for hours today on how to make#include work in Visual Studio 2017 on Windows 10 and haven't come across an answer that has worked. Can someone please instruct me how to get this to work?\n\nThe error I receive is: cannot open source file \"pthread.h\"\n", "answer": "In Visual Studio 2017\n\nProject -> Manage Nuget PackagesIn browse Tab search for 'pthread'Select Install[Search Results in Nuget packages]\n\n\n"} {"question": "I feel like I've been searching for hours today on how to make#include work in Visual Studio 2017 on Windows 10 and haven't come across an answer that has worked. Can someone please instruct me how to get this to work?\n\nThe error I receive is: cannot open source file \"pthread.h\"\n", "answer": "In Visual Studio 2017\n\nProject -> Manage Nuget PackagesIn browse Tab search for 'pthread'Select Install[Search Results in Nuget packages]\n\n\n"} {"question": "I feel like I've been searching for hours today on how to make#include work in Visual Studio 2017 on Windows 10 and haven't come across an answer that has worked. Can someone please instruct me how to get this to work?\n\nThe error I receive is: cannot open source file \"pthread.h\"\n", "answer": "In Visual Studio 2017\n\nProject -> Manage Nuget PackagesIn browse Tab search for 'pthread'Select Install[Search Results in Nuget packages]\n\n\n"} {"question": "What is the meaning of the following operation in C\n\n```\nUSIC2_CH0->PSR &= ~((uint32_t)USIC_CH_PSR_ASCMode_TFF_Msk);\n```\n\nI know that ifA|=BmeantA=A|Bthen what is meant by\n\nA&=~B;? Does that meantA=~(A&B)??\n", "answer": "A &= ~BmeansA = A & (~B), notA=~(A&B).\n\nYou can see those two are different if you take A=b010 and B=b110, for example.\n\nIn context it's disabling the bits in that PSR bitfield that are set in the constant whose name ends in \"TFF_Msk\" above.\n"} {"question": "How can I use assembly instructions that contain quotation marks insideasm()?\nlike:\n\n```\nasm(\n\".section .rdata,\"dr\"\\n\"\n);\n```\n\nThe code above gives me this error:\n\n```\nexpected ')' before 'dr'\n```\n", "answer": "Any string literal, not just the ones required by anasmdeclaration, can contain double quotes if they are escaped. You escape them with a\\. So when applied to your example:\n\n```\nasm(\n\".section .rdata,\\\"dr\\\"\\n\"\n);\n```\n"} {"question": "Im learning for my upcoming exam and i wanted to ask if an Array counts blanks.\n\ne.g in the Image below: does he count like the first row?\n\n\n", "answer": "It's an array of characters yes it counts the spaces,\nit should be in the 9 position the first blank/space and the first (i) should be in 10 position and etc and in the end of the array should be a /0..\n\np.s: null is a character also, that gets on the end of the array\n"} {"question": "Im learning for my upcoming exam and i wanted to ask if an Array counts blanks.\n\ne.g in the Image below: does he count like the first row?\n\n\n", "answer": "It's an array of characters yes it counts the spaces,\nit should be in the 9 position the first blank/space and the first (i) should be in 10 position and etc and in the end of the array should be a /0..\n\np.s: null is a character also, that gets on the end of the array\n"} {"question": "Im learning for my upcoming exam and i wanted to ask if an Array counts blanks.\n\ne.g in the Image below: does he count like the first row?\n\n\n", "answer": "It's an array of characters yes it counts the spaces,\nit should be in the 9 position the first blank/space and the first (i) should be in 10 position and etc and in the end of the array should be a /0..\n\np.s: null is a character also, that gets on the end of the array\n"} {"question": "How can I define the type of an enum to beuint8instead ofint?\n\n```\ntypedef enum\n{\n R_DIRECTION_LEFT = 1,\n R_DIRECTION_RIGHT = 2,\n R_DIRECTION_TOP = 4,\n R_DIRECTION_BOTTOM = 8\n} R_Direction;\n```\n", "answer": "No you can't.\n\nFrom standard §6.4.4.3C11 standard N1570\n\nAn identifier declared as an enumeration constant has type int.\n"} {"question": "I have a program that uses dynamic allocation for a uint8_t array; can I safely \nassume that its length will always be one byte?\n", "answer": "Ifuint8_texists, thensizeof(uint8_t)must be 1.uint8_tisrequiredto have width exactly 8 and no padding bits, andCHAR_BITis required to be at least 8. Ifuint8_texists, it can't have more than one char's worth of bits without violating these requirements.\n"} {"question": "How can I define the type of an enum to beuint8instead ofint?\n\n```\ntypedef enum\n{\n R_DIRECTION_LEFT = 1,\n R_DIRECTION_RIGHT = 2,\n R_DIRECTION_TOP = 4,\n R_DIRECTION_BOTTOM = 8\n} R_Direction;\n```\n", "answer": "No you can't.\n\nFrom standard §6.4.4.3C11 standard N1570\n\nAn identifier declared as an enumeration constant has type int.\n"} {"question": "I'm writing a user define function for Vertica and don't know how to initialize a Vstring of Vertica from a C string (char *) . Thanks for any suggestion?\n", "answer": "Following to Vertica documentation:\n\nYou cannot create instances ofVStringorVNumericyourself. You can manipulate the values of existing objects of these classes that HP Vertica passes to your UDx, and extract values from them. However, only HP Vertica can instantiate these classes.\n"} {"question": "For example, if I allocate more memory space then needed on a C string is there a way to return back the unused memory? Or is this automatically done?\n\n```\nchar *x = malloc(256);\nstrcpy(x, \"Hello World\");\n// return back unused x memory allocation\n```\n", "answer": "You can callreallocto change the size of an allocation; this can be used to make it bigger or smaller.\n\nThe computer would have no basis for automatically making your allocation smaller.\n"} {"question": "Not C# or C++, but C. Is there any C support in Visual Studio?\n", "answer": "Using theVisual Studio Installerif you click on your already installed version of Visual Studio (in the image I clicked on my VS 2017 Community).\n\nUnderIndividual components-->Compilers, build tools and run-timesyou can checkClang/C2. Clang is aCcompiler.\n\nAnswer:by default it appears not, but you can install the Clang component and it appears you will be able to.\n\n\n"} {"question": "Not C# or C++, but C. Is there any C support in Visual Studio?\n", "answer": "Using theVisual Studio Installerif you click on your already installed version of Visual Studio (in the image I clicked on my VS 2017 Community).\n\nUnderIndividual components-->Compilers, build tools and run-timesyou can checkClang/C2. Clang is aCcompiler.\n\nAnswer:by default it appears not, but you can install the Clang component and it appears you will be able to.\n\n\n"} {"question": "```\nFILE * fp = fopen (\"excel.csv\" , \" w+ \");\nfprintf (fp, \"%s\", \"hello,world\");\n```\n\nI want to printhello,worldwith comma in a single cell.\nHow can I print the same without printing in two different cells?\n", "answer": "Put quotes around the cell:\n\n```\nfprintf(fp, \"%s\", \"\\\"hello,world\\\"\");\n```\n\nIIRC Wikipedia hasa pretty good article on CSV.\n"} {"question": "When compiling a C program the compiler/linker will generate a symbol table. How can we print that symbol table and what values it will store in the terminal?\n", "answer": "You can view the symbols of a compiled program or object file withnm(1):\n\n```\nnm a.out\n```\n\nDisplays all symbols ina.out.\n"} {"question": "When compiling a C program the compiler/linker will generate a symbol table. How can we print that symbol table and what values it will store in the terminal?\n", "answer": "You can view the symbols of a compiled program or object file withnm(1):\n\n```\nnm a.out\n```\n\nDisplays all symbols ina.out.\n"} {"question": "I would like to realize in GTK3 a text window where to redirect the stdout using the c language.\nCould you help me with suggestions about how to start.\nThank you.\n", "answer": "I think what you'll need to do is write GTK code that reads from a named pipe and writes to the text box, and when you start your other c code (assuming you're starting it from a shell command), redirect stdout to the named pipe.\n"} {"question": "I would like to realize in GTK3 a text window where to redirect the stdout using the c language.\nCould you help me with suggestions about how to start.\nThank you.\n", "answer": "I think what you'll need to do is write GTK code that reads from a named pipe and writes to the text box, and when you start your other c code (assuming you're starting it from a shell command), redirect stdout to the named pipe.\n"} {"question": "I'm trying to compile library from .c file in Xcode. (It doesn't give me any errors in Visual Studio on Windows) But Xcode gives:\n\nUse of undeclared identifier 'byte'\n\nin the next line:\n\n```\nbuf[2] = (byte)(addr & 0xff);\n```\n", "answer": "In the .c file i have declaredbytewith the next code:\n\n```\ntypedef uint8_t byte\n```\n\nuint8_t is similar to byte, so it compiled\n"} {"question": "I'm trying to compile library from .c file in Xcode. (It doesn't give me any errors in Visual Studio on Windows) But Xcode gives:\n\nUse of undeclared identifier 'byte'\n\nin the next line:\n\n```\nbuf[2] = (byte)(addr & 0xff);\n```\n", "answer": "In the .c file i have declaredbytewith the next code:\n\n```\ntypedef uint8_t byte\n```\n\nuint8_t is similar to byte, so it compiled\n"} {"question": "What does this line mean?\n\n```\nif (strcmp(argv[0],\"./lower\")==0)\n```\n\nBefore converting to lower or upper case why this condition is checked?\nWhat does it results to?\n", "answer": "Comparingargv[0]is checking the name of the executable.\n\nI assume you look at code similar tobusyboxin which you check the executable that the user used so you know which action to perform.\n"} {"question": "What is the difference between the two Instruction pointers (eip)? What is the goal of each one?\n\nFrame info image:\n\n\n\nThere are two different eip?\n", "answer": "saved eipis the address that your frame willreturnto (i.e. oni*86it's the address of the next instruction after theCALL).\n\neipis thecurrentinstruction pointer, i.e. the address of instruction that is going to be executed next (once control returns to this frame).\n"} {"question": "What is the difference between the two Instruction pointers (eip)? What is the goal of each one?\n\nFrame info image:\n\n\n\nThere are two different eip?\n", "answer": "saved eipis the address that your frame willreturnto (i.e. oni*86it's the address of the next instruction after theCALL).\n\neipis thecurrentinstruction pointer, i.e. the address of instruction that is going to be executed next (once control returns to this frame).\n"} {"question": "Is there a way to send a signal to all the processes of a process ID group except for the one that is sending it?\n\nWithkill(0, SIGUSR1)we can send it to all the processes of a group including the one calling it, but what if we wanted to send it to all except for the one calling it?\n", "answer": "```\n#include \n#include \n...\nsignal(SIGUSR1, SIG_IGN); /* Ignore own signal */\n\nkillpg(getpgrp(), SIGUSR1); /* Send SIGUSR1 to pgrp */\n```\n"} {"question": "Why \"strrev()\" and some other inbuilt string functions in c doesn't work in terminal?\n\n```\n#include\nmain()\n{\nchar c[50];\nscanf(\"%s\",c);\nstrrev(c);\nprintf(\"%s\",c)\n}\n```\n", "answer": "strrevis not standard, but can be easily implemented\n\n```\nvoid strrev(char *s) {\n int i,n = strlen(s);\n for(i=n/2 ; i>=0 ; i--) {\n char c = s[i];\n s[i] = s[n-i-1];\n s[n-i-1] = c;\n }\n}\n```\n"} {"question": "I need to add quotes in begging and ending of a char.\n\n```\nchar *Mychar = \"hello\"; \nprintf(\"%c\\n\",Mychar[0]);\n```\n\nMy result ishand my desired result is'h'.\n", "answer": "Just add them in the format string. For single quotes, you can just put them in there:\n\n```\nprintf(\"'%c'\\n\",Mychar[0]);\n```\n\nFor double quotes, you'll have to escape them:\n\n```\nprintf(\"\\\"%c\\\"\\n\",Mychar[0]);\n```\n"} {"question": "This question already has answers here:Implicit type promotion rules(5 answers)Closed5 years ago.\n\nThe result of the values ​of A and B is as follows.\n", "answer": "In the first case, the type of the expression on the right-hand side isint, and the value is -121. In the second case, the type isuint32_t, and the value isuint32_t(-121) == 4294967175. The latter cannot be precisely represented in afloat, so it gets rounded.\n"} {"question": "This question already has answers here:Implicit type promotion rules(5 answers)Closed5 years ago.\n\nThe result of the values ​of A and B is as follows.\n", "answer": "In the first case, the type of the expression on the right-hand side isint, and the value is -121. In the second case, the type isuint32_t, and the value isuint32_t(-121) == 4294967175. The latter cannot be precisely represented in afloat, so it gets rounded.\n"} {"question": "Is it possible (using the CPLEX C APIs) to retrieve the variables type (CPX_CONTINUOUS, CPX_BINARY, CPX_INTEGER, ...) of a model not handled by me but directly built from an .mps file?\n", "answer": "Yes, you can use theCPXgetctypefunction. Here's the example given in the documentation link:\n\n```\nstatus = CPXgetctype (env, lp, ctype, 0, cur_numcols-1);\n```\n\nTo get the number of columns useCPXgetnumcols.\n"} {"question": "I have a code where am gettingPC Lint info 825, even though I'm using/* fallthrough */comment. Tell me if any of my usage is wrong.\n\nExample code:\n\n```\ncase 1:\n\ncase 2:\n\ncase 3:\n{\n statement;\n}\n\n/* fallthrough */\n\ncase 4:\n{\nstatement 1;\nstatement 2;\nbreak;\n}\n\ndefault:\nbreak;\n```\n", "answer": "That's the wrong comment content. Try:\n\n```\n//lint -fallthrough\n```\n\nSeethe huge text filefor details.\n"} {"question": "I want to get a samesemIdusing same key.\nAlthough, I calledsemgetmethod using same key, and returned differentsemId.\n\nPlease answer me the reason why this problem happened.\n\nSample source :\n\n```\nint id1, id2;\nint semflg = IPC_CREAT | 0666;\nid1 = semget(0, 1, semflg);\nid2 = semget(0, 1, semflg);\n```\n\nResult : id1 != id2\n", "answer": "Key id0isIPC_PRIVATE, and will always generate a new set of semaphores. Choose a valid key.\n"} {"question": "I want to get a samesemIdusing same key.\nAlthough, I calledsemgetmethod using same key, and returned differentsemId.\n\nPlease answer me the reason why this problem happened.\n\nSample source :\n\n```\nint id1, id2;\nint semflg = IPC_CREAT | 0666;\nid1 = semget(0, 1, semflg);\nid2 = semget(0, 1, semflg);\n```\n\nResult : id1 != id2\n", "answer": "Key id0isIPC_PRIVATE, and will always generate a new set of semaphores. Choose a valid key.\n"} {"question": "In Code::Blocks when i run and debug my code it says in the \"Build messages section\" (error: Cannot find id) I reinstalled both the coding platform (code::blocks) and the compiler individually and nothing has changed.\n", "answer": "Try simple program first to see if installation is correct:\n\n```\n#include \n\nint main()\n{\n printf(\"Hello World\");\n\n return 0;\n}\n```\n"} {"question": "Can I safely usememmem()if I want it to also run on Mac?\n\nI know it requires:\n\n```\n#define _GNU_SOURCE\n#include \n```\n", "answer": "Yes,memmemis available on MacOS. Seethe man pagefor details.\n\nYou don't however need to#define _GNU_SOURCE. That is specific to Linux.\n"} {"question": "I'm trying to make a game program in C.\nHow to get a char or input without displaying and pausing the screen?\n", "answer": "You mentioned you want to make a game in C.\n\nCreate your own window.\nCapture and Process events.\n\nThis sounds a bit much for a beginner but actually it is not.\nUse a library like SDL2 to help you with that.\n\nHere is atutorial seriesthat walks you through some of the basics of game making.\n"} {"question": "Is there a way to find which interface has been used to join an IPv6 multicast group, if the index used was 0 meaning that we leave to the kernel to choose which interface is suitable. \nCan we get that information afterwards?\n", "answer": "Does the IPV6_MULTICAST_IF socket option change after the join is complete? If not you'll have to look at the interface table and see which is the default, on windows this would be done with GetAdaptersAddresses, no idea for *nix.\n"} {"question": "Is there a way to find which interface has been used to join an IPv6 multicast group, if the index used was 0 meaning that we leave to the kernel to choose which interface is suitable. \nCan we get that information afterwards?\n", "answer": "Does the IPV6_MULTICAST_IF socket option change after the join is complete? If not you'll have to look at the interface table and see which is the default, on windows this would be done with GetAdaptersAddresses, no idea for *nix.\n"} {"question": "I am new at GTK and started out using Glade to design a UI. But whenever I run my app, I must keep the Glade file in the same directory as the executable. I would like to distribute the Glade file in a compiled form, same as the source code. Is this possible?\n", "answer": "Yes, that's possible. Give a look to theGResourcedocumentation. Its main use is to embed resources like ui files, icons, etc. in the main binary.\n"} {"question": "I am new at GTK and started out using Glade to design a UI. But whenever I run my app, I must keep the Glade file in the same directory as the executable. I would like to distribute the Glade file in a compiled form, same as the source code. Is this possible?\n", "answer": "Yes, that's possible. Give a look to theGResourcedocumentation. Its main use is to embed resources like ui files, icons, etc. in the main binary.\n"} {"question": "I have a file and I want to make a backup file, with the same name as file but with \"aux\" at the end. How do I do this? I tried:\n\n```\nchar *nameFile, *nameAux;\nchar *aux = aux;\nnameAux = nameFile + aux;\n```\n\nWhich didn't work.. nameFile is given to me by the user, and it's right because I can open/ceate the file with nameFile\n", "answer": "You can't just \"add\" C strings. effectively you've summed pointers.\nSeeHow do I concatenate const/literal strings in C?\n"} {"question": "I have a file and I want to make a backup file, with the same name as file but with \"aux\" at the end. How do I do this? I tried:\n\n```\nchar *nameFile, *nameAux;\nchar *aux = aux;\nnameAux = nameFile + aux;\n```\n\nWhich didn't work.. nameFile is given to me by the user, and it's right because I can open/ceate the file with nameFile\n", "answer": "You can't just \"add\" C strings. effectively you've summed pointers.\nSeeHow do I concatenate const/literal strings in C?\n"} {"question": "I am working on an implementation of named pipes client/server for school. I have asked my teacher what happens if i use unlink while either of the pipes end is still opened. He had no answer for me.\n\nAnyone know?\n", "answer": "Nothing in particular happens, except the name is removed from the file system so no future processes can open the same named pipe.\n\nThe processes that has the pipe open will continue as normal.\n"} {"question": "how to get bluetooth address of same device either through command line or program\n", "answer": "Two problems: First is that you never check for errors from any of the system calls.\n\nThe second is that the child process shouldterminatewhich yours doesn't. Instead your child process continues in the loop and callaccepton the listening socket and so on, fighting with the parent process about connections. When the child process is done it should callexitto terminate.\n"} {"question": "I'm imagining readingbyte by bytewould be very inefficient, but reading in bulks would almost always read more than needed, requiring to store the rest of the read input in a global context for all subsequent read operations to find. What am I missing?\n", "answer": "The prototype is:\n\n```\nssize_t getline(char **lineptr, size_t *n, FILE *stream);\n```\n\nSo it's clearly usingFILE, which is already buffered. So reading character-by-character is not inefficient at all.\n"} {"question": "I'm imagining readingbyte by bytewould be very inefficient, but reading in bulks would almost always read more than needed, requiring to store the rest of the read input in a global context for all subsequent read operations to find. What am I missing?\n", "answer": "The prototype is:\n\n```\nssize_t getline(char **lineptr, size_t *n, FILE *stream);\n```\n\nSo it's clearly usingFILE, which is already buffered. So reading character-by-character is not inefficient at all.\n"} {"question": "I'm imagining readingbyte by bytewould be very inefficient, but reading in bulks would almost always read more than needed, requiring to store the rest of the read input in a global context for all subsequent read operations to find. What am I missing?\n", "answer": "The prototype is:\n\n```\nssize_t getline(char **lineptr, size_t *n, FILE *stream);\n```\n\nSo it's clearly usingFILE, which is already buffered. So reading character-by-character is not inefficient at all.\n"} {"question": "I want to know whether threads created usingpthread.hlibrary are using one core, or they are running in multiple cores.\n", "answer": "A newly created thread has no affinity, and will be shuffled around the process as deemed best by the system.\n\nIf you need to pin it to a specific core,this answer provides detailsfor setting affinity to a specific pthread.\n"} {"question": "I've found out where caused SEGSEV, but only happens when that function be called hundreds of thousands times to trigger some rare case, is it possible to set breakpoint there when something is true? either on the gdb command line or c source file\n", "answer": "Try like this:\n\n```\n(gdb) break file.c:15 if some_variable == some_value\n```\n"} {"question": "Let's say here is a char with unknown digit number in C:\n\n```\nchar char_id[1000] = {'1', '2', '3', ..., '8', '9', '\\0'};\n```\n\nIf I want the last two digit to form an integer i.e. '89'.\n\nWhat is the easiest way?\n", "answer": "may be this\n\n```\nchar char_id[1000] = {'1', '2', '3', /*..., */ '8', '9', '\\0'};\nint what_i_want = atoi( char_id + ( strlen(char_id) - 2 ) );\n```\n\nby the way those dots are a bit of rubbish, comment them\n"} {"question": "For example, if I had amakefilethat contains this:\n\n```\ndynArray.o: dynArray.c dynArray.h type.h \n gcc -Wall -ansi -c dynArray.c\n```\n\nHow would I translate that into aCMakeLists.txtfile?\n", "answer": "ProbablyCMake's object librarieswould do that, that mean compile objects but not archive them like normal library would.\n\n```\nadd_library( OBJECT ...)\n```\n"} {"question": "For example, if I had amakefilethat contains this:\n\n```\ndynArray.o: dynArray.c dynArray.h type.h \n gcc -Wall -ansi -c dynArray.c\n```\n\nHow would I translate that into aCMakeLists.txtfile?\n", "answer": "ProbablyCMake's object librarieswould do that, that mean compile objects but not archive them like normal library would.\n\n```\nadd_library( OBJECT ...)\n```\n"} {"question": "For example, if I had amakefilethat contains this:\n\n```\ndynArray.o: dynArray.c dynArray.h type.h \n gcc -Wall -ansi -c dynArray.c\n```\n\nHow would I translate that into aCMakeLists.txtfile?\n", "answer": "ProbablyCMake's object librarieswould do that, that mean compile objects but not archive them like normal library would.\n\n```\nadd_library( OBJECT ...)\n```\n"} {"question": "I have the following code:\n\n```\nstruct coord {\n float x;\n float y;\n};\n\nstruct coord vertices[4];\n```\n\nBut when I do the following, an error occurs:\n\n```\nvoid setVertices(float x, float y) {\n vertices[0] = (struct coord) { x, y };\n}\n```\n\nWhy isn't this allowed in C? Is there another way to do this? Thank you.\n", "answer": "I can initialize structs that way, actually. The IDE just lagged on its error-checking for several minutes, for some reason.\n"} {"question": "When we create temporary files using tmpfile, in most cases we cannot easily predict the name. Coverity scan also complains about its vulnerability.\nSo is there any function to create a temporary file which cannot be guessed easily?\n", "answer": "If you using Linux, thenmkstemp\n\nOr usetmpnam\n"} {"question": "This question already has answers here:In a C function declaration, what does \"...\" as the last parameter do?(7 answers)Closed5 years ago.\n\nI was going through the logger code and came across a function\n\n```\nbool LogMessage(const char *szFor, ...)\n```\n\nWhat does...indicates here?\n", "answer": "This is called anellipsis notation. This means, the function is avariadic function.\n\nIt canlegallyaccept any number and type of incoming arguments.\n"} {"question": "This question already has answers here:In a C function declaration, what does \"...\" as the last parameter do?(7 answers)Closed5 years ago.\n\nI was going through the logger code and came across a function\n\n```\nbool LogMessage(const char *szFor, ...)\n```\n\nWhat does...indicates here?\n", "answer": "This is called anellipsis notation. This means, the function is avariadic function.\n\nIt canlegallyaccept any number and type of incoming arguments.\n"} {"question": "I'm trying to input data from filesample.txtinto my c program on netbeans. How can I do that from command line? I know I should go toFile -> Project Properties -> Run -> Run Command.But what would I enter for Run Command?\n", "answer": "If you have set theOUTPUT_PATHproperly it will be\"${OUTPUT_PATH}\" \"ARG\"\n"} {"question": "I'm trying to input data from filesample.txtinto my c program on netbeans. How can I do that from command line? I know I should go toFile -> Project Properties -> Run -> Run Command.But what would I enter for Run Command?\n", "answer": "If you have set theOUTPUT_PATHproperly it will be\"${OUTPUT_PATH}\" \"ARG\"\n"} {"question": "I'm trying to input data from filesample.txtinto my c program on netbeans. How can I do that from command line? I know I should go toFile -> Project Properties -> Run -> Run Command.But what would I enter for Run Command?\n", "answer": "If you have set theOUTPUT_PATHproperly it will be\"${OUTPUT_PATH}\" \"ARG\"\n"} {"question": "This question already has answers here:What should main() return in C and C++?(19 answers)Closed5 years ago.\n\nWhat will happen if we don't use it? will the compiler automatically add it like it does in C++?\n", "answer": "It will return0automatically in C99-compliant compilers (and later). In pre-C99 compilers the return value is undefined in such cases.\n\nIn other words, inmodernC you don't need an explicitreturn 0at the end ofmain.\n"} {"question": "Given achar *str = \"something %s something2 %d\", how can I format it and produce a new string without printing out? I know of \"printf\" which prints out a result, but I don't need a result to be printed out.\n", "answer": "The answer issprintf: it's exactlyprintfto a buffer.\n"} {"question": "I'm trying to learn RDMA.\n\nMy question is, when doingibv_post_send, I should get a completion event on a completion queue. But how does theibv_post_sendknow to which completion queue? From what I see here, I could have createdmany.\n", "answer": "Turns outwhen initiating a QP, it can be assigned to a send CQ and recv CQ in its init attributes.\n"} {"question": "A runtime I'ld like to to know if an stack defined struct sockaddr_storage was assigned to any IP address (IPv4 or IPv6)\n\nAny idea?\n", "answer": "Check thess_familyfield. It will beAF_INETfor an IPv4 address, orAF_INET6for an IPv6 address. You can then type-cast thesockaddr_storageaccordingly to eithersockaddr_inorsockaddr_in6in order to access thesockaddr_in::sin_addrorsockaddr_in6::sin6_addrfield, respectively, to make sure it is not set to zeros.\n"} {"question": "I want to open terminal and cat a file (show its content) using c;\ni got error from code below:\n\n```\nchar * com = \"xterm cat /home/user/Desktop/file.c\";\nsystem(com);\n```\n\nor even:\n\n```\nchar * com = \"/usr/bin/xterm /bin/cat /home/user/Desktop/file.c\";\nsystem(com);\n```\n\nthanks for any help;\n", "answer": "You could change your command to:\n\n```\nxterm -e less file.c\n```\n"} {"question": "I want to open terminal and cat a file (show its content) using c;\ni got error from code below:\n\n```\nchar * com = \"xterm cat /home/user/Desktop/file.c\";\nsystem(com);\n```\n\nor even:\n\n```\nchar * com = \"/usr/bin/xterm /bin/cat /home/user/Desktop/file.c\";\nsystem(com);\n```\n\nthanks for any help;\n", "answer": "You could change your command to:\n\n```\nxterm -e less file.c\n```\n"} {"question": "i have array of strings.\n\n```\nchar strings[][30]={\"word1\",\"word2\",......,\"\"};\n```\n\nIterated over them but at the end i got messageSegmentation fault (core dumped)\n\nTried with following code :\n\n```\nfor(int i=0;strings[i] != \"\";i++){printing items...}\n```\n\nI think the problem is with!= \"\"but why isn't it working?\n", "answer": "Usestrcmpto compare strings in C.==or!=doesn't work for strings in C.\n"} {"question": "Is this possible? I need to make a 2d array and each element is supposed to have an int array of size 2.\n\nSo if I make a 10x10 array I need each index to have a [x, y] where x and y are ints.\n", "answer": "```\nint array[10][10][2];\n```\n\nHere you have a 3D array. Where the 2D array : array[..][..] has 2 elements inside it.\n\nOr you can use structure.\n\n```\nstruct number {\n int x;\n int y;\n};\n```\n\nthen :\n\n```\nstruct number array[10][10];\n```\n"} {"question": "Does anyone know how to enable the use of OpenMP in Xcode 9.0?\n\nIn Xcode 8, I procide as described inthis tutorialbut it doesn't work anymore in Xcode 9.0 ...\n\nThe error is :clang-5.0: error: cannot specify -o when generating multiple output files\n\nThanks in advance for help\n", "answer": "I think the problem is in flag -index-store-path\nIn build settings > build options set Enable Index-While-Building Functionality to No\n"} {"question": "I'm new embedded electronics and am learning via online tutorials. I built and downloaded a code (with the uVision IDE) which made the blue and orange LEDs flash. I want these LEDs to stop flashing, and I want the MCU to go back to the state it was at before I downloaded the code. How would I do that?\n", "answer": "How to return:\n\nWrite FLASH mass erase functionCopy mass flash erase function to the RAM.Jump to itDo the software reset\n"} {"question": "I installed the MJPG-Streamer and i want to run this from a C program.\nI start the MJPG-Streamer entering the following code in the pi terminal:\n\n```\nLD_LIBRARY_PATH=/usr/local/lib mjpg_streamer -i \"input_file.so -f /tmp/stream -n pic.jpg\" -o \"output_http.so -w /usr/local/www\"\n```\n\nI want to run mjpg streamer from a C program, how do I do this?\n\nThanks!\n", "answer": "You can usesystem()function inside stdlib header.\n"} {"question": "This question already has answers here:What happens when I use the wrong format specifier?(2 answers)Closed5 years ago.\n\ni have used the code.\n\n```\nchar *y;\ny=\"hello world\";\nprintf(\"%c\",y);\n```\n\nit just shows something useless.\nWhat mistake i am making.\n", "answer": "Change :\n\n```\nprintf(\"%c\",y);\n```\n\nto :\n\n```\nprintf(\"%s\",y);\n```\n\nas%cspecifier indicates achar. To identify a string, you need the specifier%s.\n"} {"question": "```\n#include \n\nint a = printf(\"cs136/n\");\n\nint main(){\n printf(\"%d\\n\", a);\n}\n```\n\nError: (initializer element is not a compile-time constant)\n", "answer": "You can't use printf outside of an function. Move the line \"int a = printf...\" inside main.\n\nYou variable \"a\" is an global variable. You can only initialize \"a\" with an constant. For example:\n\n```\nint a = 42;\n\nint main()\n{\n a = printf(...\n```\n"} {"question": "I saw the following line of codeherein C.\n\n```\nint mask = ~0;\n```\n\nI have printed the value ofmaskin C and C++. It always prints-1.\n\nSo I do have some questions:\n\nWhy assigning value~0to themaskvariable?What is the purpose of~0?Can we use-1instead of~0?\n", "answer": "It's a portable way to set all the binary bits in an integer to 1 bits without having to know how many bits are in the integer on the current architecture.\n"} {"question": "I saw the following line of codeherein C.\n\n```\nint mask = ~0;\n```\n\nI have printed the value ofmaskin C and C++. It always prints-1.\n\nSo I do have some questions:\n\nWhy assigning value~0to themaskvariable?What is the purpose of~0?Can we use-1instead of~0?\n", "answer": "It's a portable way to set all the binary bits in an integer to 1 bits without having to know how many bits are in the integer on the current architecture.\n"} {"question": "Is there a way to get the static address of a function pointed byllvm::Functionobject in a C code using the LLVM IR API?\n", "answer": "Sincellvm::Function*is a subclass ofllvm::Value*you can just treat as anllvm::Value*and LLVM will substitute the correct address.\n\nllvm::Function Documentation\n"} {"question": "I need to print.5as0.5using theprintfstatement in C language.\nIt can be done easily using the following code.\n\n```\nprintf(\"%03f\", myfloatvalue);\n```\n\nBut the situation ismyfloatvalueis dynamic. So i am not sure whether it is a 3 character number, it could be.5or.56or.567. In the above cases i need to print as0.5,0.56, and0.567.\n", "answer": "%gdoes print the shortest possible representation of a float.\n\n```\nprintf(\"%g\",myfloatvalue);\n```\n"} {"question": "Is there a way to get the static address of a function pointed byllvm::Functionobject in a C code using the LLVM IR API?\n", "answer": "Sincellvm::Function*is a subclass ofllvm::Value*you can just treat as anllvm::Value*and LLVM will substitute the correct address.\n\nllvm::Function Documentation\n"} {"question": "Is this statement correct in C-language?\n\n```\na && b && c\n```\n\nI want to check((a==2) && (b==3) && (c==4)).Is this usage of logicalANDcorrect?\n", "answer": "Yes, the usage is correct. You can AND as many expressions as you want.\n"} {"question": "Is this statement correct in C-language?\n\n```\na && b && c\n```\n\nI want to check((a==2) && (b==3) && (c==4)).Is this usage of logicalANDcorrect?\n", "answer": "Yes, the usage is correct. You can AND as many expressions as you want.\n"} {"question": "In my driver module data is coming in callback function. \nI want to add data to read callback but not able to find read callback in tty structure\n", "answer": "There is no read callback. The tty core buffers the data received by the tty drivers in a structure called struct tty_flip_buffer. ReadChapter 18of LDD3\n"} {"question": "I'm new to Linux and C and when trying to run a basic \"Hello World\" script, i kept getting the same two errors. I have confirmed that everything in the program is correct.errors gotten when trying to compile code\n", "answer": "You are running thegcccommand from the home directory (~) when thehello.cfile is in~/Documents.\n\nEither navigate toDocumentsusingcdbefore runninggccor placehello.cin the home directory.\n"} {"question": "In my driver module data is coming in callback function. \nI want to add data to read callback but not able to find read callback in tty structure\n", "answer": "There is no read callback. The tty core buffers the data received by the tty drivers in a structure called struct tty_flip_buffer. ReadChapter 18of LDD3\n"} {"question": "I'm new to Linux and C and when trying to run a basic \"Hello World\" script, i kept getting the same two errors. I have confirmed that everything in the program is correct.errors gotten when trying to compile code\n", "answer": "You are running thegcccommand from the home directory (~) when thehello.cfile is in~/Documents.\n\nEither navigate toDocumentsusingcdbefore runninggccor placehello.cin the home directory.\n"} {"question": "This question already has answers here:hello world in C without semicolons and without IF/WHILE/FOR statements [closed](7 answers)Closed6 years ago.\n\nI want to display hello world message in c without using semicolon. how can I do that?\nIs it possible?\n", "answer": "Yes, It is possible.\n\n```\n#include\nint main(){\n if(printf(\"hello world\")){}\n}\n```\n"} {"question": "I am new in the IDE Code::Blocks, and I accidentally inserted this mark in every line of the code (CR LF), and I want to remove, I'm sure to be a pretty simple thing to fix but I found nothing in the Settings. By the way, what does it mean?\n\n\n", "answer": "There is a checkbox in Menue\n\n\"Settings\"\"Editor...\"General SettingsEditor SettingsEnd of Line options\"show end of line chars\"\n"} {"question": "I am new in the IDE Code::Blocks, and I accidentally inserted this mark in every line of the code (CR LF), and I want to remove, I'm sure to be a pretty simple thing to fix but I found nothing in the Settings. By the way, what does it mean?\n\n\n", "answer": "There is a checkbox in Menue\n\n\"Settings\"\"Editor...\"General SettingsEditor SettingsEnd of Line options\"show end of line chars\"\n"} {"question": "I have a NodeJS server running on the same server with a C program. I need to sent a byte array from my NodeJS server to my C program. I have a set_title function in C.\n\n```\nset_title(uint16_t *title)\n```\n\nAny idea how can I do this ?\n", "answer": "You need some form of interprocess communication to be able to do that.\n\nThere are libraries out there which can facilitate that work for you, have a look atnanomsgandzmqwhich both have both C and JS bindings.\n"} {"question": "What's the best way to allocate an array on the stack that will be used by several helper functions/macros. Is there anyway to avoid passing pointers around?\n", "answer": "No, there is not. You will have to use pointers.\n"} {"question": "I have a NodeJS server running on the same server with a C program. I need to sent a byte array from my NodeJS server to my C program. I have a set_title function in C.\n\n```\nset_title(uint16_t *title)\n```\n\nAny idea how can I do this ?\n", "answer": "You need some form of interprocess communication to be able to do that.\n\nThere are libraries out there which can facilitate that work for you, have a look atnanomsgandzmqwhich both have both C and JS bindings.\n"} {"question": "What's the best way to allocate an array on the stack that will be used by several helper functions/macros. Is there anyway to avoid passing pointers around?\n", "answer": "No, there is not. You will have to use pointers.\n"} {"question": "If I have a functiondostuff_1and another function,dostuff_2and N other functionsdostuff_N, is there a way I can make a macro like#define DOSTUFF(X) ...so thatDOSTUFF(5)gives medostuff_5?\n", "answer": "Use this:\n\n#define DOSTUFF(X) dostuff_##X()\n\nThe preprocessor willreplaceevery existence ofDOSTUFF(X)in your code todostuff_x().\n\nOn the other hand, consider renaming your methods to something meaningful.\n"} {"question": "How would you simplify the following if-else-if ladder such that the function call is made only once?\n\n```\nif (Condition A){\n A();\n}\nelse {\n if (Condition B) {\n A();\n }\n}\n```\n", "answer": "Change it to:\n\n```\nif ((Condition A) || (Condition B)) {\n A();\n}\n```\n\nAs you want the functionA()to run ifCondition Aistrueor ifCondition Bistrue, you can use the||(OR) operator. This returnstrueif either conditions aretrue.\n"} {"question": "If I have a functiondostuff_1and another function,dostuff_2and N other functionsdostuff_N, is there a way I can make a macro like#define DOSTUFF(X) ...so thatDOSTUFF(5)gives medostuff_5?\n", "answer": "Use this:\n\n#define DOSTUFF(X) dostuff_##X()\n\nThe preprocessor willreplaceevery existence ofDOSTUFF(X)in your code todostuff_x().\n\nOn the other hand, consider renaming your methods to something meaningful.\n"} {"question": "I have only a compiled binary code (.hex) of pic microcontroller,how can i convert it to code line in mikroc in order to see the instruction of program?\n", "answer": "When it's compiled, it ismachine codeand there's no (automatic) way of translating machine code to C. Youcanget a readable version of the code,assembly, using adisassemblerfor your target CPU. This of course requires you learning your CPU's assembly language.\n"} {"question": "I have a string\"2017-07-30_00:00:00\"I want to convert this string into milliseconds in C/Android NDK. But did not find any function to do so. Some example which is in C++boost::and any other libs which don't work in Android NDK. So if there is any way to do this in C/C++ that can be run in Android NKD, it will be helpful.\n", "answer": "strptime()is suported by bionic (i.e. available in NDK).\n"} {"question": "I have a string\"2017-07-30_00:00:00\"I want to convert this string into milliseconds in C/Android NDK. But did not find any function to do so. Some example which is in C++boost::and any other libs which don't work in Android NDK. So if there is any way to do this in C/C++ that can be run in Android NKD, it will be helpful.\n", "answer": "strptime()is suported by bionic (i.e. available in NDK).\n"} {"question": "I want my program to convert characters into integers, but not into their ASCII equivalents.\nFor example,'A'should equal 0, not 65, while'B'should equal 1.\nThen I want to add that number to an ASCII character and convert that value back to achar.\n", "answer": "```\nchar test = 'C';\nint num = test - 'A';\n// result: 2 with ASCII and any other encoding\n// having the uppercase letters in sequence\n```\n"} {"question": "what is the true path to prevent codeblocks error.\n\nI know question very short but when I selected any path I am getting error\n", "answer": "1-Create New console C project\n\n2-Right Click your project and click properties in the context menu\n\n3-go to the libraries page\n\n4-click 'Avaliable in pkg-config' in the known libraries layout\n\n5-and make it like the following picture\n"} {"question": "I need convert unsigned char array into unit8_t array maybe someone has an idea how to do it?\n\nI tried to look for information on the Internet, but unfortunately I did not succeed.\n\n:)\n", "answer": "So, have you trieduint8_t* myuint8array = (uint8_t*)myuchararray;?\n"} {"question": "I am creating an apache module using eclipse c/c++ on eclipse but I am getting this errorType 'apr_pool_t' could not be resolved Eclipse C/C++I included/usr/include/apacheand/usr/libwhere is the structureapr_pool_t?\n", "answer": "I solved by myself. It is as simple as include /usr/include/apr-1.0 in right click on my project properties->C/C++General->Paths & Symbols.\n"} {"question": "I need convert unsigned char array into unit8_t array maybe someone has an idea how to do it?\n\nI tried to look for information on the Internet, but unfortunately I did not succeed.\n\n:)\n", "answer": "So, have you trieduint8_t* myuint8array = (uint8_t*)myuchararray;?\n"} {"question": "I'm trying to compile android-kernel-goldfish-2-6-29 but when i use make -j2 to compile it, i get this error:\n\ninclude/linux/compiler-gcc.h:86:30: fatal error: linux/compiler-gcc6.h: No \n such file or directory\n #include gcc_header(__GNUC__)\n\nmy ubuntu is 17.04 and i downgrade my gcc to\n\ngcc version 4.7.4 (Ubuntu/Linaro 4.7.4-3ubuntu12)\n\ncan any body fix the problem?\n", "answer": "I changed the goldfish version from 2.6.29 to 3.18 and now everything is okay.\n"} {"question": "I'm unable to understand below this line , could somebody tell me what it does ?\n\n```\nfscanf(file_pointer, \"%*[^\\n]\");\n```\n", "answer": "From thedocsone might see, that:\n\n*- assignment-suppressing character which is used not to assign the value being read to any receiveing argument offscanf.\n\n[^\\n]- conversion specifier which matches any symbol except (^) new line (\\n).\n\nAs a result, thisfscanfreads all symbols until new line is met.\n"} {"question": "i'm a new devopler in CUDA 8 and compiling my codes with nvcc\nhow can i install conio.h into my compiler \nby the way i'm running my code on server at a company\nthanks\n", "answer": "The short answer: you can't.\nCUDA is based on C, but is a different language and a different compiler. And conio.h is not even part of C standard.\nYou ca however use printf from a Cuda kernel\n"} {"question": "I have the text file with 2000 lines and each line contains up to 256 characters.\n\nI need to detect EOF as I'm reading the file.\n\nShould the code process a line as it is read or should it read the lines into an array and then process the array one element at a time?\n", "answer": "If the data don't change in your file, you should stock the data in an array.\n\nIn the other case, you have to read your file each time you need to check a line.\n"} {"question": "Thedocumentationsays thatMK_RBUTTON, and notMK_SHIFT, indicates the Shift key state.\n\nIs this correct or is this a typo? It differs fromthe behavior inWM_LBUTTONUP.\n", "answer": "Yeah, it's a typo. Spy++ showsMK_SHIFTand notMK_RBUTTON.\n"} {"question": "Thedocumentationsays thatMK_RBUTTON, and notMK_SHIFT, indicates the Shift key state.\n\nIs this correct or is this a typo? It differs fromthe behavior inWM_LBUTTONUP.\n", "answer": "Yeah, it's a typo. Spy++ showsMK_SHIFTand notMK_RBUTTON.\n"} {"question": "```\nchar* p = init();\np = foo(p); /* this one */\n```\n\nthe functionfooprototype:\n\n```\nchar* foo(char* p);\n```\n\nIs it permissible to callfoothat way, or does it fall in theUndefined Behaviorcategory?\n", "answer": "Yes, this is well-defined - there is a sequence point between the evaluation of the function arguments and the function call.\n"} {"question": "```\nchar* p = init();\np = foo(p); /* this one */\n```\n\nthe functionfooprototype:\n\n```\nchar* foo(char* p);\n```\n\nIs it permissible to callfoothat way, or does it fall in theUndefined Behaviorcategory?\n", "answer": "Yes, this is well-defined - there is a sequence point between the evaluation of the function arguments and the function call.\n"} {"question": "How to detect if cable is unplugged on W5100 Ethernet controller?.\n\nIndatasheetI can't find register for cable detection. But chip provides LAN status LED.\n", "answer": "W5100does not support reading register to get status if cable is plugged or not (network available or not). You can only check by doingfake connectionand wait for either any response or timeout.\n\nInstead, you should useW5200which has this feature.\n"} {"question": "I am getting the following compilation error:\n\nprog.c:13:5: error: called object is not a function or function pointer\n a=250(n-1)+192;\n\n```\n#include \n\nint main(){\n long long n,a;\n int t;\n\n scanf(\"%d\",&t);\n while(t--){\n scanf(\"%lld\",&n);\n a=250(n-1)+192;\n printf(\"%lld\\n\",a);\n }\n}\n```\n", "answer": "In C, you always have to write a*character for multiplication, as this:\n\n```\na=250*(n-1)+192;\n```\n"} {"question": "I am getting the following compilation error:\n\nprog.c:13:5: error: called object is not a function or function pointer\n a=250(n-1)+192;\n\n```\n#include \n\nint main(){\n long long n,a;\n int t;\n\n scanf(\"%d\",&t);\n while(t--){\n scanf(\"%lld\",&n);\n a=250(n-1)+192;\n printf(\"%lld\\n\",a);\n }\n}\n```\n", "answer": "In C, you always have to write a*character for multiplication, as this:\n\n```\na=250*(n-1)+192;\n```\n"} {"question": "In Allegro, I can set the Window to be resizeable by running\n\n```\nal_set_new_display_flags(ALLEGRO_RESIZABLE);\n```\n\nbefore\n\n```\ndisplay = al_create_display(800, 600);\n```\n\nhowever, if I resize the window, how will I know how big the window is that I resize?\n", "answer": "useal_get_window_constraints(ALLEGRO_DISPLAY *display,\n int *min_w, int *min_h, int *max_w, int *max_h).\n\nSource\n"} {"question": "I have a message encoded with Nanopb implementation of Google Protocol Buffers.\n\nI have to decode it to display the decoded result on a php page.\n\nIs it possible to do it with PHP ?\nIf not, what is the best solution to do it in order to get an exploitable result in php ?\n\nThanks for your help.\n", "answer": "Use php implementation of google protocol buffers like for instance:\n\ngoogle/protobuf/php\n\nprotobuf-php\n"} {"question": "I have a message encoded with Nanopb implementation of Google Protocol Buffers.\n\nI have to decode it to display the decoded result on a php page.\n\nIs it possible to do it with PHP ?\nIf not, what is the best solution to do it in order to get an exploitable result in php ?\n\nThanks for your help.\n", "answer": "Use php implementation of google protocol buffers like for instance:\n\ngoogle/protobuf/php\n\nprotobuf-php\n"} {"question": "I am running my C program and I want to see the memory used by this. I am using the profilergprof. Is it possible withgprof? Or maybe I have to study theValgrindprofile?\n", "answer": "If you want to go down the Valgrind route, Massif is the tool to use:\n\nvalgrind --tool=massif your_app -your_options\n"} {"question": "This the short code, that produces adouble free or corruptionerror.\n\n```\nSDL_Surface *surface;\nSDL_Surface *surface2;\nsurface = NULL;\nsurface2 = SDL_LoadBMP(\"someImg.bmp\");\nsurface = surface2;\nSDL_FreeSurface(surface);\nSDL_FreeSurface(surface2);\n```\n\nI don't understand, why I can't free second surface before I free first.\n", "answer": "Both variablessurfaceandsurface2point to the same object. You are effectively freeing twice the same object.\n"} {"question": "I just started my C programming class today and I am having a problem with the output on my terminal which the C doesn't print on it's own line.\n\n```\n#include \n\n int main(){\n\n printf(\"Hello World\");\n\n return 0;\n```\n\n}\n\n\n", "answer": "Use a newline character, represented as'\\n'. The slash is an escape character for a few special characters, such as tab'\\t', and carriage return'\\r'.\n\nprintf(\"Hello World\\n\");\n"} {"question": "I just started my C programming class today and I am having a problem with the output on my terminal which the C doesn't print on it's own line.\n\n```\n#include \n\n int main(){\n\n printf(\"Hello World\");\n\n return 0;\n```\n\n}\n\n\n", "answer": "Use a newline character, represented as'\\n'. The slash is an escape character for a few special characters, such as tab'\\t', and carriage return'\\r'.\n\nprintf(\"Hello World\\n\");\n"} {"question": "This question already has answers here:What is the full \"for\" loop syntax in C?(7 answers)Closed6 years ago.\n\nMy question is simple,thus I will not go in deep\n\ncan we usefor()loop without condition like this\n\n```\nfor(;;space+=1)\n{\nprintf(\" \");\nbreak;\n}\n```\n", "answer": "Of course you can. An empty condition is taken to evaluate to1.\n\nfor (;;){/*ToDo - your code here*/}is idiomatic C.\n"} {"question": "If I use uninitialized global variable in C program, What happens? Is it undefined behavior?\n\n```\n#include \n\nint i;\n\nint main() \n{\n while(i < 5)\n {\n i++;\n }\n printf(\"%d\\n\", i);\n return 0;\n}\n```\n", "answer": "Is it undefined behavior?\n\nNo.\n\nWhat happens?\n\nihas static storage duration (file scope). It will initialize to zero by default.\n"} {"question": "This is what I'm trying to do:-\n\n```\ndouble x = 4.0\n double y = 4.0\n x+y = 8.0\n```\n\nThe input has to be of double type only (given condition of the problem).\n", "answer": "```\nprintf(\"%.1lf\", yournumber);\n```\n\nwill do the trick. This will print value to1decimal place. In case number is1.123, printed number will be rounded, in this case to1.1.\n"} {"question": "Is there any way to store mobile numbers with starting '0' and having 8 or 9 in c without getting the error invalid 8 or 9 in octal constant?\n", "answer": "If you're not planning on doing math on a \"number\", then use a char array, not an int. Just because something looks like an integer doesn't mean your program should treat it as one.\n"} {"question": "Is there any way to store mobile numbers with starting '0' and having 8 or 9 in c without getting the error invalid 8 or 9 in octal constant?\n", "answer": "If you're not planning on doing math on a \"number\", then use a char array, not an int. Just because something looks like an integer doesn't mean your program should treat it as one.\n"} {"question": "What isSuper Loopin Embedded C programming language?\n", "answer": "This refers to the eternal loop usually located inmain()of a \"bare metal\" system (no OS), since such systems can never return from main. A typical bare metal embedded system looks like this:\n\n```\nvoid main (void)\n{\n // various initializations\n\n for(;;) // \"super loop\" or \"main loop\"\n {\n // do stuff\n }\n}\n```\n"} {"question": "I am using struct module for serializing the data to send the data over socket. I observed thatstruct.pack(frmt, value1, ...)returns a string of the value 1 intwo byteshexadecimal format. Why does it returnonly in two bytes format? There should be some reason. Maybe I am missing something while understanding struct class.\n\nThanks in advance.\n", "answer": "Read the documentation of thepython struct module\n\nIf you concern about the size of the packed result readthis\n"} {"question": "In GCC the following C code compiles correctly-\n\n```\nint i = 7;\ni = 5i;\nprintf(\"%d\", i);\n```\n\nAnd prints-0.\n\nThe statementi = 5iclearly makes no sense. Then why on earth the code does not give any compilation error? And whyibecomes0?\n", "answer": "This is aGCC extension for representing the imaginary component of complex numbers.\n\nThe compiler complains if you compile with-pedanticand-Werror:http://ideone.com/PMlZr5.\n"} {"question": "In GCC the following C code compiles correctly-\n\n```\nint i = 7;\ni = 5i;\nprintf(\"%d\", i);\n```\n\nAnd prints-0.\n\nThe statementi = 5iclearly makes no sense. Then why on earth the code does not give any compilation error? And whyibecomes0?\n", "answer": "This is aGCC extension for representing the imaginary component of complex numbers.\n\nThe compiler complains if you compile with-pedanticand-Werror:http://ideone.com/PMlZr5.\n"} {"question": "I want to know number of tokens in the statement given below\n\n```\na+++b---c\n```\n\nPlease tell me number of tokens\nI told my viva teacher that there are 7 tokens but he said it is wrong.\n", "answer": "You are correct. There are seven tokens: (in C)\n\n```\na\n++\n+\nb\n--\n-\nc\n```\n"} {"question": "Is there some tutorial available for Bullseye code coverage tool. Is it automated? How do we find line coverage using this tool?\n", "answer": "Function coverage and decision coverage are supported in Bullseye coverage tool.I dont think line coverage/statement coverage is supported. Please see this link.\n\nhttp://www.bullseye.com/measurementTechnique.html\n"} {"question": "Confused, Why does this work when I compile, when hold is an integer?\n\n```\nchar value = 'p';\nint hold = value;\nprintf(\"%c\", hold);\n```\n", "answer": "First, in\n\n```\nint hold = value;\n```\n\nis performed implicit conversion fromchartoint.\n\nSecond, in\n\n```\nprintf(\"%c\", hold);\n```\n\nthe%cspecifier means something asconvert it tocharand print it as symbol.\n"} {"question": "Confused, Why does this work when I compile, when hold is an integer?\n\n```\nchar value = 'p';\nint hold = value;\nprintf(\"%c\", hold);\n```\n", "answer": "First, in\n\n```\nint hold = value;\n```\n\nis performed implicit conversion fromchartoint.\n\nSecond, in\n\n```\nprintf(\"%c\", hold);\n```\n\nthe%cspecifier means something asconvert it tocharand print it as symbol.\n"} {"question": "Confused, Why does this work when I compile, when hold is an integer?\n\n```\nchar value = 'p';\nint hold = value;\nprintf(\"%c\", hold);\n```\n", "answer": "First, in\n\n```\nint hold = value;\n```\n\nis performed implicit conversion fromchartoint.\n\nSecond, in\n\n```\nprintf(\"%c\", hold);\n```\n\nthe%cspecifier means something asconvert it tocharand print it as symbol.\n"} {"question": "I want to detect the last element of an array of integer in C code.\nOtherwise i need to stop handling array data when the array element is empty.\nreally my array have a maximum size fixed and it was filled from an external file so i dont know when it stop filling the array.\n", "answer": "Last element is in position\n\n```\nsizeof(array)/sizeof(array[0]) - 1\n```\n"} {"question": "I want to write in Makefile like this\n\n```\nfoo: foo.c\n $(CC) -o foo -Wall foo.c\n```\n\nbut I'm not sure if allccimplementations support-Wall.\n", "answer": "No, there is no standard regarding the command-line interface of C compilers.\n\nThe Microsoft compiler (in Windows) for instance does not accept options starting with-at all, since that's not the syntax typically used with Windows programs.\n"} {"question": "I know how to use the two functions, but I do not know what the suffix \"at\" means. Does it represent the abbreviation of \"another\"?\n", "answer": "At means that the working directory considered for the open call is at the given file descriptor, passed as the parameter. The *at() family of functions are useful so that all path relative operations refer to the same file inode, even if it changes name or someone replaces it.\n"} {"question": "I know how to use the two functions, but I do not know what the suffix \"at\" means. Does it represent the abbreviation of \"another\"?\n", "answer": "At means that the working directory considered for the open call is at the given file descriptor, passed as the parameter. The *at() family of functions are useful so that all path relative operations refer to the same file inode, even if it changes name or someone replaces it.\n"} {"question": "```\n#include \n\nint main(void) {\n\n int i;\n i = 10;\n i*= 10+2;\n printf(\"%d\",i);\n return 0;\n}\n```\n\nwhy is the output of the following code 120 and not 102?\n", "answer": "Because the order of precedence makes '+' higher than *=, so the 10+2 will occur befor the i *=.\n\nC reference for ordering athttp://en.cppreference.com/w/c/language/operator_precedence\n"} {"question": "```\n#include \n\nint main(void) {\n\n int i;\n i = 10;\n i*= 10+2;\n printf(\"%d\",i);\n return 0;\n}\n```\n\nwhy is the output of the following code 120 and not 102?\n", "answer": "Because the order of precedence makes '+' higher than *=, so the 10+2 will occur befor the i *=.\n\nC reference for ordering athttp://en.cppreference.com/w/c/language/operator_precedence\n"} {"question": "If you're going to define these at all, why not define them as\n\n```\n#define SIZEOF_INT sizeof(int)\n```\n\netc. so they are correct even if someone tries to use them to compile against a different architecture?\n", "answer": "I found the answer a minute after asking the question. These macros are sometimes used in the predicates of #if etc. where sizeof calls cannot be evaluated.\n\nFor example\n\n```\n#if SIZEOF_LONG_LONG_INT == 8\nstuff\n#endif\n```\n"} {"question": "Is there any way in MPI to get the total number of bytes transferred by my entire MPI program in C?\n", "answer": "The best way is to use a MPI profiling tool such as the simplempiP. There are more sophisticated / heavyweight tools that can also do that, such as Score-P. You should check if there is something available if you are running your code on an HPC site.\n"} {"question": "What is the optimal code for the following block:\n\n```\nif (a != b)\n a = b\n```\n", "answer": "You can just do\n\n```\na = b;\n```\n\nbecause this way only one assignment will be run every time instead of the possibility of a condition check and an assignment.\n"} {"question": "If i create a pointer like:\n\n```\nint *pointer;\n```\n\nis also a variable (called pointer) created in the C Language? Why/why not?\n", "answer": "Let's get the terminology straight:\n\nint *pointerdeclares a variableVariables have a name and a typeThe name of the variable ispointerThe type of the variable is \"pointer toint\"\n"} {"question": "i have a project where in the user can be the client or server. if he use the program first, he will serve as the server then the other one will be the client and vice versa. is there a possible way to do this ?\n", "answer": "Maybe not the best way, but you can try to bind a server socket to some port and assume that if you can, then you are the server. otherwise, you are the client.\n"} {"question": "i have a project where in the user can be the client or server. if he use the program first, he will serve as the server then the other one will be the client and vice versa. is there a possible way to do this ?\n", "answer": "Maybe not the best way, but you can try to bind a server socket to some port and assume that if you can, then you are the server. otherwise, you are the client.\n"} {"question": "This question already has answers here:dos.h for Linux?(3 answers)Closed6 years ago.\n\nI got this message when I compiled a C program\n\n\"fatal error: dos.h: No such file or directory\ncompilation terminated.\"\n\nI am currently using Ubuntu 16.04\n", "answer": "I believe you can't do that, because from the sound of it, \"dos.h\" is specific to MS-DOS.\n"} {"question": "This question already has answers here:dos.h for Linux?(3 answers)Closed6 years ago.\n\nI got this message when I compiled a C program\n\n\"fatal error: dos.h: No such file or directory\ncompilation terminated.\"\n\nI am currently using Ubuntu 16.04\n", "answer": "I believe you can't do that, because from the sound of it, \"dos.h\" is specific to MS-DOS.\n"} {"question": "I'm looking at a program that was written in C and I need to write it in C#.\n\nWhat is the C# equivalent of this whole line?:\n\n```\nprintf(\"%s\", \" \");\n```\n", "answer": "If you can use C# 6, you could use string interpolation, and go like this.\n\n```\nConsole.WriteLine($\"{variableName} text\");\n```\n"} {"question": "This question already has answers here:Escape character in C(6 answers)Closed6 years ago.\n\nI need to check into a loop if the user inserts '\\' for exiting from the menu.\n\n```\nwhile(choise != '\\'){\n // do stuff\n}\n```\n\nBut I get this error:\n\nerror: missing terminating ' character\n", "answer": "Backslashes are special characters and need to be escaped with another backslash:\n\n```\nwhile (choice != '\\\\') {\n```\n"} {"question": "I'd like to store the variable(two spaces) in C.\n\nIt looks like there are no string data types in C, so how can I store such a value without having to create astring s = get_stringfunction?\n", "answer": "Strings in C programming are built as arrays of chars.\n\nIn your case:char c[] = \" \";\n"} {"question": "When we are writingprintf()in C, are we declaring it or defining?\nIf it is a definition then where is the declaration and vice versa?\n", "answer": "When we are writingprintf()in C, we are making a call toprintf,\nwhich has adeclarationin theheader like thisint printf(const char *format, ...);, and we should include that header in the C program.\n\nThedefinitionofprintfis in the standard library implementation that\ngets linked with the application code.\n"} {"question": "When we are writingprintf()in C, are we declaring it or defining?\nIf it is a definition then where is the declaration and vice versa?\n", "answer": "When we are writingprintf()in C, we are making a call toprintf,\nwhich has adeclarationin theheader like thisint printf(const char *format, ...);, and we should include that header in the C program.\n\nThedefinitionofprintfis in the standard library implementation that\ngets linked with the application code.\n"} {"question": "I am getting stuck because of this error and can't test my application.\n\n\n", "answer": "You only can specific value indimentag. So, please give them aspordpvalue instead of name.\n\nHope this helped.\n"} {"question": "Will this work? \nI expect\n\n```\nfoo(myArraypointer + 10);\n```\n\nbe the same as\n\n```\nfoo( &(myArraypointer[10]));\n```\n\nwill this be treated as same for most compilers? Is this considered good or bad practice and why? What could go wrong?\n", "answer": "For any pointer or arrayaand indexi, the expressiona[i]is equal to*(a + i). That means that&a[i]is equal to&*(a + i), where the last can be shortened toa + i.\n"} {"question": "Will this work? \nI expect\n\n```\nfoo(myArraypointer + 10);\n```\n\nbe the same as\n\n```\nfoo( &(myArraypointer[10]));\n```\n\nwill this be treated as same for most compilers? Is this considered good or bad practice and why? What could go wrong?\n", "answer": "For any pointer or arrayaand indexi, the expressiona[i]is equal to*(a + i). That means that&a[i]is equal to&*(a + i), where the last can be shortened toa + i.\n"} {"question": "I have a function which splits a string into tokens and stores it in an array. How to determine the size of an array of strings of typechar**?\n\n```\nie: char **input;\n```\n", "answer": "Keep a variable globally and increment that variable value in the function which is splitting the string into tokens & storing into array.\n"} {"question": "How can one increase the maximum size of a stack for C program that has a deep recursive call? Is there any config for the project where one can specify the stack or heap size for executables?\n", "answer": "I solved the problem by adding following linker flag in project'sCMakeList.txt\n\n```\nMATH(EXPR stack_size \"16 * 1024 * 1024\") # 16 Mb\nset(CMAKE_EXE_LINKER_FLAGS \"-Wl,--stack,${stack_size}\")\n```\n"} {"question": "How can one increase the maximum size of a stack for C program that has a deep recursive call? Is there any config for the project where one can specify the stack or heap size for executables?\n", "answer": "I solved the problem by adding following linker flag in project'sCMakeList.txt\n\n```\nMATH(EXPR stack_size \"16 * 1024 * 1024\") # 16 Mb\nset(CMAKE_EXE_LINKER_FLAGS \"-Wl,--stack,${stack_size}\")\n```\n"} {"question": "When duplicating a file descriptor fd calling dup, and closing the original file descriptors.\n\nDo all the duplicated file descriptors get closed also?\n", "answer": "No the duplicates won't be closed. Otherwise the main use-case (duplicating intoSTDOUT_FILENOandSTDIN_FILENO) would be pretty useless.\n"} {"question": "If I use goto instruction inside a recursive function (wanting to exit the function before it finishes naturally) is the stack freed automatically or not?\n", "answer": "no, and so far as I know most compilers will not goto to exit the current function.\n\nif you must escape directly from deep recursionthrowanexception(c++) or uselongjmp(c) these actions will restore the stack.\n"} {"question": "I want to fetch and decode a instruction at address X. After that I want to increment the address by 4 and then execute the decoded instruction. The registers are 32 bit big endian. I am not asking for a solution, more a pointer or tips on how to do this in C, or if any of you know some good guides to follow.\n", "answer": "You probably want assembly for this, not C. You could link assembly code into a C program, but you shouldn't write that in C.\n"} {"question": "Suppose I'm writing a program for an environment that has 32 bits for virtual spaces addresses (4294967296 addresses), what happens if create more than 4294967296 variables, effectively exceeding the number of possible addresses? Or all programs in an environment collectively use over 4294967296 addresses?\n", "answer": "It depends precisely how you try to do it. It may crash, it may return an error, it may throw an exception.\n"} {"question": "I have a string char * a = '343'. I want to convert it into integer value.\n\nExample.\nchar *a = \"44221\"\nI want to store that value into into int a;\n", "answer": "This is is part of most C runtimes:\n\n```\n#include \n\nchar *a = \"1234\";\nint i = atoi(a);\n```\n\nThat's theatoifunction. Do read through the various methods available. C's library is pretty lean so it won't take long.\n"} {"question": "I'm writing some kind of protocol to transmit with the NRF24 module so, the procotol is declared like this:\n\n```\nunsigned char protocol[16];\n```\n\nthat protocol have 16bits or 16bytes size?\n", "answer": "16 bytes. 1 char is generally 1 byte on most systems.\n"} {"question": "I want to fetch and decode a instruction at address X. After that I want to increment the address by 4 and then execute the decoded instruction. The registers are 32 bit big endian. I am not asking for a solution, more a pointer or tips on how to do this in C, or if any of you know some good guides to follow.\n", "answer": "You probably want assembly for this, not C. You could link assembly code into a C program, but you shouldn't write that in C.\n"} {"question": "I have a cordova project and I added windows platform but when I run the project I have this error:\n\n```\nMSBuild v4.0 is not supported, aborting.\nError: AppPackages doesn't exists\n```\n", "answer": "Try to set OS environment variable \nVSINSTALLDIR = C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\\nwhich points to your Visual Studio folder with MSBuild directory.\n"} {"question": "I have a cordova project and I added windows platform but when I run the project I have this error:\n\n```\nMSBuild v4.0 is not supported, aborting.\nError: AppPackages doesn't exists\n```\n", "answer": "Try to set OS environment variable \nVSINSTALLDIR = C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\\nwhich points to your Visual Studio folder with MSBuild directory.\n"} {"question": "I have a cordova project and I added windows platform but when I run the project I have this error:\n\n```\nMSBuild v4.0 is not supported, aborting.\nError: AppPackages doesn't exists\n```\n", "answer": "Try to set OS environment variable \nVSINSTALLDIR = C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\\nwhich points to your Visual Studio folder with MSBuild directory.\n"} {"question": "I have define below array in int data types with hexa decimal data.\n\n```\nvolatile int Send_Data[3] = {0x0H11, 0xAAAC, 0x0DD0};\n```\n\nHow can I initialize hex array with int data type in c language?\n", "answer": "Hex array does not exist. Hex is only representation for numbers in computer language (used for programmers).\n\n```\nvolatile int Send_Data[3] = {1, 2, 3};\n```\n"} {"question": "I'm having issues with a c program that I want to debug.\nI would like to know how to get a file that contains every lines of my executable, so I can later set breakpoints with gdb in it.\nThanks :)\n", "answer": "For GCC specify-gwhen compiling.\n\nMore here:https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html\n"} {"question": "I'm having issues with a c program that I want to debug.\nI would like to know how to get a file that contains every lines of my executable, so I can later set breakpoints with gdb in it.\nThanks :)\n", "answer": "For GCC specify-gwhen compiling.\n\nMore here:https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html\n"} {"question": "This question already has answers here:Concise way to implement round() in C?(10 answers)Closed6 years ago.\n\nlike 52.7-->53, 5.5-->6, 3.2->3\n", "answer": "To handle negative numbers properly (-52.7 ==> -53 (away from zero)), you must check if the initial value is negative:\n\n```\n((int)(num + ((num > 0)? +0.5 : -0.5)))\n```\n"} {"question": "This question already has answers here:Concise way to implement round() in C?(10 answers)Closed6 years ago.\n\nlike 52.7-->53, 5.5-->6, 3.2->3\n", "answer": "To handle negative numbers properly (-52.7 ==> -53 (away from zero)), you must check if the initial value is negative:\n\n```\n((int)(num + ((num > 0)? +0.5 : -0.5)))\n```\n"} {"question": "I know thatint *(*func)()means a function pointer which takes no arguments and returns an integer pointer but what does the following syntax means in C:\n\n```\nint *(*func())[]\n```\n\nAny explanations on how do we read such syntax in C would be very helpful.\n", "answer": "funcis a function and returning a pointer to an array of pointers to int.\n\nreference link :http://gateoverflow.in/35193/regarding-pointers\n"} {"question": "I have a dynamic array of c-strings\n\nchar **my_strings = (char**)malloc(50 * sizeof(char*));\n\nand I want to find it's actual length (how many strings it actually contains). How can I do this?\n", "answer": "You can't tell: it's your job to keep track of the size, or to use a magic value (NULL, say) to mark the final element.\n\nNote that the c runtime probably keeps track of the amount of memory allocated, but this is not exposed to you in any portable way.\n"} {"question": "When attempting to compile\n\n```\n#include\n\nint main(){\n\nprintf(\"Hello World\");\n\nreturn 0;\n\n}\n```\n\nI get the following errors with Solaris11 gcc:\n\nhello.c:4:23: error: expected expression before ';' tokenhello.c:6:1: error: expected ';' before '}' token\n\nVisual C++ can compile this code.\n", "answer": "the ';' in line four (thereturnstatement) is not a standard ';'.\n"} {"question": "My function isvoid x(int *y);\n\nI want to call it likex(&6);orx({6});, I do not want to define an integer and assign 6 to it, I want single line.\n", "answer": "What you need iscompound literals\n\n```\n#include \n\nvoid x(const int *y)\n{\n printf(\"%d\\n\", *y);\n}\n\nint main(void)\n{\n x(&(int){6});\n\n return 0;\n}\n```\n"} {"question": "I'm trying to read 4 user inputs that can either be one digit, two digits, or a letter. I've tried using %c, but that can't contain any two digit numbers. I've also tried %d, but that reads all letters as 0. Is there anything that can cover all the bases?\n", "answer": "In C there %c is usually for character inputs and %d is for integer. Usually you use these when scanning. Try %s this scans a string.\n"} {"question": "```\n'#include \nint main() \n{ \n short arr[3][2]={3, 6, 9, 12, 15, 18}; \n printf(\"%d %d\", *(arr + 1)[1], **(arr + 2)); \n}'\n```\n\nThe output of the program is 15,15?\n", "answer": "As per the operator precedence rule*(a+i)[j]will be parsed as*((a + i)[j])which is ultimately equivalent to*( *(a + i + j) ). So fori = 1andj = 1it will be*( *(a + 1 + 1) ) = *( *( a + 2) + 0) = a[2][0]\n"} {"question": "```\n'#include \nint main() \n{ \n short arr[3][2]={3, 6, 9, 12, 15, 18}; \n printf(\"%d %d\", *(arr + 1)[1], **(arr + 2)); \n}'\n```\n\nThe output of the program is 15,15?\n", "answer": "As per the operator precedence rule*(a+i)[j]will be parsed as*((a + i)[j])which is ultimately equivalent to*( *(a + i + j) ). So fori = 1andj = 1it will be*( *(a + 1 + 1) ) = *( *( a + 2) + 0) = a[2][0]\n"} {"question": "How to do stop scrolling uitableview if new rows are not there in tableview in objective c?\n", "answer": "For disabling bounces for the tableView you can use:\n\n```\nself.tableView.bounces = NO;\n```\n\nthis will disable it when it gets to the last row\n"} {"question": "Im new to programming with C and I'm having a hard time coming up with the proper formula to where it ignores, spaces, tabs, and new lines when I enter a string\n\nMy Current Code\n", "answer": "Replaceelse specialCharacter++;withelse if(!isspace(str[x])) specialCharacter++;.\n"} {"question": "For a class project I am writing, my teacher's style guide for functions says that \"input parameters must appear before out parameters.\" I am not too sure what they mean by this?\n", "answer": "If I have a function\n\n```\nvoid foo(int a, int b, int* c)\n{\n *c = a+b;\n}\n```\n\nIn the above case a and b are inputs while c is an output.\n\nGenerally you use \"outputs\" in this way if you are returning an array.\n"} {"question": "I did not understand why this works:\n\n```\nif(1)\n{\n int i;\n}\n```\n\nand this not:\n\n```\nif(1) \n int i;\n```\n\nerror: expected expression before int\n\nIf you could supply some standard reference.\n", "answer": "In C, declarations can only occur as part of acompound-statement, not as part of any of the other kinds ofstatement(see C11 6.8 and 6.8.2).\n"} {"question": "I did not understand why this works:\n\n```\nif(1)\n{\n int i;\n}\n```\n\nand this not:\n\n```\nif(1) \n int i;\n```\n\nerror: expected expression before int\n\nIf you could supply some standard reference.\n", "answer": "In C, declarations can only occur as part of acompound-statement, not as part of any of the other kinds ofstatement(see C11 6.8 and 6.8.2).\n"} {"question": "Got this\n\n```\nchar array1[10][10];\n```\n\nIs it possible to get address of array1 ? In which type could I stock it ?\nAlready tried the following:\n\n```\nchar *hold[10][10];\nhold = &array1;\n```\n\nBut doesnt work, ideas?\n", "answer": "What you have now is a 2D array ofchar *. You need some parenthesis in this type.\n\n```\nchar (*hold)[10][10];\n```\n\nThis is a pointer to a 2D array of typechar[10][10]that you can assign&arrayto.\n"} {"question": "Can someone please explain to me the difference between saya=1and*a=1in C. I'm having difficulty conceptualizing how pointers are used.\n", "answer": "a = 1assigns1toa.\n\n*a = 1assigns1to the memory location thatapoints to. (Note thatahas to be a pointer for this to compile.)\n"} {"question": "Got this\n\n```\nchar array1[10][10];\n```\n\nIs it possible to get address of array1 ? In which type could I stock it ?\nAlready tried the following:\n\n```\nchar *hold[10][10];\nhold = &array1;\n```\n\nBut doesnt work, ideas?\n", "answer": "What you have now is a 2D array ofchar *. You need some parenthesis in this type.\n\n```\nchar (*hold)[10][10];\n```\n\nThis is a pointer to a 2D array of typechar[10][10]that you can assign&arrayto.\n"} {"question": "Can someone please explain to me the difference between saya=1and*a=1in C. I'm having difficulty conceptualizing how pointers are used.\n", "answer": "a = 1assigns1toa.\n\n*a = 1assigns1to the memory location thatapoints to. (Note thatahas to be a pointer for this to compile.)\n"} {"question": "Can anyone explain what $(%SYMBOLIC) means in the make file target below?\n\n```\nR_all: $(%SYMBOLIC)\n $(CD_MAKE) $(BASE_ROOT) R_all\n```\n", "answer": "That's just a variable called%SYMBOLIC. Because of the%character, you can't set such a variable with a normal=or:=in the Makefile, but you can set it withdefineor in the environment if you run make directly withexecve\n"} {"question": "Can anyone explain what $(%SYMBOLIC) means in the make file target below?\n\n```\nR_all: $(%SYMBOLIC)\n $(CD_MAKE) $(BASE_ROOT) R_all\n```\n", "answer": "That's just a variable called%SYMBOLIC. Because of the%character, you can't set such a variable with a normal=or:=in the Makefile, but you can set it withdefineor in the environment if you run make directly withexecve\n"} {"question": "This question already has answers here:Two semicolons inside a for-loop parentheses(4 answers)Closed6 years ago.\n\nI'm analyzing a C program and i find this loop that i can't understand. There is no counter or limit or variable.\n\n```\n/* ioloop */\n for (;;)\n {\n// statements\n\n }\n```\n\nis this an infinite loop ?\n", "answer": "It's an idiomatic way of writing a potentially infinite loop in C.\n\nAlternatives such aswhile(1)often issued a compiler warning.\n"} {"question": "What's the exact difference betweenprintkandpr_infofunctions ? And under what conditions, should I choose one over the another ?\n", "answer": "Thekernel's printk.hhas:\n\n```\n#define pr_info(fmt,arg...) \\\n printk(KERN_INFO fmt,##arg)\n```\n\nJust like the name,pr_info()isprintk()with theKERN_INFOpriority.\n"} {"question": "I am working on a project in the X11 API, and I have a Window based custom control consistently rendering. But for some reason, when I re-size the window, the control does not redraw unless I interact with the control directly, or move the entire main window.\n", "answer": "I found the solution to my problem. I just needed to add the Structure Notify Mask to my custom window input.\n\n```\nXSelectInput(display, CustomWindow, StructureNotifyMask);\n```\n"} {"question": "Regarding c variables, I want to know what the x does in:\n\n```\nint var[x]\n```\n", "answer": "This is a declaration of aVariable Length Array(VLA).\n\nThe value of expressionx(most likely, a variable) is treated as the number of array elements. Itmust have a positive valueat the time the expression is evaluated, otherwise the declaration of the VLA produces undefined behavior.\n"} {"question": "Isdup(file_des)equivalent tofcntl(filedes, F_DUPFD, 0)? Ifyes, then which is better to use?\n", "answer": "Yes it exactly the same. According to theposixstandard\n\nThe dup() function provides an alternative interface to the service\n provided by fcntl() using the F_DUPFD command. The call dup(fildes)\n shall be equivalent to:fcntl(fildes, F_DUPFD, 0);\n\ndup()is shorter and easier to read, I would use that.\n"} {"question": "Regarding c variables, I want to know what the x does in:\n\n```\nint var[x]\n```\n", "answer": "This is a declaration of aVariable Length Array(VLA).\n\nThe value of expressionx(most likely, a variable) is treated as the number of array elements. Itmust have a positive valueat the time the expression is evaluated, otherwise the declaration of the VLA produces undefined behavior.\n"} {"question": "Isdup(file_des)equivalent tofcntl(filedes, F_DUPFD, 0)? Ifyes, then which is better to use?\n", "answer": "Yes it exactly the same. According to theposixstandard\n\nThe dup() function provides an alternative interface to the service\n provided by fcntl() using the F_DUPFD command. The call dup(fildes)\n shall be equivalent to:fcntl(fildes, F_DUPFD, 0);\n\ndup()is shorter and easier to read, I would use that.\n"} {"question": "I can't seem to find the answer on here, but I'm sorry if this is a duplicate. Here's my question: When I have two pointers to the same location, then I change the address of one (let's say pointer A), will I (by accident) be changing the address of the other pointer (pointer B)? Or will pointer B's location stay the same?\n", "answer": "Changing the contents of a pointer (as opposed to the object being pointed to) will not affect other pointers to the same object.\n"} {"question": "I can't seem to find the answer on here, but I'm sorry if this is a duplicate. Here's my question: When I have two pointers to the same location, then I change the address of one (let's say pointer A), will I (by accident) be changing the address of the other pointer (pointer B)? Or will pointer B's location stay the same?\n", "answer": "Changing the contents of a pointer (as opposed to the object being pointed to) will not affect other pointers to the same object.\n"} {"question": "I have recently started to learn ANSI C. I have come across this:\n\n```\nint a[7];\n*(a+2);\n```\n\nI don't understand how it's possible to add 2 toa. Does it add 2 to every element ina?\n\nAlso, what is the function of the*? Does it create a pointer?\n", "answer": "a+2causesato be interpreted as a pointer toa's first element. This is calledarray decaying.\n\nIt then offsets that pointer by2anddereferences(*) the resulting pointer. So it's the same asa[2].\n"} {"question": "Are there any static code metrics tools that measure total size of static local variables in c functions. The tools that I explored report the stack size but not the size of the static local variables. Is there another option apart from using linux objdump and parsing the output?\n", "answer": "The POSIXsizecommand can be used for this purpose. The size of the data section is the size of all data in static storage (except data declared const on some targets).\n"} {"question": "Everytime I compile and run c file, I have to type:\n\ngcc filename.c\n\na.out\n\nI don't want to do this in two lines, How to compile and run in one line on linux terminal?\n", "answer": "Try\n\n```\ngcc filename.c && a.out\n```\n\nIt only runs the second command if the first was successful. Seehttps://askubuntu.com/questions/334994/which-one-is-better-using-or-to-execute-multiple-commands-in-one-line\n"} {"question": "The .txt file will have the matrix we need to input into our program, it may have more than one matrices.\n\nI am using VIM editor on Linux.\n\nIs there any specific escape sequence to copy the .txt file while compiling?\n", "answer": "To redirect standard output to a file, the>character is used like this:\n\nls > file_list.txt\n\nAnd To take input from the file , the\n\nvoid main ()\n{\n char word[10] = {\"hello\"};\n FILE*fp;\n fp = fopen(\"C:\\\\temp\\\\Dictionary.txt\", \"w+\"); \n\n fprintf(fp, word[0]);\n}\n```\n", "answer": "You're printing first char instead of the string. And it might not be a valid format either. Correct call will befprintf(fp, \"%s\", word). And don't forget to close file too.\n"} {"question": "Is it possible to multiply usingi**in C?\nFor example, I can incrementiusingi++. Why doesn'ti**work in C?\n\n```\n#include \nint main(void)\n{\n int result;\n for (int i = 2; i < 100; i**){\n result = i + 1;\n printf(\"%i\\n\", result);\n }\n\n\n return 0;\n}\n```\n", "answer": "No, it's not possible. There is no operator like**in C unlike unary increment (++) and decrement (--) operators. You should have tryi *= i.\n"} {"question": "Is it possible to multiply usingi**in C?\nFor example, I can incrementiusingi++. Why doesn'ti**work in C?\n\n```\n#include \nint main(void)\n{\n int result;\n for (int i = 2; i < 100; i**){\n result = i + 1;\n printf(\"%i\\n\", result);\n }\n\n\n return 0;\n}\n```\n", "answer": "No, it's not possible. There is no operator like**in C unlike unary increment (++) and decrement (--) operators. You should have tryi *= i.\n"} {"question": "Let's say we have the following C code:\n\n```\n#include\nint main(){\n char *a = \"askakasd\";\n return 0;\n}\n```\n\nI tried to find my local variable \"a\", but I don't know how to recognize it looking in this output, where p is the C code compiled:\n\n\n", "answer": "It's not there. Since the code can't tell at execution time whether it's there or not, the linker removed it to save space.\n"} {"question": "Probably really trivial question, but:\n\nRecently started working an open-source system -janus-gatewayand i am in a need to run a method every 1 second(checking if all users muted).\n\nWhat are the options to do this in C?\nShould i spawn a new thread?\n\nAnswer with an example would much appreciated!\n", "answer": "Ended up spawning a new thread and doing stuff that way.\n"} {"question": "Let's say we have the following C code:\n\n```\n#include\nint main(){\n char *a = \"askakasd\";\n return 0;\n}\n```\n\nI tried to find my local variable \"a\", but I don't know how to recognize it looking in this output, where p is the C code compiled:\n\n\n", "answer": "It's not there. Since the code can't tell at execution time whether it's there or not, the linker removed it to save space.\n"} {"question": "Probably really trivial question, but:\n\nRecently started working an open-source system -janus-gatewayand i am in a need to run a method every 1 second(checking if all users muted).\n\nWhat are the options to do this in C?\nShould i spawn a new thread?\n\nAnswer with an example would much appreciated!\n", "answer": "Ended up spawning a new thread and doing stuff that way.\n"} {"question": "Probably really trivial question, but:\n\nRecently started working an open-source system -janus-gatewayand i am in a need to run a method every 1 second(checking if all users muted).\n\nWhat are the options to do this in C?\nShould i spawn a new thread?\n\nAnswer with an example would much appreciated!\n", "answer": "Ended up spawning a new thread and doing stuff that way.\n"} {"question": "!I had written this simple program on a different Ubuntu PC using Gedit]1\n", "answer": "You do not have execute permissions for your executable.\n\nUse\n\n```\nchmod +x ./secondo\n```\n\nfirst to correct this.\n\nThisquestion gives more detail.\n"} {"question": "!I had written this simple program on a different Ubuntu PC using Gedit]1\n", "answer": "You do not have execute permissions for your executable.\n\nUse\n\n```\nchmod +x ./secondo\n```\n\nfirst to correct this.\n\nThisquestion gives more detail.\n"} {"question": "How to decide if two ip are on the same subnet or not?\nThe only input is the ip address and the subnet mask!\nWhat is the optimal way, usingC/C++, to compute if two ip have the same subnet?\n", "answer": "```\nbool checkForSubnetEquality(in_addr_t ipA, in_addr_t ipB, uint32_t subnetMask) {\n return (ipA & subnetMask) == (ipB & subnetMask);\n}\n```\n"} {"question": "I have searched on the Internet but most of the answers suggest using library conio.h which is not available. Can anyone give me answer for this question. Thanks in advance.\n", "answer": "If you are on Windows\n\nsystem(\"cls\");\n\nIf you are on Linux/unix\n\nsystem(\"clear\");\n"} {"question": "How to decide if two ip are on the same subnet or not?\nThe only input is the ip address and the subnet mask!\nWhat is the optimal way, usingC/C++, to compute if two ip have the same subnet?\n", "answer": "```\nbool checkForSubnetEquality(in_addr_t ipA, in_addr_t ipB, uint32_t subnetMask) {\n return (ipA & subnetMask) == (ipB & subnetMask);\n}\n```\n"} {"question": "I have searched on the Internet but most of the answers suggest using library conio.h which is not available. Can anyone give me answer for this question. Thanks in advance.\n", "answer": "If you are on Windows\n\nsystem(\"cls\");\n\nIf you are on Linux/unix\n\nsystem(\"clear\");\n"} {"question": "How to cast \"ptr\" to assign directly a zend_long into it without writing two lines?\n\n```\nzend_long *val = *ptr;\n*val = *(ISC_LONG*)var->sqldata;\n```\n", "answer": "Assuming that your original code is correct, the corresponding assignment looks like this:\n\n```\n*((zend_long*)*ptr) = *(ISC_LONG*)var->sqldata;\n```\n"} {"question": "I am trying to initiate a TCP Three-Way-Handshake in C. However, it occurred to me thatconnectmay already be establishing such a connection or in some way interfering. Doesconnectautomatically establish a TCP connection whenever the socket it's called on has theIPPROTO_TCPoption set?\n", "answer": "Yes,IPPROTO_TCPcreates TCP socket. To use raw socket, you need to pass SOCK_RAW as second argument to thesocketfunction.\n"} {"question": "How would I go to cast/convert literalchar '0'toint 0?\n\ni.e.:\n\n```\nchar string[] = \"0101\";\nchar ch = string[0];\nx = magic(ch);\nif (x)\n printf(\"int zero\")\n```\n", "answer": "```\nch = 0;\n```\n\nNow, if you want to convertanydigit-character to its numeric equivalent, you'd need something like:\n\n```\nch = ch - '0';\n```\n"} {"question": "I am trying to initiate a TCP Three-Way-Handshake in C. However, it occurred to me thatconnectmay already be establishing such a connection or in some way interfering. Doesconnectautomatically establish a TCP connection whenever the socket it's called on has theIPPROTO_TCPoption set?\n", "answer": "Yes,IPPROTO_TCPcreates TCP socket. To use raw socket, you need to pass SOCK_RAW as second argument to thesocketfunction.\n"} {"question": "How would I go to cast/convert literalchar '0'toint 0?\n\ni.e.:\n\n```\nchar string[] = \"0101\";\nchar ch = string[0];\nx = magic(ch);\nif (x)\n printf(\"int zero\")\n```\n", "answer": "```\nch = 0;\n```\n\nNow, if you want to convertanydigit-character to its numeric equivalent, you'd need something like:\n\n```\nch = ch - '0';\n```\n"} {"question": "It is undefined behavior to do this?\n\n```\nchar *a = \"hello\";\nchar b[] = \"abcd\";\na = b;\n```\n\nMy compiler throws no warning, with the maximum warning level.\n", "answer": "There is no UB here. You are simply re-assigning a pointer to point at the address of the start of the array instead.\n\nNote that you are not actually modifying the value thatais pointing at, onlyaitself, andais a normalchar *.\n"} {"question": "How to convert rgb to hexadecimal using GTK?\n\nI can convert from hex to rgb usinggdk_rgba_parse (GdkRGBA *rgba, const gchar *spec);, but not the reverse.\n", "answer": "You can do this manually:\n\n```\nsprintf(spec, \"#%02X%02X%02X\", (int)(rgba.red*255), (int)(rgba.green*255), (int)(rgba.blue*255));\n```\n\nBe sure to provide a buffer large enough to hold the string or use g_strdup_printf instead.\n"} {"question": "How to convert rgb to hexadecimal using GTK?\n\nI can convert from hex to rgb usinggdk_rgba_parse (GdkRGBA *rgba, const gchar *spec);, but not the reverse.\n", "answer": "You can do this manually:\n\n```\nsprintf(spec, \"#%02X%02X%02X\", (int)(rgba.red*255), (int)(rgba.green*255), (int)(rgba.blue*255));\n```\n\nBe sure to provide a buffer large enough to hold the string or use g_strdup_printf instead.\n"} {"question": "This question already has answers here:Maximum size of a bit field in C or C++? [duplicate](2 answers)struct bitfield max size (C99, C++)(4 answers)Closed6 years ago.\n\nIs the following code legal?\n\n```\nstruct BigInt {\n uint64_t a : 128;\n};\n```\n", "answer": "A bitfield must fit within a singleint, so you're out of luck unlessintis 128 bits on your platform.\n\n(You were also missing a;at the end of thestructprior to the edit.)\n"} {"question": "I have one program that uses shared library. In shared library, error case they have written exit(0). So if that function is called then exit(0) will be executed of shared library.\n\nWill it exit my program too ?\n", "answer": "Yes it terminates the calling process immediately.SIGCHLD signal will be send to process which inherited by process 1 or init.\n"} {"question": "I got a warning:\n\n```\nassignment makes integer from pointer without a cast.\n```\n\nThe line that triggers the warning is:\n\n```\nnev[i][0]=\"\";\n```\n\nThenevvariable is a 2 dimension char block(please don't ask why, I don't know).\n\nThanks in advance guys!\n", "answer": "Ifnevis a 2-dimensional array ofchar, thennev[i][0]is achar. But\"\"is an array ofchar, not achar.\n – Barmar\n\nnev[i][0]=\"\";-->nev[i][0]=0;– BLUEPIXY\n"} {"question": "As the title suggests, I would like to create connection between a JavaScript (usingWebSocket) client and a C/C++ (usingWinsock) server.\n\nA simple code example would be much appreciated.\n", "answer": "You can't use Websocket at java side and a Winsock only implementation on C++ side, you have to implement Websocket over winsock or using some thing like Qt Platform which has an implementation Websocket under C++. sample codes are available onQt Docs.\n"} {"question": "In my program I have got a NxN table stored in one-dimensional table.\nSo, I use#define Board(x,y) board[(x)*N + (y)]and works perfectly\n\nSo, what if my board becomes N1xN2 and N1 is different than N2?\nHow should I set the #define instruction then?\n\nthank you in advance\n", "answer": "It shouldn't work perfectly. You need(board[(x)*N+(y)])for square boards, and(board[(x)*N2+(y)])for non-square boards, assuming x from 0 to N1-1, y from 0 to N2-1\n"} {"question": "In my program I have got a NxN table stored in one-dimensional table.\nSo, I use#define Board(x,y) board[(x)*N + (y)]and works perfectly\n\nSo, what if my board becomes N1xN2 and N1 is different than N2?\nHow should I set the #define instruction then?\n\nthank you in advance\n", "answer": "It shouldn't work perfectly. You need(board[(x)*N+(y)])for square boards, and(board[(x)*N2+(y)])for non-square boards, assuming x from 0 to N1-1, y from 0 to N2-1\n"} {"question": "I wonder how to convert like a char: 1101_0110(D6) to two char(ascii format) 0100_0100(44) and 0011_0110(36).\nThanks a lot!\n", "answer": "sample code\n\n```\n#include \n\nint main(void){\n char x = '\\xD6';\n char asc[3];\n sprintf(asc, \"%02X\", (unsigned char)x);\n printf(\"%s\\n\", asc);//D6\n}\n```\n"} {"question": "I wonder how to convert like a char: 1101_0110(D6) to two char(ascii format) 0100_0100(44) and 0011_0110(36).\nThanks a lot!\n", "answer": "sample code\n\n```\n#include \n\nint main(void){\n char x = '\\xD6';\n char asc[3];\n sprintf(asc, \"%02X\", (unsigned char)x);\n printf(\"%s\\n\", asc);//D6\n}\n```\n"} {"question": "I'm searching for a method to convert a two Byte UNICODEora variable (1-3 Byte) UTF-8 string to Chinese Simplified (GB2312). I found a lot of methods for php, Java, C# and Windows but nothing for standard \"C\".\n\nRight now, my best solution is to translate this JavaScript example:https://gist.github.com/19317362/a1d8e40bfb6587463d4d\n\nThanks in advance!\n", "answer": "As Remy Lebeau mentioned, I used the C-compatible library iconv.\n"} {"question": "I know the difference betweenself.xxxand_xxxBut I don't understand the difference betweenself->_xxx = yyyand_xxx = yyy\n\nIs it only a matter of writing in ObjC and C?\n", "answer": "When accessing an ivar there is no difference betweenself->_ivarand_ivarin terms of resulting compiled code.\n\nOnly use case I can think of where it matters is if you have another local or global variable with the same name in the same scope, and you want to use the ivar.\n"} {"question": "Normally when a foo() have memory problem the whole program will simply core dump, crash. But does C have any protection ways to guarantee a program will not crash, just goto a state or simply return, when core dump happens inside foo()?\n", "answer": "Can not say for try and catch statement in c but yes you can write signal handler to catch segfault. \nHere is a link.How to catch segmentation fault in Linux?\n"} {"question": "The code i'm looking for is the following :\n\nWe have a source number100, a destination number,50and we have10steps.\n100 ----> 50 in 10 steps.\n\nHow can i find the value X, corresponding tothe number i have to subto 100, 10 times to have 50. I found :dest*steps/srcbut didn't work...\n\nRegards.\n", "answer": "It's as simple as this\n\n```\nX = (src-dest)/NumOfSteps\n```\n"} {"question": "I was trying some C codes in Dev C++ and Visual C++.\n\nFor Example:\n\n```\nint t =6;\nprintf(\"\\nt = %d \",&t);\n```\n\nThe output is :\n\n```\nt = 2358848\n```\n\nwhy is it so ? How can I get the value of t?\n", "answer": "&tgives you theaddress oft, not its value.\n\nTo print the value do:\n\n```\nprintf(\"\\nt = %d \", t);\n```\n"} {"question": "If I have a .jar file with a compiled scala method, is there any way to call it from a C/C++ dll ? How can I do this? I have only been able to find infos on the opposite.\n", "answer": "A Scala program (once compiled) is a Java class. So follow this suggestion:How to access the Java method in a C++ application\n"} {"question": "When I try to execute a c code with the following two lines, ulimit still shows to be unlimited but i want the answer to be 1024.\n\nsystem(\"ulimit -d 1024\");\nsystem(\"ulimit -d\");\n", "answer": "If you want to set the ulimit for calling process, usesetrlimit(2), with arguemntRLIMIT_DATA.\n\nsystem()will fork and the ulimit command only affects the child process, not the calling process.\n"} {"question": "When I try to execute a c code with the following two lines, ulimit still shows to be unlimited but i want the answer to be 1024.\n\nsystem(\"ulimit -d 1024\");\nsystem(\"ulimit -d\");\n", "answer": "If you want to set the ulimit for calling process, usesetrlimit(2), with arguemntRLIMIT_DATA.\n\nsystem()will fork and the ulimit command only affects the child process, not the calling process.\n"} {"question": "So I compiled a simple cpp program using clang++ with termux on android, but I can't run the program, I get the following error:\n\n```\n$ ./execname\n-bash: . /execname: Permission denied\n```\n", "answer": "Are you running on shared storage (under/sdcard)? The file system there does not support executable permissions.\n\nTry compiling and running the file directly in the$HOMEdir!\n"} {"question": "I wrote my c program add.c, then preprocessed with cpp, then compiled with CC to obtain an add.s file. Now I would like to open it to see the assembly code. Can't find a way to do it.\n", "answer": "The.sfiles are basically assemblersourcefiles, so you can pretty much open them in whatever tool you used to create the.cfiles in the first place.\n\nIn other words, mere mortals will opt forNotepad++orEmacs, but the true intelligentsia will useVim:-)\n"} {"question": "This question already has answers here:How to generate a random int in C?(32 answers)Closed6 years ago.\n\nHere is my code:\n\n```\nalpha = ((rand() % 12) + 1) * 2 + 1;\n```\n\nI want to generate randomoddnumbers between 0-25. But except integer13. How can I fix this? Thank you.\n", "answer": "Generates number from 0 to 23. If it's a 13, then store 25 in your variable :\n\n```\nalpha = ((rand() % 11) + 1) * 2 + 1;\nif (alpha == 13) alpha = 25;\n```\n"} {"question": "I have achar*to where I want to set the byte, from malloc. How do I set it to 1 or 0, for example?\n", "answer": "Assign to your dereferenced pointer:\n\n```\n//This will (obviously) set it to 1\n*your_pointer = 1;\n\n//This will set it to 0\n*your_pointer = 0;\n```\n"} {"question": "```\nchar msg[100] = {’C’,’P’,’R’,‘E’,‘\\0’,‘2’,‘8’, ‘8’,‘\\0’};\nint my_length = 0xFFFFFFFF;\nmy_length = strlen(msg);\n```\n\nI thought it is nine, however, the answer is 4. anyone can explain? thanks\n", "answer": "strlenwill stop counting as soon as it hits a null terminator (as C uses null terminated strings and expects to only find them at the end of a string).\n\nYou have four characters before your first null terminator, therefore the length is 4.\n"} {"question": "I am trying to compile a C program and am required to use these flags. I was hoping you could tell me why I am getting these errors.\n\nCommand:\n\n```\ngcc -ansi –Wall –pedantic stack.c\n```\n\nOutput:\n\ngcc: –Wall: No such file or directorygcc: –pedantic: No such file or directory\n", "answer": "It's\n\n```\ngcc -ansi -Wall -pedantic\n```\n\nYou're using one of those dashes:Dash(specifically, you are using en-dash U+2013). You need to use minus sign-instead\n"} {"question": "I am working on compiler design for 8051. I want to declare a memory of say 30 locations, each location is of 8bits. How do I declare that in C?\n", "answer": "to declare 30 x 8 bits memory:\n\n```\nchar memory[30];\n```\n\nto declare n x n memory:\n\n```\nchar memory[30][30];\n```\n\nit declares 30 x 30 x 8bits memory.\n"} {"question": "What is the exact equivalent of the following function for Ubuntu?\n\nhttp://www.qnx.com/developers/docs/6.4.1/neutrino/lib_ref/e/endian_be16.html\n", "answer": "What you need is:\n\n```\n#include \n\nresult_in_host_endianness = be16toh(my_big_endian_number)\n```\n\nSeehttp://man7.org/linux/man-pages/man3/endian.3.html\n"} {"question": "What is the exact equivalent of the following function for Ubuntu?\n\nhttp://www.qnx.com/developers/docs/6.4.1/neutrino/lib_ref/e/endian_be16.html\n", "answer": "What you need is:\n\n```\n#include \n\nresult_in_host_endianness = be16toh(my_big_endian_number)\n```\n\nSeehttp://man7.org/linux/man-pages/man3/endian.3.html\n"} {"question": "I have several header and source files that I needed to create, in which there are functions that generate random numbers. If I wanted to initialize my rng, where do I have to put my \"srand(time(NULL))\" line, in my code? Is it ok to put it in my main.c file? Does it affect the other source files?\n", "answer": "Yes, you can put it in the main file. Once you callsrandit is applicable for the entire program, even if it has multiple files.\n"} {"question": "The title is the exact error my compiler(geany on ubuntu) gives me when I try to compile. The part of code in question is the following:\n\n```\nfor(int q=strlen(stringA)-1;q>0;q--)\n{\n//do stuff\n}\n```\n\nI've already set the C99 mode and the initialization of variables in the 'for' header is accepted. Is what I did simply illegal in C?\n", "answer": "I assume you are missing an include. Try:\n\n#include \n"} {"question": "I am usingfPointInput = fopen(fileName, \"r\");, when trying to access the data chunk inide the .WAV file but never getting any comprehensible results. (Data array is filled mostly with zeroes except the first few hundred indices). Can this be caused by the usage of inaccurate opening mode ?\n", "answer": "Thisarticleindicates that usingrbworks well.\nNote that nothing in this answer isWindowsspecific. Just standardCIO.\n"} {"question": "The title is the exact error my compiler(geany on ubuntu) gives me when I try to compile. The part of code in question is the following:\n\n```\nfor(int q=strlen(stringA)-1;q>0;q--)\n{\n//do stuff\n}\n```\n\nI've already set the C99 mode and the initialization of variables in the 'for' header is accepted. Is what I did simply illegal in C?\n", "answer": "I assume you are missing an include. Try:\n\n#include \n"} {"question": "I am usingfPointInput = fopen(fileName, \"r\");, when trying to access the data chunk inide the .WAV file but never getting any comprehensible results. (Data array is filled mostly with zeroes except the first few hundred indices). Can this be caused by the usage of inaccurate opening mode ?\n", "answer": "Thisarticleindicates that usingrbworks well.\nNote that nothing in this answer isWindowsspecific. Just standardCIO.\n"} {"question": "I want to use interrupt handlers\n\n```\nvoid EXTI3_IRQHandler(void)\n{\n //body\n}\n```\n\nbut when I build the project, I get the following error:\n\nSymbolEXTI3_IRQHandlermultiply defined (by stm32f10x_it.o and\n main.o)\n\nI have included library stm32f10x_exti.h\n", "answer": "Handlervoid EXTI3_IRQHandler(void)already defined in filestm32f10x_it.c.\nYou can replace code of your handler frommain.cto this special file or comment blank handler instm32f10x_it.c.\n"} {"question": "What would this translate to (in a more verbose way)?\n\n```\nlocal.sin_addr.s_addr = (!ip_address) ? INADDR_ANY:inet_addr(ip_address);\n```\n\nTrying to understand Ternary operators and I can't quite get it.\n", "answer": "A ternary is similar to anifstatement, but it can be used where an expression is required. So it's equivalent to:\n\n```\nif (!ip_address) {\n local.sin_addr.s_addr = INADDR_ANY;\n} else {\n local.sin_addr.s_addr = inet_addr(ip_address);\n}\n```\n"} {"question": "I want to do an evented read on Serial port which will run only when the data is available.\n\nI have triedsigactionbut it causes problem when making a highly threaded application, alsosleepfunction seem to work incorrectly according to many forums.\n\nSo I am looking for a similar way as in windowsWaitCommEventthat is used in MSDN.\n", "answer": "The canonical equivalents for linux systems is to usepoll()orselect().\n\nWorkings are different of course.\n"} {"question": "I want to do an evented read on Serial port which will run only when the data is available.\n\nI have triedsigactionbut it causes problem when making a highly threaded application, alsosleepfunction seem to work incorrectly according to many forums.\n\nSo I am looking for a similar way as in windowsWaitCommEventthat is used in MSDN.\n", "answer": "The canonical equivalents for linux systems is to usepoll()orselect().\n\nWorkings are different of course.\n"} {"question": "If \"Allow windows manager to decorate window\" is on.\nWhat is the function name in the wine source that knows a user click this X button and send the WM_CLOSE to the app?\nThank you\n", "answer": "The window manager sends ClientMessage with type WM_PROTOCOLS and the protocol value WM_DELETE_WINDOW. This is handled in dlls/winex11.drv/event.c: X11DRV_ClientMessage() -> handle_wm_protocols().\n"} {"question": "While running a sample code from the internet, I am stuck at 'glutTimerfunc'. I cannot figure out what is this error.\n\n\n", "answer": "glutTimerFunctakes a pointer to a function that must have a signature of\n\n```\nvoid (*func)(int value)\n```\n\nYourframeTimerCallbackfunction doesn't take an integer parameter. Hence the error.\n\nRefer tohttps://www.opengl.org/resources/libraries/glut/spec3/node64.html\n"} {"question": "This question already has answers here:Yosemite and Valgrind(12 answers)Closed6 years ago.\n\nI am not sure if I can installvalgrinddebugger in my Macbook Pro. I searched online but most posts are related to Ubuntu. Can someone tell if this is possible? If so, can it be by brew for example?\n", "answer": "you can use \"brew install valgrind\" to install valgrind.\n"} {"question": "Is there any way to roundsystemGuessup. In this case the outcome ofsystemGuessis 5.5 I want it to be 6 how do I do this?\n\nSee code below:\n\n```\nint main(void){\n\n int systemGuess = 0;\n stystemGuess = (10 - 1)/2 + 1;\n printf(\" %d \", stystemmGuess);\n}\n```\n", "answer": "Use floating point division andceil:\n\n```\nstystemGuess = ceil((10 - 1)/2.0) + 1;\n```\n\nIf you want to round 0.4 down, useroundinstead.\n"} {"question": "Why we don't use extern when using function from one .c file in another .c file , but we must do extern for variables case? Is it related to linker?\n", "answer": "Functions are extern qualified by default (unless you change it to internal withstatic). For example,\n\n```\nint func(void) {\n}\n\nextern int func2(void) {\n}\n```\n\nBothfuncandfunc2are external. Theexternkeyword is optional for external functions.\n"} {"question": "```\nint j=4;\n(!j!=1)?printf(\"Welcome\"):printf(\"Bye\");\n```\n\nIn the above code segment, according to me, firstj!=1will result in true and!trueis false which must result in printingByebut I getWelcomeas the output.\n\nCan anyone explain this one?\n", "answer": "!executed first because unary operator!has a higher precedence than!=.\n\n!4become0then0 != 1becometrue.\n\nSo, output isWelcome.\n"} {"question": "I'm programmingSTM8micro controller inSTVD. I happen to use an assembly instruction in the middle of code. As shownhereI used a instruction as below\n\n```\nasm(\"MOV $00500A,#$3\");\n```\n\nBut I'm facing with following error\n\n```\n#error cpstm8 ..\\app\\sched.c:183(5) missing prototype\n```\n\nCan anyone help me in fixing this?\n", "answer": "For STM8 assembly instruction, you need to use_before the instruction as shown below\n\n```\n_asm(\"MOV $00500A,#$3\");\n```\n"} {"question": "I'm programmingSTM8micro controller inSTVD. I happen to use an assembly instruction in the middle of code. As shownhereI used a instruction as below\n\n```\nasm(\"MOV $00500A,#$3\");\n```\n\nBut I'm facing with following error\n\n```\n#error cpstm8 ..\\app\\sched.c:183(5) missing prototype\n```\n\nCan anyone help me in fixing this?\n", "answer": "For STM8 assembly instruction, you need to use_before the instruction as shown below\n\n```\n_asm(\"MOV $00500A,#$3\");\n```\n"} {"question": "GDB is showing the content of a register as\n\n```\nrbp 0x604420 0x604420 \n```\n\nWhat does sval mean? Does it means string val?\n", "answer": "What does sval mean?\n\nIt means that there is a symbol (givenx86_64target,0x604420would usually mean it's a.textsymbol) with that value in the binary, andrbphappens to point to that symbol.\n\nYou can runnm your-binary | grep svaland see that symbol.\n\nDoes it means string val?\n\nNo,nothingof the sort.\n"} {"question": "I am learning C usingthissite.\n\nUnderfgetc()Function the author said:\n\nThis function reads a single character from a file and after reading increments the file position pointer.\n\n```\nFILE *fp;\nfp = fopen(filename, \"r\");\n```\n\nWhat I want to ask is that thefile position pointeris different from the pointerfpor not?\n", "answer": "It means your current offset in the file. It is the return value offtell.\n"} {"question": "GDB is showing the content of a register as\n\n```\nrbp 0x604420 0x604420 \n```\n\nWhat does sval mean? Does it means string val?\n", "answer": "What does sval mean?\n\nIt means that there is a symbol (givenx86_64target,0x604420would usually mean it's a.textsymbol) with that value in the binary, andrbphappens to point to that symbol.\n\nYou can runnm your-binary | grep svaland see that symbol.\n\nDoes it means string val?\n\nNo,nothingof the sort.\n"} {"question": "I'm trying define \"ip_addr\" from lwip. That's my code:\n\n```\n#include \"lwip/tcp.h\"\n#include \"ip_addr.h\"\n...\nstruct ip_addr ip;\n```\n\nBut when i'm trying to compile this, compiler gives me error:\n\n```\nerror: storage size of 'ip' isn't known\n```\n", "answer": "Try:\n\n```\nip_addr_t ip;\n```\n\nand your second #include line should it not be:\n\n```\n#include \"lwip/ip_addr.h\"\n```\n"} {"question": "my code can be compiled with C or C++ compilers.\nI'd like to know which one is doing the compilation\n\nis there preprocessor define to tell me this ?\n", "answer": "The definition is__cplusplus.\n\n```\n#ifdef __cplusplus \n// treated as C++ code\n#else\n// treated as C code\n#endif // __cplusplus\n```\n"} {"question": "my code can be compiled with C or C++ compilers.\nI'd like to know which one is doing the compilation\n\nis there preprocessor define to tell me this ?\n", "answer": "The definition is__cplusplus.\n\n```\n#ifdef __cplusplus \n// treated as C++ code\n#else\n// treated as C code\n#endif // __cplusplus\n```\n"} {"question": "I want to create a socket connected directly to the gpu.\nI would like to send data from a server to the gpu without spending a copy/moving time from host to device.\nIs it possible?\n", "answer": "If you have suitable network hardware and are willing to write your own device driver for your network adaptor, thenmaybe.SeveralInfiniband and iWARP adapter vendors can have engineered such support for their products.\n\nBut realistically, no.\n"} {"question": "When writing a program (Unix-style), can it address and manage more than one stdout and stdin channels?\n", "answer": "No; there is (at most) one standard input and one standard output at any given time. Ultimately, since the question specifically mentions Unix, standard input is file descriptor 0 and standard output is file descriptor 1, and there is only one file descriptor with a given number.\n"} {"question": "I want to create a socket connected directly to the gpu.\nI would like to send data from a server to the gpu without spending a copy/moving time from host to device.\nIs it possible?\n", "answer": "If you have suitable network hardware and are willing to write your own device driver for your network adaptor, thenmaybe.SeveralInfiniband and iWARP adapter vendors can have engineered such support for their products.\n\nBut realistically, no.\n"} {"question": "How can I stop the execution of a thread until a file is created ?I would like to avoid doing it in a busy loop, and use something with a behavior similar to select(). Is something like this possible?I only found ways to check if a file exists at a given time.\n", "answer": "You are probably looking forinotify(7). At the botton of the man page linked, there's example showing how to monitor for various events.\n"} {"question": "Is there any limit as to how many elements a2D integer arraycan contain inC?PS : I was expecting there would be some space limitations in declaring an array but could not find any such reference in the internet.\n", "answer": "It depends on yourRAMor the memory available for you.\n\ni:e:My program used to crash when I declared a global arraya[100000][10000], but this declaration is fine with the system now I have.\n"} {"question": "How can I stop the execution of a thread until a file is created ?I would like to avoid doing it in a busy loop, and use something with a behavior similar to select(). Is something like this possible?I only found ways to check if a file exists at a given time.\n", "answer": "You are probably looking forinotify(7). At the botton of the man page linked, there's example showing how to monitor for various events.\n"} {"question": "Is there any limit as to how many elements a2D integer arraycan contain inC?PS : I was expecting there would be some space limitations in declaring an array but could not find any such reference in the internet.\n", "answer": "It depends on yourRAMor the memory available for you.\n\ni:e:My program used to crash when I declared a global arraya[100000][10000], but this declaration is fine with the system now I have.\n"} {"question": "I came across this line of code written in C that confuses me coming from a JavaScript background.\n\n```\nshort s;\nif ((s = data[q])) \n return s;\n```\n\nIs this assigningstodata[q], and if it equals true/1, return s?\n", "answer": "Yes, an assignment...well assigns...but it's also an expression. Any value not equalling zero will be evaluated as true and zero as false.\n\nit would be the same as\n\n```\nif ((s = data[q]) != 0) return s;\n```\n"} {"question": "Consider inline assembly like this:\n\n```\nuint64_t flags;\nasm (\"pushf\\n\\tpop %0\" : \"=rm\"(flags) : : /* ??? */);\n```\n\nNonwithstanding the fact that there is probably some kind of intrinsic to get the contents of RFLAGS, how do I indicate to the compiler that my inline assembly clobbers one quadword of memory at the top of stack?\n", "answer": "As far as I am concerned, this is currently not possible.\n"} {"question": "Is ZeroMQ or RabbitMQ asynchronous, even when it is utilized in C programming?\n", "answer": "Yes, both ZeroMQ and RabbitMQ support asynchronous modes of operation, and this applies to the C client library implementations for both (as of this writing).\n"} {"question": "This question already has answers here:C: transitive (double) assignments(6 answers)Closed7 years ago.\n\nI came across this code today:\n\n```\nfor (i = 0; i < level; i++) {\n a[i] = b[i] = c[i] = 0;\n}\n```\n\nWhat is the meaning of the code located inside the for loop?\n", "answer": "```\na[i] = b[i] = c[i] = 0;\n```\n\nis parsed as:\n\n```\na[i] = (b[i] = (c[i] = 0));\n```\n\nand has the same effect as:\n\n```\na[i] = 0;\n b[i] = 0;\n c[i] = 0;\n```\n"} {"question": "Can I pass a character array tofopen? For example:\n\n```\nfopen(s, \"r\");\n```\n\nWheresis declared as a character array and is null terminated.\n", "answer": "smust be a pointer to a null terminated character array.\n\nTheman pagesconfirm this\n\n```\nFILE *fopen(const char *path, const char *mode);\n```\n\nYou can see that it must be null terminated, since nosizeargument is given.\n"} {"question": "Is ZeroMQ or RabbitMQ asynchronous, even when it is utilized in C programming?\n", "answer": "Yes, both ZeroMQ and RabbitMQ support asynchronous modes of operation, and this applies to the C client library implementations for both (as of this writing).\n"} {"question": "This question already has answers here:C: transitive (double) assignments(6 answers)Closed7 years ago.\n\nI came across this code today:\n\n```\nfor (i = 0; i < level; i++) {\n a[i] = b[i] = c[i] = 0;\n}\n```\n\nWhat is the meaning of the code located inside the for loop?\n", "answer": "```\na[i] = b[i] = c[i] = 0;\n```\n\nis parsed as:\n\n```\na[i] = (b[i] = (c[i] = 0));\n```\n\nand has the same effect as:\n\n```\na[i] = 0;\n b[i] = 0;\n c[i] = 0;\n```\n"} {"question": "Can I pass a character array tofopen? For example:\n\n```\nfopen(s, \"r\");\n```\n\nWheresis declared as a character array and is null terminated.\n", "answer": "smust be a pointer to a null terminated character array.\n\nTheman pagesconfirm this\n\n```\nFILE *fopen(const char *path, const char *mode);\n```\n\nYou can see that it must be null terminated, since nosizeargument is given.\n"} {"question": "```\nvoid func(int num){\n if(num< 3){\n printf(\"%d \", num);\n func(num+ 1);\n printf(\"%d \", num);\n }\n}\n```\n\nSuppose I call this function with func(0).\nWhy is the result 0 1 2 2 1 0 ? \nI don't know why it's decreasing.\n", "answer": "Here's a stack trace\n\n```\nf(0)\n print 0\n f(1)\n print 1\n f(2)\n print 2\n f(3) // 3 < 3 == false\n print 2\n print 1\n print 0\n```\n"} {"question": "Set PriorityWhat are all possible priorities in KPRIORITY in win kernel?\n", "answer": "From thedocumentation for KeQueryPriorityThread:\n\nThread priorities range from 0 to 31, where 0 is the lowest priority and 31 is the highest.\n"} {"question": "I've used OpenSSLBIGNUMto implement some cryptosystems and I am now wondering if it also offers big decimal support. I could not find anything in the documentation but perhaps there is an extension/add-on somewhere preferably in C (not C++)?\n\nNote: I am aware of GMP and NTL, I am not looking for those.\n", "answer": "Does OpenSSL offer Big Decimal support?\n\nNo.\n"} {"question": "From this page:http://linux.die.net/man/2/mprotect\n\nI understand the flags except for PROT_EXEC. What is the effect of calling\n\n```\nmprotect(ptr, size, PROT_EXEC);\n```\n", "answer": "From the manual page you link to:\n\nPROT_EXECThe memory can be executed.\n\nIt marks the memory as executable, meaning it can contain code you can call and run.\n"} {"question": "I would like a check box to be automatically unchecked when a certain value is reached. But I can't find an option to set the state of a check box\n", "answer": "Send it aBM_SETCHECKmessage:\n\n```\nSendMessage(hWndOfCheckbox, BM_SETCHECK, BST_UNCHECKED, 0);\n```\n\nAlternatively, use theButton_SetCheckmacro, that expands to the same call toSendMessage(but doesn't expose unused formal parameters):\n\n```\nButton_SetCheck(hWndOfCheckbox, BST_UNCHECKED);\n```\n"} {"question": "I want to compile several c files and I want to have executables whose names are same as the c file's names i.e if I have trial1.c, how can I have trial1.out?\n", "answer": "Do you want something like this?\n\n```\nfor i in *.c; do gcc ${i::1}.c -o ${i::1}.out; done\n```\n\nOr, if you are interested on just knowing if they compile successfully:\n\n```\nfor i in *.c; do gcc $i 2>/dev/null && echo \"$i : OK\" || echo \"$i : FAIL\"; done\n```\n"} {"question": "I know * indicates it is a pointer, but what's the difference betweenint (* a)[2]and(int (*)[2]) ainC?\n", "answer": "int (* a)[2];declaresaasa pointer to an array of twointwhile(int (*)[2]) acastsatoa pointer to an array of twoint.\n"} {"question": "How can I useperf_event_open()to retrieve callchain? I do not want to use the callchains provided by oprofile and perf. I want to get them directly. It seems that I need tommap()the file descriptor returned byperf_event_open(). I do not know the size ofmmap()and how to read from it.\n", "answer": "Chapter 8 ofthis bookdescribes, by example, how to useperf_event_open()for bothcountingandsamplingmodes.\n"} {"question": "In C, if the array is initialised while declaration then the dimension is optional. Why?\n", "answer": "Because if you tell it to create an array holding a1,2, and3, it can easily figure out the required size since you gave it 3 elements.\n"} {"question": "Given the following lines:\n\n```\nchar szInline[80];\nchar szDescription[80] = { NULL };\nfloat fCost = 0;\nsscanf (szInline, \"%80[^,], %f\", szDescription, &fCost);\n```\n\nWhat does the %80[^,] do?\n", "answer": "Read at most 80 chars up to the next,comma.\n\nBtw, theszDescriptionbuffer is too small by 1.\n"} {"question": "I know what a delimiter is, but what does the string\" \\t\\r\\n\\a\"stand for in the example below?\n\n```\n#define DELIMITER \" \\t\\r\\n\\a\"\n```\n", "answer": "```\n\\t = tab\n\\r = carriage return\n\\n = newline\n\\a = alert (bell)\n```\n\nLooks like the author was creating a preprocessor DEFINE containing these common delimiters.\n"} {"question": "What is maximum length of user space APC queue to one thread in Windows? I read Windows Internals 6 Part 1 and didn't finded any information about this.\n", "answer": "There is no fixed limit. KAPC structures are allocated fromnonpaged pooland linked to a thread by a singleLIST_ENTRYstructure. Nonpaged pool islimited by available system resources only.\n"} {"question": "As for System V messageint msgget(key_t key, int msgflg);,\n\nCan syscallreadwork likemsgsndto send a message?Can syscallwritework likemsgrcvto receive a message?\n", "answer": "No, they can't. The message queue identifier (returned bymsgget) is not a descriptor.\n\nDifferent sub-systems, different identifiers.\n"} {"question": "I have some operation like this C++ code that I want to convert in C89:\n\nreturn reinterpret_cast(stream.buffer) - buffer;\n\nHow can I replace the reinterpret cast in C?\n", "answer": "Nothing very exciting, you've seen this before:\n\n```\n(uint8_t *)(stream.buffer)\n```\n\nThat's the only way to cast something in C.\n"} {"question": "I've been programming in C for a while and i wondered why is important to separate this processes (Compile and Linking)?\n\nCan someone explain please?\n", "answer": "It is useful in order to decrease rebuilt time. If you change just one source file - it is often no need to recompile whole project but only one or few files.\n"} {"question": "This question already has answers here:How memory is allocated to macros in c?(4 answers)Closed7 years ago.\n\nDoes a macro allocate memory in a segment? If yes, in which memory segmentNUMBERis stored?\n\n```\n#define NUMBER 10\n```\n", "answer": "No, macros don't work like that.\n\nThey are substituted by thepreprocessor. Thecompilerdoesn't get to seeNUMBER. All it will see is the literal10.\n\nIn this respect, C and C++ are identical.\n"} {"question": "I would like to close a socket but before notify all threads blocking onaccept/connect, therefore I am sending a user specific signal, however not knowing the tid of the signal receiving threads. I cannot use syscallkill(pid, signal)\n", "answer": "Why not just shutdown the socket without notifying? Each thread that is blocked on accept or read from that socket will return with the corresponding error that you can parse to take the necessary actions\n"} {"question": "This question already has answers here:How memory is allocated to macros in c?(4 answers)Closed7 years ago.\n\nDoes a macro allocate memory in a segment? If yes, in which memory segmentNUMBERis stored?\n\n```\n#define NUMBER 10\n```\n", "answer": "No, macros don't work like that.\n\nThey are substituted by thepreprocessor. Thecompilerdoesn't get to seeNUMBER. All it will see is the literal10.\n\nIn this respect, C and C++ are identical.\n"} {"question": "```\n#define HELPER(param) Wazz ##param\n\nHELPER(hek)\n```\n\nDoing agcc -E filenameshows me\n\n```\nWazzhek\n```\n\nHow do I getWazz hek? How do I insert a space between the 2 tokens?\n\n```\n#define HELPER(param) Wazz ## ## ##param\n```\n\nDoesnt work either. Any suggestions?\n", "answer": "Just do not use token concatenation operator when you don't want to do token concatenation.\n\n```\n#define HELPER(param) Wazz param\n\nHELPER(hek)\n```\n"} {"question": "What is the quickest bit-hack to achieve the following result?\n\nLet x be a 4 byte int, in a C program.\n\nIf x is0x00000000, then x should be0xFFFFFFFF, else x should be untouched.\n", "answer": "x |= -(x == 0);x |= -!x;x = x ? x : 0xFFFFFFFF;if (x == 0)\n x = 0xFFFFFFFF;...\n\nBenchmark and choose what's appropriate for you\n"} {"question": "I know I can do this:\n\n```\n//With A = tax(x);\nreturn tan(arctan(A)/2);\n```\n\nbut I wanted something more efficient.\n", "answer": "Whenxis between -π/2 and π/2 you can use this formula:\n\n```\nt / (1 + sqrt(1 + t*t))\n```\n\nThis is hardly an improvement on the original formula, but it uses one function call instead of two.\n\nNote:I found this formulahere. The wikipedia page is in Russian, and the equivalent English page does not include the same formula.\n"} {"question": "I am reading lines from a file, the lines look like this:\n\n```\n89f81a03eb30a03c8708dde38cf:000391716\n```\n\nThe thing is: I want to remove everything after the:(including the:).\nI tried everything I could find online but they seem to useconst charand the lines arecharpointers.\n", "answer": "You can usestrchr:\n\n```\nchar str[] = \"89f81a03eb30a03c8708dde38cf:000391716\";\nchar *ptr;\n\nptr = strchr(str, ':');\nif (ptr != NULL) {\n *ptr = '\\0';\n}\n```\n"} {"question": "I am using char array to store data when using fscanf function, as there is no space to malloc the char* before the function. However, I need it to be pointer for next function as the input is set as char pointer. How can I do it?\n\n(Does it actually make sense?)\n", "answer": "Iffoois of typechar[n]for integraln, then you can use\n\n&foo[0]\n\nto give you the pointer to the zeroth element offoo. The type of this expression ischar*.\n"} {"question": "I am using char array to store data when using fscanf function, as there is no space to malloc the char* before the function. However, I need it to be pointer for next function as the input is set as char pointer. How can I do it?\n\n(Does it actually make sense?)\n", "answer": "Iffoois of typechar[n]for integraln, then you can use\n\n&foo[0]\n\nto give you the pointer to the zeroth element offoo. The type of this expression ischar*.\n"} {"question": "I want to dynamically load library from SD card, with dlopen, but when I do it, get error:\ndlopen failed: couldn't map \"/storage/emulated/0/Documents/Tests/armeabi-v7a/libtest.so\" segment 2: Operation not permitted\n\nWhen i use it for internal storage it's work.\nWhat can i do to solve this problem?\n", "answer": "This is disallowed by Android's security policy. Anyone can write to that location, so loading code from it is an easily exploitable attack vector.\n"} {"question": "My code:\n\n```\nPGresult *res = PQexec(m_IConnection, \"MOVE NEXT in my_cursor_name\");\n\nExecStatusType status = PQresultStatus(res);\n\nif (status != PGRES_COMMAND_OK)\n{\n PQclear(res);\n return;\n}\n```\n\nBut it does not fail after it reaches the last row.\nI've searched all over and can find no reference for detecting the end of rows.\n", "answer": "Per the first comment,\n\nif(!stricmp(PQcmdTuples(res), \"0\"))\n\nworks to check for the last row of the MOVE\n"} {"question": "I am building a C application that uses OpenCV.\n\nwhen compiling, I get the following error:\n\n```\nfatal error C1189: #error : core.hpp header must be compiled as C++\n```\n\nI did not find how to resolve this error.\n\nHow to use OpenCV from a C project?\n", "answer": "Select the required file.Launch its properties windowGoto C/C++ -> Advanced, and changeCompile astoCompile as C++ Code (/TP)\n\n\n"} {"question": "I need to create a function in which there is a default argument:\n\n```\nvoid func ( int a, int b = 1 );\n// and\nfunc (1, 2);\nfunc (1);\n```\n", "answer": "C doesn't support default arguments, though you can sometimes hack something like them using the preprocessor:\n\n```\nvoid func(int a, int b);\n#define TWO_ARGS(A, B, ...) A, B\n#define func(...) func(TWO_ARGS(__VA_ARGS__, 1))\n\nfunc(1, 2); /* calls func(1, 2); */\nfunc(1); /* calls func(1, 1); */\n```\n"} {"question": "I need to create a function in which there is a default argument:\n\n```\nvoid func ( int a, int b = 1 );\n// and\nfunc (1, 2);\nfunc (1);\n```\n", "answer": "C doesn't support default arguments, though you can sometimes hack something like them using the preprocessor:\n\n```\nvoid func(int a, int b);\n#define TWO_ARGS(A, B, ...) A, B\n#define func(...) func(TWO_ARGS(__VA_ARGS__, 1))\n\nfunc(1, 2); /* calls func(1, 2); */\nfunc(1); /* calls func(1, 1); */\n```\n"} {"question": "```\n#include \nint main()\n{\nint i;\ni=0;\nprintf(\"%d\\n%d\\n%d\\n\", i, &i, &(&i));\nreturn 0;\n}\n```\n\ni think that &i is just a value of address, and assume that it's 0xFF so &(&i)should be the address of 0xFF but why it's not valid?\n", "answer": "Unary&operator need an lvalue as its operand and returns an rvalue.&iis an rvalue, therefore&ican't be an operand of&.\n"} {"question": "if I have a pointer to an integer such as:\n\n```\nint num = 12;\nint *p = #\n```\n\nand then print the address so\n\n```\nprintf(\"%p\\n\", (void*)p);\n```\n\nWhat is the difference between the previous and this:\n\n```\nprintf(\"%p\\n\", (void*)&p);\n```\n", "answer": "Here,pcontains the address ofnum, so the firstprintfoutputs the address ofnum.\n\nOn the other hand,&pis the address ofp, so the secondprintfprints the address ofp.\n"} {"question": "I want to be able to do this:\n\n```\ntypedef int a[2], b[2], c[2];\n```\n\nwithout having to type the[2]. One solution is to do:\n\n```\ntypedef struct { int a[2] } a, b, c;\n```\n\nbut then you have to always do stuff likea.a[0]and that's no good.\n", "answer": "For C or C++98, a simple typedef will do:\n\n```\ntypedef int int2[2];\nint2 a, b, c;\n```\n"} {"question": "I have array defined like this\n\n```\nfloat array [1000][3]\n```\n\nI want to extract third column\n\n```\nfloat third[1000]\nfor (i = 0; i < 999,i++)\n```\n\nand then what?\n", "answer": "```\nfor (i=0; i<1000; i++)\n{\n third[i]=array[i][2]; \n}\n```\n\nThis should do it if I understood your question correctly.\n"} {"question": "I have array defined like this\n\n```\nfloat array [1000][3]\n```\n\nI want to extract third column\n\n```\nfloat third[1000]\nfor (i = 0; i < 999,i++)\n```\n\nand then what?\n", "answer": "```\nfor (i=0; i<1000; i++)\n{\n third[i]=array[i][2]; \n}\n```\n\nThis should do it if I understood your question correctly.\n"} {"question": "I have an array which is stored in my program memory\n\n```\nconst char* const paragraph[] PROGMEM = {\n \"First Line\",\n \"Second Line\"\n};\n```\n\nHow do I read one string at a time so that it output\n\n```\nFirst Line\nSecond Line\n```\n", "answer": "```\nint i;\nfor (i = 0; i < sizeof(paragraph)/sizeof(paragraph[0]); ++i) {\n printf(\"%s\\n\", paragraph[i]);\n}\n```\n"} {"question": "I have an array which is stored in my program memory\n\n```\nconst char* const paragraph[] PROGMEM = {\n \"First Line\",\n \"Second Line\"\n};\n```\n\nHow do I read one string at a time so that it output\n\n```\nFirst Line\nSecond Line\n```\n", "answer": "```\nint i;\nfor (i = 0; i < sizeof(paragraph)/sizeof(paragraph[0]); ++i) {\n printf(\"%s\\n\", paragraph[i]);\n}\n```\n"} {"question": "2d array declared by me.\n\n```\nstatic char daytab[2][13] = {\n {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},\n {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},\n };\n```\n\nI want address location of the element [1][5].\n\nWhen I use the statementchar *p = &daytab[1][5];it works but when I use pointer notationchar *p = &(*(*daytab+1)+5);then it shows error?\n", "answer": "That's becausea[i]is equivalent to*(a+i), not*a+i.\n"} {"question": "Can you use a pipe to share threads between two processes in C? I am writing my own shell and want to know if this implementation would be more optimal, if it is even possible?\n", "answer": "Each thread is specific to a process and share memory of the calling thread.\n\nIf you want efficient inter process communication, you can use shared memory.\n\nSeehttp://man7.org/linux/man-pages/man7/shm_overview.7.html\n"} {"question": "2d array declared by me.\n\n```\nstatic char daytab[2][13] = {\n {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},\n {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},\n };\n```\n\nI want address location of the element [1][5].\n\nWhen I use the statementchar *p = &daytab[1][5];it works but when I use pointer notationchar *p = &(*(*daytab+1)+5);then it shows error?\n", "answer": "That's becausea[i]is equivalent to*(a+i), not*a+i.\n"} {"question": "As far as i know, the only possible way to find largest number and lowest number if they array is not sorted by using linear search.\n\nis there any other option for this one? just want to know tho\n", "answer": "Since the value of a particular element in an unsorted collection tells you nothing about the value of adjacent elements, you need to inspect every value.\n\nAnd doing that is O(N).\n"} {"question": "As far as i know, the only possible way to find largest number and lowest number if they array is not sorted by using linear search.\n\nis there any other option for this one? just want to know tho\n", "answer": "Since the value of a particular element in an unsorted collection tells you nothing about the value of adjacent elements, you need to inspect every value.\n\nAnd doing that is O(N).\n"} {"question": "I need to use tcl.h in my C project (VS 2012) for registering function in SQLite. I have downloaded Tcl for windows and installed it. But my project still doesn't recognize when I write #include . What should I do to get access to this header?\nThanks in advance.\n", "answer": "Open the project properties and do :\n\n\n"} {"question": "I need to use tcl.h in my C project (VS 2012) for registering function in SQLite. I have downloaded Tcl for windows and installed it. But my project still doesn't recognize when I write #include . What should I do to get access to this header?\nThanks in advance.\n", "answer": "Open the project properties and do :\n\n\n"} {"question": "I need to use tcl.h in my C project (VS 2012) for registering function in SQLite. I have downloaded Tcl for windows and installed it. But my project still doesn't recognize when I write #include . What should I do to get access to this header?\nThanks in advance.\n", "answer": "Open the project properties and do :\n\n\n"} {"question": "I am usingrecv()to read data from a socket andfcntl()to set the socket blocking/non-blocking. My question is: If I calledrecv()(blocking) and I callfcntl()from another thread and set the socket non-blocking, will the currently runningrecv()return or the effect offcntl()will only take place after the blockingrecv()returns and I call it again?\n", "answer": "It won't affect the current receive operation.\n\nStrange thing to do.\n"} {"question": "Is there a way to go from the below\n\n```\nint a; ///< This is a variable\nint b = 3; ///< This is another variable\n```\n\nTo the below?\n\n```\nint a; ///< This is a variable\nint b = 3; ///< This is another variable\n```\n", "answer": "align_right_cmt_spanshould be the correct setting.\n"} {"question": "Is there a way to go from the below\n\n```\nint a; ///< This is a variable\nint b = 3; ///< This is another variable\n```\n\nTo the below?\n\n```\nint a; ///< This is a variable\nint b = 3; ///< This is another variable\n```\n", "answer": "align_right_cmt_spanshould be the correct setting.\n"} {"question": "Given an array whose elements are sorted, return the index of a the first occurrence of a specific integer. we have to do this in sub-linear time. I.e. do not just go through each element searching for that element.\ncan we solve this using binary search???\n", "answer": "you could perform a binary search on the array,it means the index the binary search resulted was not the first occurence.\n"} {"question": "The exposed API from c is:\n\n```\nbam_hdr_t *bam_hdr_init(void);\n```\n\nhow do I write its wrapper in Julia?\n\nccall((:bam_hdr_init,\"lib.so\"), Ptr{bam_hdr_t})works in Julia v0.5, but not in v0.4.\n", "answer": "ccall((:bam_hdr_init,\"lib.so\"), Ptr{bam_hdr_t},())works for both versions of Julia\n"} {"question": "Output is:10and it gives no error.\n\n```\nint main(){\n int j=10;\n int *i=&j;\n printf(\"%d\",*i);\n return 0;\n}\n```\n\nbut it gives me an error:\n\n```\nint main(){\nint *i;\nint j=10;\n*i=&j;\nprintf(\"%d\",*i);\nreturn 0;\n}\n```\n\nI understand that pointer de-referencing is causing the error. But how is that happening?\n", "answer": "Because you are using an uninitialized pointer.\nYour*i = &jshould bei = &j\n"} {"question": "I need to select one processor from my Comm to do some works ( I don`t want other processors do the work ). \nSince I split my Comm to the groups, I cannot always pick one specific rank ( for example 0) as my master. I need to choose it from my current comm. Any suggestion?\n\nThank you.\n", "answer": "The rank of a process is always relative to a communicator. After you split your processes, you can just take process 0 in the new communicator to perform the work you want.\n"} {"question": "FromSSL_CTX_load_verify_locations:\n\nSSL_CTX_load_verify_locations - set default locations for trusted CA certificates\n\nDoes this means I can put certificates in location (or file), which passed as parameter toSSL_CTX_load_verify_locationsfunction. And are these certificates automatically will be trusted?\n", "answer": "That is correct. This is how you specify the list of certificate authorities that are trusted.\n"} {"question": "Is using__MSDOS__enough with djgpp or should__DJGPP__be used instead?\n\nBy comparison, I know_WIN32isn’t defined by default on cygwin(based on the assumption djgpp and cygwin have the purpose to build an Unix layer to hide real OS details).\n\nI no longer have a DOS machine to test it.\n", "answer": "To list the predefined macros and their values, use\n\n```\ndjgpp -E -x c -dM /dev/null\n```\n"} {"question": "Is there a way to read a HH:MM format from a file usingfscanf(), and treat it like an int? The file has this format :\n\n```\n3 14:50 20.10\n```\n\nIs it possible to do something likefscanf(fp, \"%d ... %f, &a, &b, &c);andbwill have 1450?\n", "answer": "I'm afraid you can't do this in a line. However, you can:\n\n```\nfscanf(fp, \"%d %d:%d %f\", &a, &b1, &b2, &c);\nb = b1 * 100 + ((b1 > 0) * 2 - 1) * b2; // in case b1, b2 are the different sign.\n```\n"} {"question": "I have a pointer*pthat points to astruct S.Shas various fields.\n\nIs it possible to assign structureSto the structure pointed to by*pusing only one assignment?OR,do I need to assign the fields, one by one?\n", "answer": "This example assigns a struct using a pointer and one statement.\n\n```\nint main(void) {\n\n struct Foo {\n char a;\n int b;\n double c;\n } *foo, *bar;\n\n foo->b = 10;\n bar = foo; /* now bar->b=10 as well */\n}\n```\n"} {"question": "I need to determine x from the expression root(y).\n\n\"Y\" has a range to its separated value with maximum 10^1000.\nI solved it in the normal way and I saw the right result. But when Y is very large, the program outputs the wrong answer.\n\n```\n#include\n#include\nint main()\n{\n long long int x,y;\n scanf(\"%lld\",&y);\n x=sqrt(y);\n printf(\"%lld\",x);\n return 0;\n}\n```\n", "answer": "Use some bignum library, for exampleGMP\n"} {"question": "As show in the following code, what is the difference between 0 and CVMX_FAU_REG_64_ADDR(0) in the cvmx_fau_reg_64_t?\n\n```\n#define CVMX_FAU_REG_64_ADDR(x) ((x <<3) + CVMX_FAU_REG_64_START)\ntypedef enum\n{\n CVMX_FAU_REG_64_START = 0, \n CVMX_FAU_REG_64_END = CVMX_FAU_REG_64_ADDR(0),\n} cvmx_fau_reg_64_t;\n```\n", "answer": "In the code as written, both values == 0. There is no difference in the actual value.\n"} {"question": "Is there in C/C++ standart constant that reflects how many bits are there in one byte (8)? Something like CHAR_BIT but for byte.\n", "answer": "According to the C standard, acharis one byte. ThereforeCHAR_BITis the number of bits in a byte.\n\nThe C standard says thatCHAR_BITis\"number of bits for smallest object that is not a bit-field (byte)\".\n"} {"question": "\n\nI have a text like this. And I want to show it in doxygen documentation as it is.\nWhat type of command should I use.\n", "answer": "You can use verbatim, endverbatim.\n\nhttp://www.doxygen.nl/manual/commands.html#cmdverbatim\n"} {"question": "If you useprintfsuch as:\n\n```\nprintf(\"Time as a basic string = %s\", ctime(&seconds));\n```\n\nThe output would be:\n\n```\nWed, 28 Oct 2009 11:35:37\n```\n\nHow do I store this output thatctimegenerates so that:\n\n```\nchar result[80] = ctime(&seconds);\n```\n\nWhatever I try just doesn't seem to work.\n", "answer": "You want to usectime_rinstead ofctime.\n\n```\nchar result[80];\nctime_r(&seconds, result);\n```\n"} {"question": "In C, what is the best way to ignore the commas when usingscanfon a number like 1,000,000?\n", "answer": "I would say the best way is tonotusescanffor this. At least not using any number formats.\n\nInstead read it as a string, then remove the commas, and finallyconvert to a number.\n"} {"question": "I am trying to build by gcc a simple C code using thread_create. To use thread_create(), which library should be \"#include\"d? Should I send also specific flags to the gcc?\n", "answer": "You can usepthread_createincluded in, for more information, see the manpage ofpthread_create, if you're on Linux you can typeman pthread_createin your terminal.\n"} {"question": "I am trying to build by gcc a simple C code using thread_create. To use thread_create(), which library should be \"#include\"d? Should I send also specific flags to the gcc?\n", "answer": "You can usepthread_createincluded in, for more information, see the manpage ofpthread_create, if you're on Linux you can typeman pthread_createin your terminal.\n"} {"question": "This command\n\n```\ngcc file.c -c\n```\n\noutputs me this\n\n```\nfile.o\n```\n\nhow to run above command so it outputs me object file with specified name for examplefile.dbg.o?\n", "answer": "That's it:\n\n```\ngcc -o file.dbg.o -c file.c\n```\n"} {"question": "We need check whetherstat()call willaccess Hard diskduring its operation?\n\ni coulnt find answer for above question.\n\ncan anyone help me on this?\n", "answer": "Sincestat(2)identifies the file with a pathname, the system has no option but to query the filesystem for the information.\n\nI suppose the information could happen to be in a cache, so actually hitting the disk might not happen for a particular call, but generally the system will need to perform I/O.\n"} {"question": "We need check whetherstat()call willaccess Hard diskduring its operation?\n\ni coulnt find answer for above question.\n\ncan anyone help me on this?\n", "answer": "Sincestat(2)identifies the file with a pathname, the system has no option but to query the filesystem for the information.\n\nI suppose the information could happen to be in a cache, so actually hitting the disk might not happen for a particular call, but generally the system will need to perform I/O.\n"} {"question": "We need check whetherstat()call willaccess Hard diskduring its operation?\n\ni coulnt find answer for above question.\n\ncan anyone help me on this?\n", "answer": "Sincestat(2)identifies the file with a pathname, the system has no option but to query the filesystem for the information.\n\nI suppose the information could happen to be in a cache, so actually hitting the disk might not happen for a particular call, but generally the system will need to perform I/O.\n"} {"question": "I want run a command write execlp function within c file in linux.\nI want to run the following command :\n\nls -l\n\nI can do ls command as follows :\n\nexeclp(\"/bin/ls\" , \"ls\", NULL)\n", "answer": "Add the option to the parameter list:\n\n```\nexeclp(\"/bin/ls\", \"ls\", \"-l\", NULL);\n```\n"} {"question": "This question already has answers here:Using pointers to iterate through argv[](6 answers)Closed7 years ago.\n\nIf I havechar **argshow can I loop through therowsof the array to determine how many there are?\n\nFor example, ifchar **args == {\"one\", \"two\", \"three\"}, how can I loop through each element, keeping count, and then return 3?\n", "answer": "Since yourargsis null-terminated, simply write\n\n```\nint i;\nfor (i = 0; args[i]; i++)\n // do something\n```\n"} {"question": "I have a connected socket that I want to abortively close, but I do not want an RST to be sent to the other end. Can this be done?\n", "answer": "Your question embodies a contradiction in terms.\n\n'Abortively close' == RST.\n\nEven if the actual abortive close didn't send it immediately, TCP is obliged to send it on receipt of any other traffic for the connection, including data, ACKs, or even the peer's closing FIN.\n"} {"question": "I have a connected socket that I want to abortively close, but I do not want an RST to be sent to the other end. Can this be done?\n", "answer": "Your question embodies a contradiction in terms.\n\n'Abortively close' == RST.\n\nEven if the actual abortive close didn't send it immediately, TCP is obliged to send it on receipt of any other traffic for the connection, including data, ACKs, or even the peer's closing FIN.\n"} {"question": "Im curious if they have an official name or just 'dot' and 'arrow'? I try search this in cpluscplus and in Deitel, but didn't find anything\n", "answer": "The C standard calls themmember access operators, but only in the index. They aren't given a name anywhere else except the one place in the index. In the same place, the->operator is calledarrow operator,the.operator is calledstructure/union member operator.\n"} {"question": "I want to send duplicate string to my bison file.\n\nIn my flex file I use it like this\n\n```\n\"<\" {return strdup(tOPEN);}\n\n \">\" {return strdup(tCLOSE);}\n```\n\nIs this right things to do? \nOr should I use it like below the code.\n\n```\n\"<\" { yyval. sval = strdup(yytext); return tOPEN;}\n```\n", "answer": "```\n\"<\" { yyval. sval = strdup(yytext); return tOPEN;}\n```\n\nthis is the right way of the using.\n"} {"question": "If I open a text file withopen(\"file.txt\",O_RDONLY), do I need to close it withclose()?\n\nSilly question, I know, but I am not entirely sure if the end of a process leaves open files open.\n", "answer": "The file will remain open until you close it or your process terminates. The process terminating will invalidate the file descriptors for that process, and so in essence \"close\" the files.\n\nI would always close them explicitly, and as early as reasonable.\n"} {"question": "I want to get a integer from to user. But I wonder what is the difference betweenfscanf(stdin, \"%d\", &x);andscanf(\"%d\", &x);?\n", "answer": "What is the difference between stdin with fscanf and scanf?\n\nThescanffunction is equivalent tofscanfwith the argumentstdininterposed before the arguments toscanf. C11 §7.21.6.4 2\n\nSo aside from a different amount of typing the code, they are the same.\n"} {"question": "I have an array\n\n```\nchar msgID[16];\n```\n\nHow do I increment this by 1? I read the high and low 8 bytes into 2 differentuint64_tintegers\n\n```\nuint64_t high, low;\nmemcpy(&low, msgID, sizeof(uint64_t));\nmemcpy(&high, msgID + sizeof(uint64_t) , sizeof(uint64_t));\n```\n\nIf I do\n\n```\nlow += 1;\n```\n\nHow do I account for overflow?\n\nThanks for any help provided.\n", "answer": "It's quite simple, actually:\n\n```\nif(++low == 0)\n ++high;\n```\n"} {"question": "Since Lua 5.3, inegers are supported.\n\nBut how can I do :\n\n```\nif type( 123 ) == \"integer\" then\nend\n```\n\nOr\n\n```\nswitch( lua_type( L, -1 ) )\n{\ncase LUA_TINTEGER:\n break;\n}\n```\n\nSincetype()is still going to return\"number\"for both integer and reals, andLUA_TINTEGERdoes not exist ?\n\nThanks.\n", "answer": "usemath.typefor Lua 5.3\n\nReturns \"integer\" if x is an integer, \"float\" if it is a float, or nil\n if x is not a number.\n"} {"question": "I code in C and I am little weak in C++, in my research I came across many methods to read XML from URL for my win32 application. \nI found cURL andXmlTextReaderbut it's in C++.\nIs there any function or other ways, where I can download XML from the URL and parse that XML using only C language and not C++?\n\nI can work with C++ as well, but I want to avoid it as it's not I am comfortable with.\n", "answer": "Libcurlhas pure C API.Expatandlibxmlare written in pure C too.\n"} {"question": "I thought this would be easy, but google searching isn't turning up what I'm looking for. In C, how do I initialize an entire char array to a particular char, say,'N'? This is what I tried:\n\n```\nchar test[256] = {'N'};\n```\n\nBut this only initializes the first index to'N'and the rest to 0.\n", "answer": "Usememset:\n\n```\n#include \n\nchar test[256];\nmemset(test, 'N', 256);\n```\n"} {"question": "I thought this would be easy, but google searching isn't turning up what I'm looking for. In C, how do I initialize an entire char array to a particular char, say,'N'? This is what I tried:\n\n```\nchar test[256] = {'N'};\n```\n\nBut this only initializes the first index to'N'and the rest to 0.\n", "answer": "Usememset:\n\n```\n#include \n\nchar test[256];\nmemset(test, 'N', 256);\n```\n"} {"question": "In C, If I have:\n\n```\nchar *reg = \"[R5]\";\n```\n\nand I want\n\nchar *reg_alt = \"R5\"(equal to the same thing, but without the brackets), how do I do this?\n\nI tried\n\n```\n*char reg_alt = reg[1:2];\n```\n\nbut this doesn't work.\n", "answer": "There is no built-in syntax for dealing with substrings like that, so you need to copy the content manually:\n\n```\nchar res[3];\nmemcpy(res, ®[1], 2);\nres[2] = '\\0';\n```\n"} {"question": "Given the short notation to declare arrays, how do I specify the type of myArray to be arrays?\n\n```\n[] myArray = { //here [] should be array type\n {\"obj1, \"obj2\"}, \n {\"obj1, \"obj2\"}\n}\n```\n", "answer": "Assuming you want a two-dimensional array of character strings:\n\n```\nconst char *myArray[][2] = {\n {\"obj1\", \"obj2\"}, \n {\"obj1\", \"obj2\"}\n /* any other elements */\n};\n```\n"} {"question": "Is it good practice to use the weak attribute in production code so that for test code one can override functions?\n", "answer": "I don't know if it isgood practice, but there are ways to override functions in test code that do not interfere with production code:\n\nusing macros that redefine the function names you wish to overrideusingLD_PRELOADusing macros that expand to__weakin debug mode and to nothing in production mode.\n"} {"question": "Is it good practice to use the weak attribute in production code so that for test code one can override functions?\n", "answer": "I don't know if it isgood practice, but there are ways to override functions in test code that do not interfere with production code:\n\nusing macros that redefine the function names you wish to overrideusingLD_PRELOADusing macros that expand to__weakin debug mode and to nothing in production mode.\n"} {"question": "I have a problem in which I need to declare some variables as natural numbers. Which is the propper fundamental type that I should use for variables that should be natural numbers ? Like for integers is int ...\n", "answer": "The following types resemble natural numbers set with 0 included in C++:\n\nunsigned charunsigned short intunsigned intunsigned long intunsigned long long int, since C++11.\n\nEach one differs with the other in the range of values it can represent.\n"} {"question": "I have a problem in which I need to declare some variables as natural numbers. Which is the propper fundamental type that I should use for variables that should be natural numbers ? Like for integers is int ...\n", "answer": "The following types resemble natural numbers set with 0 included in C++:\n\nunsigned charunsigned short intunsigned intunsigned long intunsigned long long int, since C++11.\n\nEach one differs with the other in the range of values it can represent.\n"} {"question": "I was given a piece of code in C, and the question asked about it is whats wrong with it? I would be fine answering, but the asterisk in front of the malloc casting is confusing the heck out of me!\n\n```\nchar f() { return *(char*)malloc(10); }\n```\n", "answer": "The function returns an indeterminate value and has a memory leak because the dynamically allocated memory is not freed.\n"} {"question": "Need to send messages on PC without configured IP using MAC address in C language as a reply on PC's broadcast message. I suppose I should work with ethernet-header and use some (linux) kernel's structures and subroutines, however I couldn't find good links and samples about my question.\n", "answer": "Example of sending a raw Ethernet frame in Linux:\n\nhttps://gist.github.com/austinmarton/1922600\n"} {"question": "Need to send messages on PC without configured IP using MAC address in C language as a reply on PC's broadcast message. I suppose I should work with ethernet-header and use some (linux) kernel's structures and subroutines, however I couldn't find good links and samples about my question.\n", "answer": "Example of sending a raw Ethernet frame in Linux:\n\nhttps://gist.github.com/austinmarton/1922600\n"} {"question": "I currently have a code that checks whether a file is a directory or not, it goes as follows;\n\n```\nfile = readdir (dir);\n if(file->d_type & DT_DIR){\n \\* some code*\\\n }\n```\n\nI was wondering, what is the if statement for the exact opposite of this. Something along the line \"if file is not directory\".\n", "answer": "Any boolean expression can be negated with thenotoperator (!):\n\n```\nif (!(file->d_type & DT_DIR)) {\n```\n"} {"question": "```\n#include \nint main(void) \n {\n char c[] = \"Gate2011\";\n char *p = c;\n printf(\"%s\", p+p[3]-p[1]);\n return 0;\n}\n```\n\nOutput:2011\n\nWhy does it give this output? I tried different combinations and it always gives junk.\n", "answer": "becausep[3] = 'e' = 101andp[1] = 'a' = 97\n\n101 - 97 = 4\n\np + 4= address of \"2001\" in \"Gate2001\"\n\ninterpreted as string ... there you go.\n\nI also do not understand the downvotes :(\n\n\n"} {"question": "Is it possible to change the options in Clion so that the variables are aligned like so:\n\n\n\nThis should be applied in structs and methods.\n", "answer": "Yes.\n\nSettings -> Editor -> Code Style -> C/C++ -> Wrapping and Braces -> Variable groups -> Align in columns\n\nYou can of course also use a custom formatting tool that does it as well.\n"} {"question": "I want to assign ' to a character but it keeps giving me error\nany help?\n\n```\nvoid main()\n {\n char c = ''';\n }\n```\n", "answer": "Special characters like ' or \\ must be escaped with a backslash in these situations. In this particular case you got an error because the compiler thinks you opened and closed a null character with the first two '' and then opened another character without closing it with the third one.\n"} {"question": "I have a makefile, called \"Makefile\", and some target in it like:\n\n```\nfile.o: file.c Makefile\n gcc file.c\n```\n\nWhat exactly doesfile.o: file.c Makefiledo?\n", "answer": "That line describes the dependencies forfile.o.\n\nIf any file listed after the:(file.candMakefilein this case) has been modified later thanfile.o, thenfile.ois rebuilt according to the command in the following line.\n"} {"question": "I have a makefile, called \"Makefile\", and some target in it like:\n\n```\nfile.o: file.c Makefile\n gcc file.c\n```\n\nWhat exactly doesfile.o: file.c Makefiledo?\n", "answer": "That line describes the dependencies forfile.o.\n\nIf any file listed after the:(file.candMakefilein this case) has been modified later thanfile.o, thenfile.ois rebuilt according to the command in the following line.\n"} {"question": "Is it possible for a function in a linux kernel module calling a function in another module ?\n", "answer": "Yes. Of course, the other kernel module must be loaded.\n\nFor an example, look at the USB code, which is implemented as a mullti-layer driver, with each layer in its own module.Reference linkhere.\n"} {"question": "I've searched the standard but didn't notice the mentioned part.\n\nIs it just \"anything but 0\" and 1 or it is compiler-dependent?\n", "answer": "The result of the logical negation operator!is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has typeint.\n\nAppears in C89/C90, C99, and C11.\n"} {"question": "This question already has answers here:Freeing global variable(2 answers)Closed7 years ago.\n\nSay I declare a global arrayint arr[10];Should I free it somehow in the end?\n", "answer": "You need not free it.You should usefree()only when you have usemalloc().\n"} {"question": "This question already has answers here:Freeing global variable(2 answers)Closed7 years ago.\n\nSay I declare a global arrayint arr[10];Should I free it somehow in the end?\n", "answer": "You need not free it.You should usefree()only when you have usemalloc().\n"} {"question": "why this code is showing value of a = 1120403456 (may be garbage) in Dev-C++.\n\n```\n#include\nint main()\n{\n int a=5;\n float * pf;\n pf=(float *)&a;\n *pf=100.0;\n printf(\"%d\",a);\n return 0;\n}\n```\n", "answer": "The floating point number 100.0 is represented as 0x42C80000 in memory, which in decimal is 1120403456. You're printing out the 32-bit integer representation of 100.0.\n"} {"question": "How does the commandls -lcount the number of hard links of an inode?\nDoes it use the Linux API or is it code that requires deeper knowledge of the Linux kernel source code?\n\nI am not, yet, able to understand the source code ofls, because I just started learning C.\n", "answer": "It callsstatto get information about the file (in astruct stat). Then it looks at thest_nlinkfield of thestruct stat.\n"} {"question": "lets say I have two int arrays, array1 and array2.\n\nIs this line:\n\n```\narray1[i++] = array2[j++];\n```\n\nequal to this:\n\n```\narray1[i] = array2[j];\ni++;\nj++;\n```\n\n?\n", "answer": "Yes they are equivalent,unlessyou've written#DEFINE i jor#DEFINE j i, in which case the behaviour of the first snippet isundefined.\n"} {"question": "There is an option '-fshort-double' in GCC, Clang does not understand it. Is there some analog of this option for Clang 3.7 ?\n", "answer": "in looking at the web page:https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html#Option-Summary,\n\nthere is no-fshort-doubleoption ingcc.\n\ntherefore, the option is not valid to begin with.\n\nsuggest removing that option when changing toclang\n"} {"question": "I am trying to obtain a number of bits from a byte in C. Currently I am doing so by shifting and then bit masking (0xFF), however the shifting operator is taking a long time. Is there another way to this using only bitwise operations? And if so how?\n\nThanks!\n", "answer": "If you want to move a particular (single) bit to the least-significant position, you can use a hack like this:\n\n```\n(x & mask) != 0\n```\n\nwheremaskselects the single bit.\n"} {"question": "I am trying to obtain a number of bits from a byte in C. Currently I am doing so by shifting and then bit masking (0xFF), however the shifting operator is taking a long time. Is there another way to this using only bitwise operations? And if so how?\n\nThanks!\n", "answer": "If you want to move a particular (single) bit to the least-significant position, you can use a hack like this:\n\n```\n(x & mask) != 0\n```\n\nwheremaskselects the single bit.\n"} {"question": "What is the asmjit equivalent ofmov eax,[ecx+0CC]?\n\nThis is close:c.mov_ptr(x86::eax, x86::ptr(x86::ecx, 0x0CC)); but the arguments are wrong.\n\nAny ideas?\n", "answer": "The answer is:\n\na.mov(x86::eax, x86::ptr(x86::ecx, 0x0CC));\n"} {"question": "How do I return a double without gettingrounded:\n\n```\nint function() {\n double d = 5.894; \n printf(\"d=%f\\n\", d);\n return d;\n}\n\nint main() {\n double d = function();\n printf(\"d=%f\\n\", d);\n return 0;\n}\n```\n\nThis gives me\n\n```\nd=5.894000\nd=5.000000\n```\n\nWhat am I missing here?\n", "answer": "Your function returns ٰintit must returndouble\n\nChange\n\n```\nint function()\n```\n\nto\n\n```\ndouble function()\n```\n"} {"question": "How do I return a double without gettingrounded:\n\n```\nint function() {\n double d = 5.894; \n printf(\"d=%f\\n\", d);\n return d;\n}\n\nint main() {\n double d = function();\n printf(\"d=%f\\n\", d);\n return 0;\n}\n```\n\nThis gives me\n\n```\nd=5.894000\nd=5.000000\n```\n\nWhat am I missing here?\n", "answer": "Your function returns ٰintit must returndouble\n\nChange\n\n```\nint function()\n```\n\nto\n\n```\ndouble function()\n```\n"} {"question": "I need to get the path of %APPDATA% in my c program, to save a file in%APPDATA%\\myprogram\\How can I do that ?\n", "answer": "You should be able to get that information throughgetenv, here is an example.\n\n```\n#include\n#include\n\nint main ()\n{\n char * app_data;\n app_data= getenv (\"APPDATA\");\n\n if (app_data!=NULL)\n printf (\"The appdata path is: %s\",app_data);\n\n return 0;\n}\n```\n"} {"question": "Is operator->allowed to use in C instead of.? Does its availability depend on compiler we are using? Is->operator available in the last C standard or does it come from the C++ standard? How those two differ?\n", "answer": "In C,c->mis equivalent to(*c).m. The parentheses are necessary since.has a higher precedence than*. Any respectable compiler will generate the same code.\n\nIn C++, unless->or*isoverloaded, the equivalence is as above.\n"} {"question": "Is operator->allowed to use in C instead of.? Does its availability depend on compiler we are using? Is->operator available in the last C standard or does it come from the C++ standard? How those two differ?\n", "answer": "In C,c->mis equivalent to(*c).m. The parentheses are necessary since.has a higher precedence than*. Any respectable compiler will generate the same code.\n\nIn C++, unless->or*isoverloaded, the equivalence is as above.\n"} {"question": "Is operator->allowed to use in C instead of.? Does its availability depend on compiler we are using? Is->operator available in the last C standard or does it come from the C++ standard? How those two differ?\n", "answer": "In C,c->mis equivalent to(*c).m. The parentheses are necessary since.has a higher precedence than*. Any respectable compiler will generate the same code.\n\nIn C++, unless->or*isoverloaded, the equivalence is as above.\n"} {"question": "I have a small Linux project written in C is it possible to analyze it with a SonarQube?\n", "answer": "According tohttps://en.wikipedia.org/wiki/SonarQube, it support c/c++, and is cross-platform, so you can do it I think.\n"} {"question": "Is there a simple lexer/parser for C language or a subset of it which is based on Flex/Bison?\n\nI have found some open source parsers for C (TCC, LCC, ...) but none of them are based on bison.\n", "answer": "There is aC11 grammarfor YACC (a predecessor of Bison), it should work with Bison (maybe some tweaks will be needed).\n\nGCC used to be based on Bison a long ago. GCC 3.4 source code contains afilewith C grammar.\n"} {"question": "I have a small Linux project written in C is it possible to analyze it with a SonarQube?\n", "answer": "According tohttps://en.wikipedia.org/wiki/SonarQube, it support c/c++, and is cross-platform, so you can do it I think.\n"} {"question": "I am doing vectorization using AVX intrinsics, I want to fill constant floats like1.0into vector__m256. So that in one register I got a vector{1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}Does anyone knows how to do it?\n\nIt is similar to this questionconstant float with SIMD\n\nBut I am using AVX not SSE\n", "answer": "The simplest method is to use_mm256_set1_ps:\n\n```\n__m256 v = _mm256_set1_ps(1.0f);\n```\n"} {"question": "This question already has answers here:C comma operator(4 answers)Closed7 years ago.\n\n```\nint a=3,1; \nint b=(5,4);\n```\n\nI am a beginner in c and I noticed in a book this type of initialization . what does thisinitialisationmean?\n", "answer": "int b = (5,4)will first evaluate 5 then 4. The last thing that is evaluated will be assigned to the variable. For example\n\n```\nint b = (5,4,3,2,1)\n```\n\nin this case the value of b will be 1.\n"} {"question": "This question already has answers here:C comma operator(4 answers)Closed7 years ago.\n\n```\nint a=3,1; \nint b=(5,4);\n```\n\nI am a beginner in c and I noticed in a book this type of initialization . what does thisinitialisationmean?\n", "answer": "int b = (5,4)will first evaluate 5 then 4. The last thing that is evaluated will be assigned to the variable. For example\n\n```\nint b = (5,4,3,2,1)\n```\n\nin this case the value of b will be 1.\n"} {"question": "I was looking into a code snippet and saw below statement. How will below statement evaluated?\n\n```\nx= 5|(high == 1 ? y : high == 0 ? z:0);\n```\n", "answer": "The expression\n\n```\nx= 5|(high == 1 ? y : high == 0 ? z:0);\n```\n\nis evaluated as\n\n```\nx= 5|( high == 1 ? y : (high == 0 ? z:0) );\n```\n\nIt has similar effect as that of\n\n```\nif(high == 1) \n x = 5|y;\nelse if(high == 0)\n x = 5|z; \nelse \n x = 5|0;\n```\n"} {"question": "Hi I want to declare a 12 bit variable in C or any \"unconventional\" size variable (a variable that is not in the order of 2^n). how would I do that. I looked everywhere and I couldn't find anything. If that is not possible how would you go about saving certain data in its own variable.\n", "answer": "Use a bitfield:\n\n```\nstruct {\n unsigned int twelve_bits: 12;\n} wrapper;\n```\n"} {"question": "Say if you have the following IP address:\n\n```\n192.168.0.255\n```\n\nHow can I store that human readable IP address into astruct in_addr? I'm brand new to network programming in C at this low level, so any help would be greatly appreciated.\n", "answer": "You can do\n\n```\nstruct in_addr p;\ninet_aton(\"192.168.0.255\", &p.s_addr);\n```\n"} {"question": "I Would like to know how I can do exponent function in this code part (that means how I can change ^ to something that works in c language)?\n\n```\nK = (S * (P/100/12)) / (1 - (1 + (P/100/12))^(-Y*12) );\n```\n", "answer": "It's thepow()function frommath.h\n\n```\nK = (S * (P / 100 / 12)) / (1 - pow((1 + (P / 100 / 12)), (-Y * 12)));\n```\n"} {"question": "I'm working on a C grammar analysis program. While running C preprocessor, there are some libraries which check the environment and use#errorto stop compiling. How can I disable them, since I only need the preprocess step to finish?\n", "answer": "Why do you want to disable them? They are outputting an error and stopping compilation for a reason. The only way I know to disable them is to modify the source code and remove them.\n"} {"question": "I'm working on a C grammar analysis program. While running C preprocessor, there are some libraries which check the environment and use#errorto stop compiling. How can I disable them, since I only need the preprocess step to finish?\n", "answer": "Why do you want to disable them? They are outputting an error and stopping compilation for a reason. The only way I know to disable them is to modify the source code and remove them.\n"} {"question": "I am using GDB(peda-gdb) to debug a program, can I write something in a heap address so when the program reach that address It can read it out? I know the address but I do not know how to write something in that address. Thanks.\n", "answer": "You can write to the heap using C syntax, with commands that evaluate an expression likeprintorset var. For example, to write an integer value to a specific location:\n\n```\n(gdb) set var *(int *)0xYOURADDR = 23\n```\n"} {"question": "```\nmain()\n{\nint a,b=0,c=1,d=1;\na=++b&&++c||++d; \nprintf(\"%d %d %d\",b,c,d); //1 2 1\nb=0,c=1,d=1;\na=b&&++c||++d;\nprintf(\"%d %d %d\",b,c,d); //0 1 2\n}\n```\n\nWhy second printf gives answer 0 1 2 instead of 0 2 1 ?\n", "answer": "Why second printf gives answer 0 1 2 instead of 0 2 1 ?\n\n&&isshort-circuiting.\n\nIn\n\n```\na=b&&++c||++d;\n```\n\n++cwill not be evaluated ifbis0which is the case here. Hencecis1instead of2.\n"} {"question": "The sizeof(char) in C gives 1 and sizeof(\"a\") gives 2. Please help\n", "answer": "Achari.e. a character has size 1.\n\nThestring literal\"a\"isnota character. It is a \"string\" (and by string I meanchar[]). All \"strings\" in C are null-terminated, so your \"string\" is actually:\n\n```\n{'a','\\0'}\n```\n\nAnd that's two characters. So size is 2.\n"} {"question": "I found that a single-linelanguage: c.travis.yml file basically does all I need, with the exception that I don't wantmake testto happen. Is there a way I could make Travis just run./configure && make?\n", "answer": "Have you tried overriding the default test script as described in:https://docs.travis-ci.com/user/languages/c#Default-Test-Script?\n\nSomething like:\n\n```\nscript:\n ./configure && make\n```\n"} {"question": "I have a memory address integer like this 0x80480ac and i want to assign it a char * like this:\n\n```\nchar *address=\"\\x08\\x04\\x80\\xac\";\n```\n\nHow can i do it?\n", "answer": "I believe you are looking for:\n\n```\nchar * address = (char *)0x080480ac;\n```\n"} {"question": "I found that a single-linelanguage: c.travis.yml file basically does all I need, with the exception that I don't wantmake testto happen. Is there a way I could make Travis just run./configure && make?\n", "answer": "Have you tried overriding the default test script as described in:https://docs.travis-ci.com/user/languages/c#Default-Test-Script?\n\nSomething like:\n\n```\nscript:\n ./configure && make\n```\n"} {"question": "I have a memory address integer like this 0x80480ac and i want to assign it a char * like this:\n\n```\nchar *address=\"\\x08\\x04\\x80\\xac\";\n```\n\nHow can i do it?\n", "answer": "I believe you are looking for:\n\n```\nchar * address = (char *)0x080480ac;\n```\n"} {"question": "Can someone explain mecmpfuncwhich is used in theqsortfunction? What areaandbin this function and what are they pointing to?\n\n```\nint cmpfunc(const void *a, const void *b)\n{\n return(*(int*)a - *(int*)b);\n}\n```\n", "answer": "aandbincmpfuncare pointers toconst voidtype.cmpfunccan accept pointer to elements of array of any data type.void *pointer can't be dereferenced, therefore a castint *is needed before dereferencing.\n"} {"question": "I want to display \"string pointer affected\" but I get an error. Here is my code:\n\n```\n#include\n\nmain()\n{\n char* *p;\n\n char * s=\"string pointer affected\";\n\n *p=s;\n\n printf(\"%s\",*p);\n}\n```\n", "answer": "pdoesn't point to any known location, so writing to*pis a bad idea.\n\nYou mean to say:\n\n```\np = &s;\n```\n"} {"question": "I want to display \"string pointer affected\" but I get an error. Here is my code:\n\n```\n#include\n\nmain()\n{\n char* *p;\n\n char * s=\"string pointer affected\";\n\n *p=s;\n\n printf(\"%s\",*p);\n}\n```\n", "answer": "pdoesn't point to any known location, so writing to*pis a bad idea.\n\nYou mean to say:\n\n```\np = &s;\n```\n"} {"question": "I've been trying to make a program to input two numbers from the user.The XCode application is showing error as\n\nData argument not used by format string\n\nHow am I supposed to get over this? \nplease help \nthanks\n\n\n", "answer": "just type%dinside the(\"Here is my number %d\",Num)\n\nYou can find more formats here:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html\n"} {"question": "I want initialize a function pointer so that it is null. Which of these two ways is preferred?\n\n```\nvoid (*Pointer)(void) = NULL;\n```\n\nOr\n\n```\nvoid (*Pointer)(void) = (void (*)(void))0;\n```\n", "answer": "0is implicit convertible to any pointer type. Though how your compiler implementsNULLdepends.\n\nIn your code you can simply write\n\nvoid (*Pointer)(void) = 0;but it won't be portable , so writevoid (*Pointer)(void) = NULL;\n"} {"question": "Within a function, we have the following:\n\n```\n__asm__(\"movl $0xe4ffffe4, -4(%ebp)\");\n```\n\nDoes this mean that we move the contents of the memory address 0xe4ffffe4 over to the ebp register?\n", "answer": "This:\n\n```\nmovl $0xe4ffffe4, -4(%ebp)\n```\n\nSays \"move the 4-byte value 0xe4ffffe4 into the slot 4 bytes before the address stored in register ebp.\"\n"} {"question": "I am working on small project using Arduino. I have this char array which used to store some values. the problem is How to set this char array to null after assign some values in Arduino?\n\n```\nchar packetBuffer[200]\n```\n", "answer": "Usememsetfromstring.h:\n\n```\nmemset(packetBuffer, 0, sizeof packetBuffer);\n```\n"} {"question": "How do i make the printf(\"%d, veck[i]); print out all 100 numbers of the array instead of only 1-10?\n\n```\nint vek[100];\n for(int a=0;a<10;a++){\n for(int i=0;i<10;i++){\n printf(\"%d \", vek[i]); //only shows numbers 1-10\n }\n printf(\"\\n\");\n }\n```\n", "answer": "You should change the index of vek.\n\n```\nprintf(\"%d \", vek[10* a + i]);\n```\n"} {"question": "How can I open a file in an ext2 file system. For example, lets say I want to open the file:/a/b/c.txt\n\nI'm looking at the functions here:http://www.nongnu.org/ext2-doc/ext2.html\n", "answer": "The same as any other filesystem: usefopen(\"/path/to/the/file\", \"r\")or similar.\n\nThe documentation you found is only relevant to people implementing the filesystem.\n"} {"question": "In the following floor loop, how wouldsum += n --be evaluated? I'm very, very confused...\n\n```\nint sum;\nfor(sum=0;n>0;sum+=n--);\n```\n", "answer": "Forsum += n--the following operations are performed\n\naddntosumdecrementn\n\nWithsum += --n\n\nnis decrementedthe new value ofnis added tosum\n\nn--is calledpostdecrement, and--nis calledpredecrement\n"} {"question": "The following code:\n\n```\n#include \n#include \n#include \n\nint main()\n{\n pid_t mypid = getpid();\n write(1, &mypid, sizeof(pid_t));\n return 0;\n}\n```\n\nPrints gibberish instead of actual pid. Why?\n", "answer": "write(..will not print formatted text, but rather binary output directly to a file descriptor.\n\nJust useprintforfprintf:\n\n```\nfprintf(stdout, \"%d\", (int) mypid);\n```\n"} {"question": "How can I remove, in C, a part of a string? I am interested especially in a built-in function, or an efficient code to do it.\nI have this line of code:\n\n```\nchar namefile[256] = \"/Users/student/Desktop/Silviu/g7.08e11.01024\"\n```\n\nand I want to keep only \"g7.08e11.01024\" so I can use it somewhere else.\n", "answer": "Usestrrchr:\n\n```\nconst char* shortName = strrchr(namefile, '/') + 1;\n```\n\nstrrchrreturns the address of the last occurence of/in the string.\n"} {"question": "How can I remove, in C, a part of a string? I am interested especially in a built-in function, or an efficient code to do it.\nI have this line of code:\n\n```\nchar namefile[256] = \"/Users/student/Desktop/Silviu/g7.08e11.01024\"\n```\n\nand I want to keep only \"g7.08e11.01024\" so I can use it somewhere else.\n", "answer": "Usestrrchr:\n\n```\nconst char* shortName = strrchr(namefile, '/') + 1;\n```\n\nstrrchrreturns the address of the last occurence of/in the string.\n"} {"question": "here is my CMakeLists.txt:\n\n```\ncmake_minimum_required(VERSION 3.3)\nset(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -std=c11\")\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++11\")\nadd_executable(ex ex.c)\ntarget_link_libraries(ex xdo)\n```\n\nthe full code ishere\n\nof course, the libxdo.so and xdo.h is exist\n", "answer": "the checked answer is wrong, the right solution is:\n\n```\n#define __USE_XOPEN\n#include \"unistd.h\"\n#include \n```\n"} {"question": "Header file math.h is for mathematical functions like cos,sin, tan..\nBut how to write the ln function and not log?\n", "answer": "The C functionlogis the natural logarithm, which mathematicians usually write as \"ln\".\n\nThe C functionlog10is the logarithm base 10, which is sometimes written \"log\".\n"} {"question": "here is my CMakeLists.txt:\n\n```\ncmake_minimum_required(VERSION 3.3)\nset(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -std=c11\")\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++11\")\nadd_executable(ex ex.c)\ntarget_link_libraries(ex xdo)\n```\n\nthe full code ishere\n\nof course, the libxdo.so and xdo.h is exist\n", "answer": "the checked answer is wrong, the right solution is:\n\n```\n#define __USE_XOPEN\n#include \"unistd.h\"\n#include \n```\n"} {"question": "```\n#include\n#include\nvoid main()\n{\n char *a=\"12345\"; //Add number of that string\n}\n```\n\n\n\nHow can i add number of that string\n\nexample :\n\n```\nsum=1+2+3+4+5\n\nsum=15\n```\n\nHow can i do that?\n", "answer": "```\nint sum = 0;\nchar *a = \"12345\";\n\nwhile (*a) {\n sum += *a - '0';\n a++;\n}\n\nprintf(\"sum=%d\\n\", sum);\n```\n"} {"question": "Discovering gateway devices process using miniupnp is as follows:\n\nCallupnpDiscover(...)to find all available devices which support UPnP protocol.CallUPNP_GetValidIGD(...)to get first gateway from this list.\n\nIs there any solution to getallgateways from list, obtained in step 1?\n", "answer": "Made aforkof miniupnpc. Added routineGetValidConnectedIGDs, which returns list of all gateway devices found.\n"} {"question": "```\n#include\n#include\nvoid main()\n{\n char *a=\"12345\"; //Add number of that string\n}\n```\n\n\n\nHow can i add number of that string\n\nexample :\n\n```\nsum=1+2+3+4+5\n\nsum=15\n```\n\nHow can i do that?\n", "answer": "```\nint sum = 0;\nchar *a = \"12345\";\n\nwhile (*a) {\n sum += *a - '0';\n a++;\n}\n\nprintf(\"sum=%d\\n\", sum);\n```\n"} {"question": "Discovering gateway devices process using miniupnp is as follows:\n\nCallupnpDiscover(...)to find all available devices which support UPnP protocol.CallUPNP_GetValidIGD(...)to get first gateway from this list.\n\nIs there any solution to getallgateways from list, obtained in step 1?\n", "answer": "Made aforkof miniupnpc. Added routineGetValidConnectedIGDs, which returns list of all gateway devices found.\n"} {"question": "I have four parameters, each an integer and I want to find the smallest. What is the quickest and/or simplest way to do it? I can probably do a bubble sort but it seems overkill.\n", "answer": "```\nint min(int a, int b){\n return a\n main()\n {\n int a=400*400/400;\n if(a==400)\n printf(\"Do good\");\n else\n printf(\"Have good\");\n }\n```\n\noutput : Have Good\n", "answer": "I guess that on your platformintis 2 byte wide, 16 bit.\n\nThen\n\n```\n400*400 = 28928\n```\n\nDue to overflow\n\n```\n28928/400 = 72\n```\n"} {"question": "What is the Win32 API for sending messages between computers? I mean, what used to be achieved by the \"net send\" command and is now using \"msg\". I imagine it is some API over NetBIOS?\n", "answer": "Bothnet sendandmsguse theWTSSendMessage()function.\n"} {"question": "I have the following code, where we try to left shift certain bits of a value:\n\n```\nint main()\n{\n unsigned long mvb = 1;\n\n mvb << 8;\n printf(\"The shift value is %u\\n\", mvb);\n\n mvb << 56;\n printf(\"The shift value is %u\\n\", mvb);\n}\n```\n\nbut the result for all those two operation are both1, what is the reason, and how use it correctly?\n", "answer": "You need to assign it back to mvb after shifting like:\n\n```\nmvb = mvb << 8;\n```\n"} {"question": "What are the differences, if any, between\n\n```\n*a = b;\n```\n\nand\n\n```\na = &b;\n```\n\nAre these two different ways to make a var point to another var?\n", "answer": "No, they do not do the same thing.*a = b;does not changeabut it changes whatapoints to.a = &b;does changeabut it does not change whatapointed to.\n"} {"question": "Starting from\n\n```\nchar tval[20] = \"temp:26.62\";\n```\n\nhow can I add a space character untiltvalis filled? I need that in the end to obtain this:\n\n```\nchar tval[20] = \"temp:26.62 \";\n```\n", "answer": "Like this, probably\n\n```\nsize_t prevlen = strlen(tval);\nmemset(tval + prevlen, ' ', 19 - prevlen);\n*(tval + 19) = '\\0';\n```\n"} {"question": "There are some#definestatements in my C language code, and now i find some bug.\nBut the codeblocks IDE can not step into the #define block.\n\nso i want to get the Pre-compiled source code, which will expand the#definemacro.\n", "answer": "If you use the-Eoption of gcc, you can expand the macros to a C file, and then compile the C file.\n"} {"question": "Withfopen, by setting it towwill automatically clear the file for me. However now I'm trying to do the same thing withopen,\n\n```\nint file = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);\n```\n\nThis won't guarantee that the file is empty and write at the beginning(?). How can I achieve that?\n", "answer": "AddO_TRUNC- Initially clear all data from the file.\n"} {"question": "First time publishing hereSimple situation: In PUTTY, i have to create a file named admin.pid where it stores a PID when the user starts the \"app\" i'm creating. How can i do this? Thanks\n", "answer": "Get the PID usinggetpid().Open the file usingfopen().Write the PID to the file byfprintf().Close the file usingfclose().\n"} {"question": "There are some#definestatements in my C language code, and now i find some bug.\nBut the codeblocks IDE can not step into the #define block.\n\nso i want to get the Pre-compiled source code, which will expand the#definemacro.\n", "answer": "If you use the-Eoption of gcc, you can expand the macros to a C file, and then compile the C file.\n"} {"question": "Withfopen, by setting it towwill automatically clear the file for me. However now I'm trying to do the same thing withopen,\n\n```\nint file = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);\n```\n\nThis won't guarantee that the file is empty and write at the beginning(?). How can I achieve that?\n", "answer": "AddO_TRUNC- Initially clear all data from the file.\n"} {"question": "When you have the statement:\n\n*str++ = *end\n\nDoes the*strget assigned the value of*endor does it get incremented and then get assigned the value of*end?\n", "answer": "As apost-increment operator, it first assigns*endthen points to new/incremented address ofstr.\n"} {"question": "I'm learning C, and I am running into some problems which make me write (seemingly) redundant code. I am finding myself writing code like\n\n```\nprintf(\"%c\", someChar);\nprintf(\" \");\n```\n\nwhich (since it is in a loop) would output something like\n\n```\na b c\n```\n\nIs there any way to combine these print statements?\n", "answer": "just write :printf(\"%c \", someChar);\n\nnote the space after%c\n"} {"question": "Which numbers can a double type contain? (in C language)\nI was trying to find the numbers that double can contain in c.\nI know that a float can contain numbers between -10^38", "answer": "In C, adoubleisusuallyan IEEE double. I don't know if this is required by the standard, but these days it would be unusual for it to be something else. Here's some info on double precision formats, particularly IEEE:double-precision floating point formats\n"} {"question": "I have a simple C library that I compile to a.sofile on my linux machine. I'd like to do the same on my Mac, but after I compile and move the library to/usr/local/lib, but I'm not sure how to link it seeing asldconfigisn't a thing.\n\nHow would I go about doing this?\n", "answer": "While Linux has.sofiles, OSX has.dylibfiles. The process is similar, you just invoke compiler as in\n\n```\nclang -dynamiclib -o libname.dylib sources.c\n```\n"} {"question": "I have the following source:\n\n```\nint main() { 000J; }\n```\n\nWith gcc 4.8.4 it compiles without errors.\nI know there are suffixes like L or U, but I didn't find anything about J.\n\nSo what does it do?\n", "answer": "I get a warning:\n\nImaginary constants are a GNU extension\n\nTheJsuffix is a GNU extension, which causes the literal to be of a_Complextype.\n\nMore info here:https://gcc.gnu.org/onlinedocs/gcc/Complex.html\n"} {"question": "I have the following source:\n\n```\nint main() { 000J; }\n```\n\nWith gcc 4.8.4 it compiles without errors.\nI know there are suffixes like L or U, but I didn't find anything about J.\n\nSo what does it do?\n", "answer": "I get a warning:\n\nImaginary constants are a GNU extension\n\nTheJsuffix is a GNU extension, which causes the literal to be of a_Complextype.\n\nMore info here:https://gcc.gnu.org/onlinedocs/gcc/Complex.html\n"} {"question": "I create 100000 of such structs, by malloc'ing pointers to them.\n\n```\ntest_struct test {\n char value[100];\n}\n```\n\nDoes it mean that all char[100] variables (100 * 100000 ~ 10mb) will go to stack memory, exceeding it and causing my program to crash?\n", "answer": "No.\n\nWhen you allocate a struct on the heap, all of its members go on the heap as well.\n"} {"question": "Thesizeof(data_type)operator returns thenumber of bytesand notoctets, so the size of a byte may not be 8 bits. How can one identify the size of a byte in bits on any platform?\n", "answer": "I think you can dosizeof(type) * CHAR_BITto determine the number of bits. Include limits.h for the definition of CHAR_BIT.\n"} {"question": "If I dosizeof('r'), the character 'r' requires 4 bytes in memory. Alternatively, if I first declare acharvariable and initialize it like so:\n\n```\nchar val = 'r';\n printf(\"%d\\n\", sizeof(val));\n```\n\nThe output indicates that 'r' only requires 1 byte in memory.\n\nWhy is this so?\n", "answer": "This is because the constant'c'is interpreted as anint.\nIf you run this:\n\n```\nprintf(\"%d\\n\", sizeof( (char) 'c' ) );\n```\n\nit will print1.\n"} {"question": "Thesizeof(data_type)operator returns thenumber of bytesand notoctets, so the size of a byte may not be 8 bits. How can one identify the size of a byte in bits on any platform?\n", "answer": "I think you can dosizeof(type) * CHAR_BITto determine the number of bits. Include limits.h for the definition of CHAR_BIT.\n"} {"question": "If I dosizeof('r'), the character 'r' requires 4 bytes in memory. Alternatively, if I first declare acharvariable and initialize it like so:\n\n```\nchar val = 'r';\n printf(\"%d\\n\", sizeof(val));\n```\n\nThe output indicates that 'r' only requires 1 byte in memory.\n\nWhy is this so?\n", "answer": "This is because the constant'c'is interpreted as anint.\nIf you run this:\n\n```\nprintf(\"%d\\n\", sizeof( (char) 'c' ) );\n```\n\nit will print1.\n"} {"question": "I want to create a function like this but with priority. For that, I need the pid, but I don't know how to get it. Any idea?\n\nMine is to usesetpriority (0, pid, value), but I need the pid.\n\n```\nvoid cmd_exec(char * tr[]) {\n if (execvp(tr[0], tr)== -1)\n perror(\"Error\");\n}\n```\n", "answer": "To get the process-id of the calling process usegetpid().\n\nPlease find the\n\nLinux man-page here.current(Issue 7) POSIX documentation here.\n"} {"question": "I want to create a function like this but with priority. For that, I need the pid, but I don't know how to get it. Any idea?\n\nMine is to usesetpriority (0, pid, value), but I need the pid.\n\n```\nvoid cmd_exec(char * tr[]) {\n if (execvp(tr[0], tr)== -1)\n perror(\"Error\");\n}\n```\n", "answer": "To get the process-id of the calling process usegetpid().\n\nPlease find the\n\nLinux man-page here.current(Issue 7) POSIX documentation here.\n"} {"question": "```\n#include \n\nvoid foo();\nint main()\n{\n int b = 0;\n int a[6] = {1,2,3,4,5,6};\n foo();\n return 0;\n}\n\nvoid foo()\n{\n //write some code to print a and b\n}\n```\n\nMy Question is:\n\nHow to get the local variable from outside without pass any parameter ?\n", "answer": "That's not possible. You need to pass a pointer to it to access it from a function or make it global.\n"} {"question": "I want to know that how to print0as000and1as001in c and so on.\n\nI tried usingprintf(\"%3d\", var);but it doesn't seem to work\n\ncan anyone please suggest any method\n", "answer": "You can do this with\n\n```\nprintf(\"%03d\", var);\n```\n\nto provide a minimum field width of 3 padded with leading zeros. Don't forget the enclosing \"quotes\". If you had put them in your posted code:\n\n```\nprintf(\"%3d\", var);\n```\n\nit would have been padded with spaces.\n"} {"question": "```\nprintf(\"%d\",pow(5,3))\n```\n\nit's printing 0, and works fine when number is different from 5 why?\n\nCan anyone explain this ?\n", "answer": "The return type of the power function is double. using the double conversion specifier to prints the output of power function.\n\nthe conversion specifier for double is not \"%d\". It should be \"%f\".\n"} {"question": "I was debugging a C code and came across below expression. I want to know, \nhow below expression will be evaluated in c?\n\nx += y*2 != z;\n", "answer": "To figure out expressions like that start with theprecedence table:\n\nMultiplication has precedence of 3, so it will be evaluated first!=has precedence of 7, so it will be evaluated next+=has precedence of 14, so it will be evaluated last.\n\nTherefore,xwill be incremented by1ify*2is not equal toz.\n"} {"question": "This question already has answers here:What does this \">>=\" operator mean in C?(5 answers)Closed7 years ago.\n\nI know>>is Binary Right Shift Operator but what does>>=mean, like if I want Log2 onxI needwhile(x >>= 1) result++;.\n", "answer": "It's the bitwise shift right assignment operator;x >>= 1is equivalent tox = x >> 1.\n\n(It has the same precedence as assignment=).\n"} {"question": "This question already has answers here:What does this \">>=\" operator mean in C?(5 answers)Closed7 years ago.\n\nI know>>is Binary Right Shift Operator but what does>>=mean, like if I want Log2 onxI needwhile(x >>= 1) result++;.\n", "answer": "It's the bitwise shift right assignment operator;x >>= 1is equivalent tox = x >> 1.\n\n(It has the same precedence as assignment=).\n"} {"question": "How can I view C11 header files content of gcc compiler in CodeLite on Linux? if not possible, How/Where can I view them?\n\nPlease ignore this location en.cppreference.com/w/c/header since it's just documentary with no actual header file content\n", "answer": "All the system header files, including the standard C header files, are under/usr/include. You can open any of them with any editor, including the CodeLite editor.\n"} {"question": "I want to find straight lines marked in the image, the coordinates point A, point B is the beginning and end of the segment. Please help me!\nimg:enter image description heresource:enter image description here\n", "answer": "It is called the \"Hough Transform\"\n\nYou could experiment using something like Mathlab, and then implement it using opencv houghtransform.\n\nhttps://github.com/Itseez/opencv/blob/master/samples/cpp/houghlines.cpp\n"} {"question": "Assume there is a structfakes:\n\n```\nstruct fakes {\n....\n};\n```\n\nAnd there is a pointer:\n\n```\nstruct fakes *fakes;\n```\n\nI'm wondering whethersizeof(struct fakes)andsizeof(*fakes)are the same.\n", "answer": "I'm wondering whethersizeof(struct fakes)andsizeof(*fakes)are the same.\n\nYes, they are guaranteed to be the same.\n"} {"question": "What is the difference between\n\n```\nfloat f = (float) 99.32 ;\n```\n\nand\n\n```\nfloat f = 99.32f ;\n```\n\nBoth of them compiled and ran successfully.\n", "answer": "```\nfloat f = 99.32f ;\n```\n\nThat is afloatliteral, which means a float variable being assigned with afloatvalue directly.\n\n```\nfloat f = (float) 99.32 ;\n```\n\nThat is afloatvariable that is assigned adoublevalue that is cast tofloatbefore being assigned.\n"} {"question": "What is the difference between\n\n```\nfloat f = (float) 99.32 ;\n```\n\nand\n\n```\nfloat f = 99.32f ;\n```\n\nBoth of them compiled and ran successfully.\n", "answer": "```\nfloat f = 99.32f ;\n```\n\nThat is afloatliteral, which means a float variable being assigned with afloatvalue directly.\n\n```\nfloat f = (float) 99.32 ;\n```\n\nThat is afloatvariable that is assigned adoublevalue that is cast tofloatbefore being assigned.\n"} {"question": "In one of my assignments I am seeing this line used:\n\n```\nint index = -1, k;\n```\n\nIm not sure what is happening when there are to entries for the one variable. \nWhat exactly is the variable \"index\" holding when it has two entries?\n", "answer": "This is the definition of 2 variables, both of the same typeint:indexandk. Onlyindexis initialized with-1, andkis left un-initialized.\n"} {"question": "In one of my assignments I am seeing this line used:\n\n```\nint index = -1, k;\n```\n\nIm not sure what is happening when there are to entries for the one variable. \nWhat exactly is the variable \"index\" holding when it has two entries?\n", "answer": "This is the definition of 2 variables, both of the same typeint:indexandk. Onlyindexis initialized with-1, andkis left un-initialized.\n"} {"question": "Code:\n\n```\n#include \nint main()\n{\n long cn=1;\n char ch;\n while((ch=getchar())!=EOF)\n {\n printf(\"%ld\\t%c\\n\",cn++,ch);\n } \n}\n```\n\nWhen I input word \"secret\" and hit enter it shows count up to 7 and not 6,why?\n", "answer": "Because the \"enter\" character is read as well. This is in fact a \"newline\", ASCII code 10 (or hex 0A).\n"} {"question": "I am developing a code in c, which simply FTPs the files on FTP server by using curl utility, by following thisexample\n\nnow i have one simple thing to do, specify curl to use particular interface (IP) of the server for upload, as other interface of the server is associated with other socket connection.\n\nis there any way to do it?\n", "answer": "Seems like curl support--interfaceoption\n\n```\ncurl --interface eth0\n```\n"} {"question": "I am developing a code in c, which simply FTPs the files on FTP server by using curl utility, by following thisexample\n\nnow i have one simple thing to do, specify curl to use particular interface (IP) of the server for upload, as other interface of the server is associated with other socket connection.\n\nis there any way to do it?\n", "answer": "Seems like curl support--interfaceoption\n\n```\ncurl --interface eth0\n```\n"} {"question": "As per title, is there an equivalent ofpthread_barrier_ttype in windows? I' ve foundSYNCHRONIZATION_BARRIERbut seems available only since Windows 8.\n\nIs there something more portable?\n\nThanks\n", "answer": "Do it the old fashioned way before barriers were invented: with a counting semaphore\n"} {"question": "There is good documentation here (http://www.postgresql.org/docs/8.3/static/xfunc-c.html), but I didn't find a way to read/modify/delete data from existing table by tablename and columns name from C extension.\n", "answer": "I guess what you need isSPI.\n\nP. S. Do you actually use 8.3? Use the latest (9.4) if you're not restricted somehow.\n"} {"question": "In a single nibble (0-F) I can store one number from 0 to 15. In one byte, I can store a single number from 0 to 255 (00 - FF).\nCan I use a byte (00-FF) to store two different numbers each in the range 0-127 (00 - 7F)?\n", "answer": "The answer to your question is NO. Youcansplit a single byte into two numbers, but the sum of the bits in the two numbers must be <= 8. Since, the range 0-127 requires 7 bits, the other number in the byte can only be 1 bit, i.e. 0-1.\n"} {"question": "```\nint m,digit[100],i=0, n = 15;\nwhile(n)\n{\n m = n%2;\n digit[i] = \"0123456789abcdefghijklmnopqrstuvwxyz\"[m];\n n = n/2;\n}\n```\n\nI did not understand what is digit[i] = \"0123456789abcdefghijklmnopqrstuvwxyz\"[m];\n", "answer": "digit[i] =\"0123456789abcdefghijklmnopqrstuvwxyz\"[m];is themth letter of0123456789abcdefghijklmnopqrstuvwxyz.\n"} {"question": "When I resize my window and aWM_SIZEmessage is sent, does theWM_SIZEmessage get sent to the message queue or does the window procedure called directly?\n", "answer": "Resizing a window by mouse sendsWM_SIZEdirectly to the window procedure, it does not go through the message queue.\n"} {"question": "There is good documentation here (http://www.postgresql.org/docs/8.3/static/xfunc-c.html), but I didn't find a way to read/modify/delete data from existing table by tablename and columns name from C extension.\n", "answer": "I guess what you need isSPI.\n\nP. S. Do you actually use 8.3? Use the latest (9.4) if you're not restricted somehow.\n"} {"question": "In a single nibble (0-F) I can store one number from 0 to 15. In one byte, I can store a single number from 0 to 255 (00 - FF).\nCan I use a byte (00-FF) to store two different numbers each in the range 0-127 (00 - 7F)?\n", "answer": "The answer to your question is NO. Youcansplit a single byte into two numbers, but the sum of the bits in the two numbers must be <= 8. Since, the range 0-127 requires 7 bits, the other number in the byte can only be 1 bit, i.e. 0-1.\n"} {"question": "```\nint m,digit[100],i=0, n = 15;\nwhile(n)\n{\n m = n%2;\n digit[i] = \"0123456789abcdefghijklmnopqrstuvwxyz\"[m];\n n = n/2;\n}\n```\n\nI did not understand what is digit[i] = \"0123456789abcdefghijklmnopqrstuvwxyz\"[m];\n", "answer": "digit[i] =\"0123456789abcdefghijklmnopqrstuvwxyz\"[m];is themth letter of0123456789abcdefghijklmnopqrstuvwxyz.\n"} {"question": "When I resize my window and aWM_SIZEmessage is sent, does theWM_SIZEmessage get sent to the message queue or does the window procedure called directly?\n", "answer": "Resizing a window by mouse sendsWM_SIZEdirectly to the window procedure, it does not go through the message queue.\n"} {"question": "```\n#include \n\nint main(void)\n{\n char *s = \"Jordan\";\n printf(\"hello, %s\\n, s\");\n}\n```\n\nDoes anyone know a way that I can get this native C source code to work? I'm having trouble getting it to compile and run.\n", "answer": "Your second quote is in the wrong place. Try:\n\n```\nprintf(\"hello, %s\\n\", s);\n```\n"} {"question": "Does gethostbyaddr() function uses internet connection for converting ip address to hostname? Or it uses some cached data (like DNS cache)?\n", "answer": "Yes. It does a DNS lookup, which may be satisfied by the local resolver's cache or may not.\n"} {"question": "```\nvoid main()\n{\n int a;\n a=10;\n do\n while(a++<10);\n while(a++<=11);\n printf(\"%d\",a);\n}\n```\n\nThe above program gives an output of14.\nCan you please explain why?\n", "answer": "This code will make you understand why , Whenever you type a++ its always incremented\n\n```\nvoid main()\n{\n int a;\n a=10;\n do{\n while(a++<10);\n printf(\"%d\",a);\n}\n while(a++<=11);\n printf(\"%d\",a);\n}\n```\n"} {"question": "```\n#include \nvoid main()\n{\n char *s= \"hello\";\n char *p = s;\n\n printf(\"%c\\t%c\", p[0], s[1]);\n}\n```\n\noutput of this program is : h e\n\nCan anyone please explain how this program is working? I'm relatively new to c..\n", "answer": "p[0]is identical to*(p+0), similarly goes fors[1].[]always operates on a pointer and is same for arrays and pointers.\n\nNote- There is no array declared in your program.\n"} {"question": "```\n#include \nvoid main()\n{\n char *s= \"hello\";\n char *p = s;\n\n printf(\"%c\\t%c\", p[0], s[1]);\n}\n```\n\noutput of this program is : h e\n\nCan anyone please explain how this program is working? I'm relatively new to c..\n", "answer": "p[0]is identical to*(p+0), similarly goes fors[1].[]always operates on a pointer and is same for arrays and pointers.\n\nNote- There is no array declared in your program.\n"} {"question": "```\n#include \nvoid main()\n{\n char *s= \"hello\";\n char *p = s;\n\n printf(\"%c\\t%c\", p[0], s[1]);\n}\n```\n\noutput of this program is : h e\n\nCan anyone please explain how this program is working? I'm relatively new to c..\n", "answer": "p[0]is identical to*(p+0), similarly goes fors[1].[]always operates on a pointer and is same for arrays and pointers.\n\nNote- There is no array declared in your program.\n"} {"question": "I need to find the length of an array, how would I do this without using thesizeoffunction.\n\neg if\n\n```\nArray 1 = [0 1 2 3 4 5 6]\n```\n\nthe size of this array would be7.\n", "answer": "If you can't usesizeof(tell us why, please), you can use a loop and a sentinel (-1 or some number that can not be used in the array):\n\n```\nint arr[] = {0, 1, 2, 3, 4, 5, 6, -1};\nint count = 0;\n\nwhile (arr[count] != -1) count++;\n```\n"} {"question": "I need to find the length of an array, how would I do this without using thesizeoffunction.\n\neg if\n\n```\nArray 1 = [0 1 2 3 4 5 6]\n```\n\nthe size of this array would be7.\n", "answer": "If you can't usesizeof(tell us why, please), you can use a loop and a sentinel (-1 or some number that can not be used in the array):\n\n```\nint arr[] = {0, 1, 2, 3, 4, 5, 6, -1};\nint count = 0;\n\nwhile (arr[count] != -1) count++;\n```\n"} {"question": "I have an function address stored in anunsigned int, and a function pointer.\n\nNow i want thatfunction_pointerwill contain the value offunction_address\n\n```\nunsigned int function_address = 0xdeadbeef;\nvoid(*function_pointer)(void) = function_address; // not valid\n```\n\nhow to do that in C ?\n", "answer": "Perform an explicit cast.\n\n```\nvoid(*function_pointer)(void) = (void (*)(void))function_address;\n```\n"} {"question": "Is there any doc i can read about this kind of function?\n\n```\n// return the capital of char c\nchar a(char c){\n return c >= 'a' && c<='z' ?\n c +'A' - 'a':c;\n}\n```\n", "answer": "Read up on the ternary operator. :) And then it will be clear the code is doing:\n\n```\nif (c >= 'a' && c<='z') {\n return(c +'A' - 'a');\n} else {\n return c;\n}\n```\n\nSo basically it is capitalizing the Latin alphabet in ASCII.\n"} {"question": "This question already has answers here:Type of #define variables(7 answers)Closed7 years ago.\n\nWhen I define a numerical constant with#define(e.g.#define pi 3.141593) is it anint,float,doubleor what?\n", "answer": "Neither. It is a lexicographical replacement, that is, it will replacepiwith3.141593wherever it shows up.\n"} {"question": "I have an function address stored in anunsigned int, and a function pointer.\n\nNow i want thatfunction_pointerwill contain the value offunction_address\n\n```\nunsigned int function_address = 0xdeadbeef;\nvoid(*function_pointer)(void) = function_address; // not valid\n```\n\nhow to do that in C ?\n", "answer": "Perform an explicit cast.\n\n```\nvoid(*function_pointer)(void) = (void (*)(void))function_address;\n```\n"} {"question": "Is there any doc i can read about this kind of function?\n\n```\n// return the capital of char c\nchar a(char c){\n return c >= 'a' && c<='z' ?\n c +'A' - 'a':c;\n}\n```\n", "answer": "Read up on the ternary operator. :) And then it will be clear the code is doing:\n\n```\nif (c >= 'a' && c<='z') {\n return(c +'A' - 'a');\n} else {\n return c;\n}\n```\n\nSo basically it is capitalizing the Latin alphabet in ASCII.\n"} {"question": "Just curious, why below code is not equivalent to forever loop? Instead application crashes.\n\n```\nunsigned short i;\nfor (i = 1; i >= 0; i++)\n{\n printf(\"%d\\n\", i);\n}\n```\n", "answer": "The problem is solved. Antivirus Karspersky was analysing this exe file for nearly 20 seconds it looks. If I disable antivirus, it runs immediately. Thanks for all your inputs.\n"} {"question": "Just curious, why below code is not equivalent to forever loop? Instead application crashes.\n\n```\nunsigned short i;\nfor (i = 1; i >= 0; i++)\n{\n printf(\"%d\\n\", i);\n}\n```\n", "answer": "The problem is solved. Antivirus Karspersky was analysing this exe file for nearly 20 seconds it looks. If I disable antivirus, it runs immediately. Thanks for all your inputs.\n"} {"question": "How can we do transaction signing in mozilla firefox by loading PKCS#11 library to database.\nafter some research i found about capicom library. but the thing is this library does not support with windows7 and higher versions.\n", "answer": "you cannot use c code but you can do the same by java applets which are to be signed. Please referhttp://www.nakov.com/books/signatures/Java-for-Digitally-Signing-Documents-in-Web-book-Nakov.html\n"} {"question": "What happens in the follwing code, does program executes 'return 1' or exits before?\n\n```\nint cmd_quit(tok_t arg[]) {\n printf(\"Bye\\n\");\n exit(0);\n return 1;\n}\n```\n", "answer": "exit()ends the program, no matter what. So: no. In practice, a C runtime will always do something similar of\n\n```\nexit(main(argc, argv));\n```\n\nto execute your program.\n\n(meaning:ifmain()returns,exit()will be called automatically with its return value)\n"} {"question": "How do I get1.371429as01.37. Is it not%2.02f? I need to have a leading zero and also round it to two decimal places.\n", "answer": "Try this:\n\n```\n#include\n\nint main()\n{\n double a = 1.2345666;\n printf(\"%05.2lf\\n\", a);\n return 0;\n}\n```\n\nHere,05says \"print 5 columns with leading zeros\"..2says \"print decimal digits untill 2 columns\". 2 decimal digits + 1.+ 2 integer part => total 5 columns you have to print.\n"} {"question": "What happens in the follwing code, does program executes 'return 1' or exits before?\n\n```\nint cmd_quit(tok_t arg[]) {\n printf(\"Bye\\n\");\n exit(0);\n return 1;\n}\n```\n", "answer": "exit()ends the program, no matter what. So: no. In practice, a C runtime will always do something similar of\n\n```\nexit(main(argc, argv));\n```\n\nto execute your program.\n\n(meaning:ifmain()returns,exit()will be called automatically with its return value)\n"} {"question": "How do I get1.371429as01.37. Is it not%2.02f? I need to have a leading zero and also round it to two decimal places.\n", "answer": "Try this:\n\n```\n#include\n\nint main()\n{\n double a = 1.2345666;\n printf(\"%05.2lf\\n\", a);\n return 0;\n}\n```\n\nHere,05says \"print 5 columns with leading zeros\"..2says \"print decimal digits untill 2 columns\". 2 decimal digits + 1.+ 2 integer part => total 5 columns you have to print.\n"} {"question": "I have the following:\n\n```\nchar rank[100][100];\nint score = 5;\n\nstrcpy(rank[0], \"%d\" score);\n```\n\nHowever,strcpy()does not accept these arguments. Is there any way to append a formatted string into my array?\n", "answer": "You could usesprintf:\n\n```\nchar rank[100][100];\nint score;\n\nsprintf(rank[0], \"%d\", score);\n```\n\nNote however thatsnprintfis the buffer overflow-safe alternative.\n"} {"question": "For example there is a method dog:\n\n```\nvoid dog(char C,int N)\n{\n//here if I want to print the value of C with a print statement,how do I do that?\n}\n```\n", "answer": "What about a\n\n```\nprintf(\"the value of c = %c\\n\", C);\n```\n"} {"question": "How can I remove opened file in linux?\n\nIn shell I can do this:\n\n```\nrm -rf /path/to/file_or_directory\n```\n\nBut how can I do it in C?\n\nI don't want to usingsystem()function.\n\nI have seen unlink and remove method but it's haven't any flags to set force deletion.\n", "answer": "Theunlinkandremovefunctions force deletion. Thermcommand is doing extra checksbeforeit calls one of those functions. But once you answery, it just uses that function to do the real work.\n"} {"question": "How can I remove opened file in linux?\n\nIn shell I can do this:\n\n```\nrm -rf /path/to/file_or_directory\n```\n\nBut how can I do it in C?\n\nI don't want to usingsystem()function.\n\nI have seen unlink and remove method but it's haven't any flags to set force deletion.\n", "answer": "Theunlinkandremovefunctions force deletion. Thermcommand is doing extra checksbeforeit calls one of those functions. But once you answery, it just uses that function to do the real work.\n"} {"question": "please i can't understand the while loop , why the loop show A two time and not one\n\n```\nchar *s,*t;\ns=\"ABC\";\nt=\"AA\";\ndo {printf(\"A\");}\nwhile(*s++==*t++);\nprintf(\"%d %d\",*s-*t);\n```\n", "answer": "In your code\n\n```\nprintf(\"%d %d\",*s-*t);\n```\n\ninvokes undefined behavior as you're not supplying enough argument to sate the supplied format specifiers.\n"} {"question": "I am using the source file fromhttps://github.com/contiki-os/contikiI added a new directory (say/foo) that includes some .c and .h files\n\nI need to use them onexamples/cc26xx, although I included the .h files (under/foo) to cc26xx-demo.c, it doesn't really include the files when I runmake\n\ncan anyone tell me how do I need to include them either onexamples/cc26xx/MakefileorMakefile.include\n", "answer": "addingPROJECT_SOURCEFILES += mylib.cto Makefile solved the issue.\n"} {"question": "I am using the source file fromhttps://github.com/contiki-os/contikiI added a new directory (say/foo) that includes some .c and .h files\n\nI need to use them onexamples/cc26xx, although I included the .h files (under/foo) to cc26xx-demo.c, it doesn't really include the files when I runmake\n\ncan anyone tell me how do I need to include them either onexamples/cc26xx/MakefileorMakefile.include\n", "answer": "addingPROJECT_SOURCEFILES += mylib.cto Makefile solved the issue.\n"} {"question": "While I was looking for MMX functions, I noticed that two of them,_m_emptyand_mm_empty, haveexactly the same definition.\n\nSo why do they both exist ? Is one of them older than the other ? Is there a difference that is not mentioned in the manual ?\n", "answer": "Differences would/should be pointed out in the documentation. TheMSDNis more precise. They explicitly mention this:\n\nA synonym for_mm_emptyis_m_empty.\n"} {"question": "I want to reduce the resolution of a video from 1024*768 to 800*600.\nI found on the web ffmpeg, and the library swscale (I use in C.\n\nAnd I found some informations on the web, but nothing about how to reduce the resolution of a video nor about which functions to use\n\nHow can I do ?\n", "answer": "Seethisorthisexample code. Usesws_getContext() to set up a scaler, andsws_scale() to convert one frame or slice.\n"} {"question": "I just created new console application project byDev-C++ 4.9.9.2. But Project Options(Alt+P) not working andError: Access violation at address 0012F64B. Write of address 0012F64B. How to fix this problem.\n", "answer": "Its Dev-C++ problem , update it .Details\n"} {"question": "I just created new console application project byDev-C++ 4.9.9.2. But Project Options(Alt+P) not working andError: Access violation at address 0012F64B. Write of address 0012F64B. How to fix this problem.\n", "answer": "Its Dev-C++ problem , update it .Details\n"} {"question": "According tothisquestion, gcc's-lcommand requires your library to be named libXXX.a.\n\nIs there a way to link a static library using a different command with gcc? The goal is to avoid this lib- prefix.\n", "answer": "Just pass the library as in input file like so:\n\n```\ngcc main.c yourlibrary.a -o prog\n```\n"} {"question": "In ubuntu I would do it by following command\n\n```\n./a.out < input.txt | cat > ouput.txt\n```\n\nhow can I do this in Windows cmd?\n", "answer": "You can do it in two lines:\n\n```\na.exe < input.txt >output.txt\ntype output.txt\n```\n"} {"question": "In ubuntu I would do it by following command\n\n```\n./a.out < input.txt | cat > ouput.txt\n```\n\nhow can I do this in Windows cmd?\n", "answer": "You can do it in two lines:\n\n```\na.exe < input.txt >output.txt\ntype output.txt\n```\n"} {"question": "I have a variable i:\n\n```\nint i;\nif(b){\n i=1;\n}\nelse{\n i=-1;\n}\n```\n\nIsiundefined behavior because ofint i;exists?\nOr Should we alwaysint i=0first?\n", "answer": "Absolutely fine.\n\nYou are initialisingion all program control paths, and not reading the value until initialisation is complete.\n\nI prefer using the ternary operator in such instances.\n\nint i = b ? 1 : -1;\n\nas that's less vulnerable to accidental reference to an uninitialisedi.\n"} {"question": "```\n#include \n#include \n\nint main()\n{\n FILE * fp;\n\n fp = fopen (\"file.txt\", \"w+\");\n\n\n fclose(fp);\n\n return(0);\n}\n```\n\nthe above programs will create a file . i need that file needs to be placed in specific directory. please help\n", "answer": "Add path into the parameter offopen().\n\n```\nfp = fopen (\"/path/to/file.txt\", \"w+\");\n```\n"} {"question": "What does this macro mean or what is the result?\n\n```\n#define MOD_TYPE_12 0x11, 0x20, 0x0C, 0x00, 0x02, 0x00, 0x07, 0x0F, 0x42, 0x40, 0x01, 0xC9, 0xC3, 0x80, 0x00, 0x02\n```\n\nIs this evaluated to an array?\n\nI couldn't find anything... Maybe because I don`t know what I have to search for ^^\n", "answer": "All the\n\nMOD_TYPE_12\n\nin your program will be replaced with\n\n0x11, 0x20, 0x0C\n\nThere is no specialty with commas\n"} {"question": "I remember being constantly told that the C preprocessor does not know C. It doesn't know about types, doesn't remember declared symbols, etc. If that's the case, how can it possibly act differently based on the type of its parameter?\n", "answer": "The_Genericfeature is not processed by the preprocessor. It is aprimary expressionthat is treated with higher preference than most other expressions.\n"} {"question": "Is there anything similar to Java's Integer.MIN_VALUE in C, which gives the smallest possible value of a signed integer, or do I just have to hard code the value myself?\n", "answer": "You can uselimits.hhttp://en.cppreference.com/w/c/types/limits\n\nI think this is what you're looking for:INT_MIN = minimum value for an int\n"} {"question": "My goal is to parse potentially garbled ASCII data containing text and numbers. So far I've been doing fine with getting a pointer to numbers within the text withstrcmpand hard-coded pointer arithmetic and then converting them withstrtol, but I feel there must be a better way.\n\nIs there a function with the effect ofscanfwhich takes a pointer to memory instead of input stream?\n", "answer": "You'll be wantingsscanf. Note that it does expect a null-terminated string.\n"} {"question": "I have a string which captures details stored indata\n\nUser 6%, System 18%, IOW 0%, IRQ 0%\n\nWhat i am doing is\n\nsscanf(data,\"User %d,System %d,IOW %d,IRQ %d\",&user,&sys,&iow,&irq);\n\nI am getting wrong output . why ?\nIs is like i am missing something ?\n", "answer": "You left out the%symbols and some spaces - try:\n\n```\nsscanf(data,\"User %d%%, System %d%%, IOW %d%%, IRQ %d%%\",&user,&sys,&iow,&irq);\n```\n"} {"question": "My goal is to parse potentially garbled ASCII data containing text and numbers. So far I've been doing fine with getting a pointer to numbers within the text withstrcmpand hard-coded pointer arithmetic and then converting them withstrtol, but I feel there must be a better way.\n\nIs there a function with the effect ofscanfwhich takes a pointer to memory instead of input stream?\n", "answer": "You'll be wantingsscanf. Note that it does expect a null-terminated string.\n"} {"question": "I have a situation where i have to callwake_up_interruptible()on a wait queue, which may not holding any process to sleep. Is it ok to callwake_up_interruptible()on an unused wait queue ?\n", "answer": "Yes, as long as the queue is initialized you are fine.\n"} {"question": "What does this expression mean:\n\n```\ntypedef char foo [FOO];\n```\n\nI am just struggeling with the meaning of the expression between the squared brackets.\n", "answer": "It readsfoois the type of an array ofFOO-manycharelements. In this case,FOOis a constant, defined somewhere as#define FOO 100\n\n```\ntypedef int pair[2]; // Pair is an array of two ints.\n```\n"} {"question": "I have a situation where i have to callwake_up_interruptible()on a wait queue, which may not holding any process to sleep. Is it ok to callwake_up_interruptible()on an unused wait queue ?\n", "answer": "Yes, as long as the queue is initialized you are fine.\n"} {"question": "A code snippet is as follows:\n\n```\nstruct wer\n{\nunsigned int a:5;\nunsigned int:0;\nunsigned int b:3;\nunsigned int c:2;\nunsigned int:0;\n}v;\n```\n\nI know that all of these are packed bit fields but how to find the storage which would be needed for v.\n", "answer": "You can get the storage required forvusingsizeof(v).\n"} {"question": "A code snippet is as follows:\n\n```\nstruct wer\n{\nunsigned int a:5;\nunsigned int:0;\nunsigned int b:3;\nunsigned int c:2;\nunsigned int:0;\n}v;\n```\n\nI know that all of these are packed bit fields but how to find the storage which would be needed for v.\n", "answer": "You can get the storage required forvusingsizeof(v).\n"} {"question": "I am trying to set a bit in a 8 bit variable.\nEvery time I print the variable after setting a particular bit , I always get the value as 1.\n\n```\nuint8 value;\nvalue = (1<<1 || value)\nprintf(%x \\n,value); //prints 1 instead of 2\nvalue = (1<<2 || value)\nprintf(%x \\n,value); //prints 1 instead of 4\n```\n", "answer": "You're using boolean 'or'||. Bitwise 'or' is|.\n\nAlso you haven't initializedvalueso you can't expect it to be anything.\n"} {"question": "I have a struct that I want to zero and then set the members. I tried this:\n\n```\ncmdRequest_t cmdRequest = {0};\ncmdRequest = {3, \"d t\"};\n```\n\nbut that doesn't work. I have also tried several variants, but I always get a syntax error on that second line. How can I do this?\n", "answer": "Simply do:\n\n```\ncmdRequest_t cmdRequest = {3, \"d t\"};\n```\n\nThere's no need to zero the structure if you're going to immediately fill in other values.\n"} {"question": "I have not really a programming issue but more like an IDE issue. My Eiffel Studio 15.01 won't start up because of this error shown on the picture in the link.https://i.stack.imgur.com/mCzrO.jpg\n\nCan anybody help please?\n", "answer": "You can try to go to menu View > Tools Layout > Reset Tools Layout\n\nOtherwise remove the files under\n%LOCALAPPDATA%\\Eiffel Software\\.es\\15.01\\docking\n(or ~/.es/15.01/docking in linux)\n\nAnd restart EiffelStudio.\n"} {"question": "I have not really a programming issue but more like an IDE issue. My Eiffel Studio 15.01 won't start up because of this error shown on the picture in the link.https://i.stack.imgur.com/mCzrO.jpg\n\nCan anybody help please?\n", "answer": "You can try to go to menu View > Tools Layout > Reset Tools Layout\n\nOtherwise remove the files under\n%LOCALAPPDATA%\\Eiffel Software\\.es\\15.01\\docking\n(or ~/.es/15.01/docking in linux)\n\nAnd restart EiffelStudio.\n"} {"question": "I need a regex that will match 24 time format.\n\nEg2300is valid2900is not valid\n\nI was using this:\n\n```\n_[0-2][0-3][0-5][0-9]_\n```\n\nBut this doesn't allow _1900_etc_\n", "answer": "You need to decompose thehourspart in two cases: from00to19and from20to23. This is done by using a(pattern1|pattern2)expression.\n\nHours: 00-23.\n\n```\n([01][0-9]|2[0-3])\n```\n\nMinutes: 00-59.\n\n```\n[0-5][0-9]\n```\n\nAll together:\n\n```\n([01][0-9]|2[0-3])[0-5][0-9]\n```\n"} {"question": "Question speaks for itself. I have a program that used SHBrowseforfolder, but now they want me to upgrade it to IFileDialog which I made but is in C++, so is it even possible to get it to work with C since it's OOP?\n", "answer": "IFileDialog is part of Microsoft's Component Object Model (COM). COM programming can be done in C. Quite tedious though.\n\nHere's a tutorial (can't vouch for it's quality)\n\nhttp://www.codeproject.com/Articles/13601/COM-in-plain-C\n"} {"question": "Question speaks for itself. I have a program that used SHBrowseforfolder, but now they want me to upgrade it to IFileDialog which I made but is in C++, so is it even possible to get it to work with C since it's OOP?\n", "answer": "IFileDialog is part of Microsoft's Component Object Model (COM). COM programming can be done in C. Quite tedious though.\n\nHere's a tutorial (can't vouch for it's quality)\n\nhttp://www.codeproject.com/Articles/13601/COM-in-plain-C\n"} {"question": "This question already has answers here:Does it ever make sense to make a fundamental (non-pointer) parameter const?(5 answers)Closed8 years ago.\n\nTaking the following example:\n\n```\nvoid foo(const int foobar);\n```\n\nIs the keywordconstmeaningful?\n", "answer": "Yes, obviously. Your functionfoo()will not be able to modify the valuefoobarinside the function.\n"} {"question": "This question already has answers here:Does it ever make sense to make a fundamental (non-pointer) parameter const?(5 answers)Closed8 years ago.\n\nTaking the following example:\n\n```\nvoid foo(const int foobar);\n```\n\nIs the keywordconstmeaningful?\n", "answer": "Yes, obviously. Your functionfoo()will not be able to modify the valuefoobarinside the function.\n"} {"question": "This question already has answers here:Does it ever make sense to make a fundamental (non-pointer) parameter const?(5 answers)Closed8 years ago.\n\nTaking the following example:\n\n```\nvoid foo(const int foobar);\n```\n\nIs the keywordconstmeaningful?\n", "answer": "Yes, obviously. Your functionfoo()will not be able to modify the valuefoobarinside the function.\n"} {"question": "Lets say I have achar[10]=\"1234567890. I want it to break it in two 5digits number. I want to ask two thing that do i need to convert it in int before spliting and how will i split it\n", "answer": "ex\n\n```\nchar num10[]=\"1234567890\";\nint n1, n2;\nsscanf(num10, \"%5d%5d\", &n1, &n2);\nprintf(\"%d, %d\\n\", n1, n2);\n```\n"} {"question": "I Want to get the username or SID from a session id value, how can I do that working from Window XP using the WinAPI?\n", "answer": "You can use theWTSQuerySessionInformationfunctionto get the Username and Domain (WTSUserNameandWTSDomainNamefromWTS_INFO_CLASS).\n\nThis function is available as far back as Windows 2000.\n"} {"question": "I couldn't disable it even though by using-std=c89flag. How can I disable it?\n", "answer": "You can generate an error for variable length arrays using a compiler flag:\n\n```\n-Werror=vla\n```\n"} {"question": "I couldn't disable it even though by using-std=c89flag. How can I disable it?\n", "answer": "You can generate an error for variable length arrays using a compiler flag:\n\n```\n-Werror=vla\n```\n"} {"question": "I want execute a code only one time. I used a solution based on a global varibale of bool type. My question, is it the best solution?\n\nRemark: I use ucos-II.\n\n```\nif (TRUE == Lock)\n{\n /*Code to execute one time*/\n}\n\n/*The reste of the code*/\n```\n", "answer": "A simple code using a static variable.\n\n```\nstatic bool once = false;\n\nif (once == false)\n{\n once = true;\n // do your \"once\" stuff here\n}\n```\n"} {"question": "Is the memory allocation system of C completely random or does it use pseudo random generator ?\nWhat is the actual algorithm for memory allocation that happens at the back ?\n", "answer": "C doesn't do memory allocation.You, the programmer, have to do it yourself based on the simple primitivesmalloc()andfree(), which do nothing but ask the OS for free chunks of memory to give you.\n"} {"question": "The problem is that on one platform (windows, mvsc2015)uint64_tis defined asunsigned long longand on another (ubuntu, clang) it'sunsigned longand there is the code which looks likesprintf(buffer, \"%#llx\", u64key);\n", "answer": "The solution is to use C99's format macros, in particularPRIu64for anuint64_t:\n\n```\n#include \n…\nsprintf(buffer, \"%#\" PRIu64 \"\\n\", u64key);\n```\n"} {"question": "What's the meaning of:\n\n```\n#include \n\nint main(){\n double bmax = 31.4159265;\n printf(\"%1.4e\\n\", bmax);\n}\n```\n\nWhat is the meaning of%1.4e? I know%ffor double.\n", "answer": "```\n%e specifier is used to print value of float\\double in exponential format.\n```\n\nSo here%1.4ewill print 1 digit before the decimal point and 4 digits after the decimal point.\n\nSo ifbmax=12.242then the output will be1.2242e+01.\n"} {"question": "I'm trying to build vp8 for android armv6 but with no luckI tried to set --target=armv6-android-gcc but i get Unrecognized toolchain 'armv6-android-gcc' errorbut --target=armv7-android-gcc works just fine.how should i do it ?\n", "answer": "There is no ARM6 Android ABI in the NDK. ARM6 Android devices use the ARM5 ABI (which is the plain androideabi).\n"} {"question": "What's the meaning of:\n\n```\n#include \n\nint main(){\n double bmax = 31.4159265;\n printf(\"%1.4e\\n\", bmax);\n}\n```\n\nWhat is the meaning of%1.4e? I know%ffor double.\n", "answer": "```\n%e specifier is used to print value of float\\double in exponential format.\n```\n\nSo here%1.4ewill print 1 digit before the decimal point and 4 digits after the decimal point.\n\nSo ifbmax=12.242then the output will be1.2242e+01.\n"} {"question": "I'm trying to build vp8 for android armv6 but with no luckI tried to set --target=armv6-android-gcc but i get Unrecognized toolchain 'armv6-android-gcc' errorbut --target=armv7-android-gcc works just fine.how should i do it ?\n", "answer": "There is no ARM6 Android ABI in the NDK. ARM6 Android devices use the ARM5 ABI (which is the plain androideabi).\n"} {"question": "what is __dirstream, where can we find the definition\n\nSo, I'm trying to get the sizeof DIR from opendir, which is a typedef of __dirstream. I understand it's hidden at compile-time, is there a defined max size?\n", "answer": "That__double-underscore in the name marks it as implementation-private. Nothing is defined about it except what the implementation documents.\n\nis there a defined max size\n\nNope, sorry.\n"} {"question": "The below program redirects all my output to log file. I need to display all the output along with log file. How can this be achieved?\n\n```\n$ gcc test.c\n$ ./a.out > log.txt\n$\n```\n", "answer": "You could usetee:\n\n```\n$ ./a.out | tee log.txt\n```\n"} {"question": "The below program redirects all my output to log file. I need to display all the output along with log file. How can this be achieved?\n\n```\n$ gcc test.c\n$ ./a.out > log.txt\n$\n```\n", "answer": "You could usetee:\n\n```\n$ ./a.out | tee log.txt\n```\n"} {"question": "Is it possible to develop applications for Roku inCorC++as the SDK is written inC? If yes, how? If no, then which languages other thanBrightscriptcan apps be developed in?\n", "answer": "My understanding is yes, at least with games and the Marmalade SDKhttps://www.roku.com/developer. I actually just downloaded the SDK and have not looked at it in much detail yet, but as it seems, developing for Roku involves a mix of Brightscript, C++ and Java (Android). Hope that helps!\n"} {"question": "In Unix, C. After afork(), usually followed by await()orwaitpid()to wait thechildterminate. But can thechildexecute thewait()? Thechilddoesn't have a_child_, so when it execute thewait(), what will happen?\n", "answer": "There are no child proccess for the child proces sowait()will return -1. From the man page:\n\nwait(): on success, returns the process ID of the terminated child;\n on error, -1 is returned.\n"} {"question": "I have a very simple macro for which I want to typecast its output tointonly. How to do that?\n\n```\n#define Numbits(A) (sizeof(A)*CHAR_BIT)\n```\n\nI tried:\n\n```\n#define int Numbits(A)({int val; val = sizeof(A)*CHAR_BIT; return val;})\n```\n\nbut it also doesn't work\n", "answer": "Are you saying that#define Numbits(A) (int)(sizeof(A)*CHAR_BIT)didn't work?\n"} {"question": "If I have program with a main thread and a function running in a separated detached thread. If something in the detached thread is returning something > 0 \nwill only the child thread exit or the main thread too?\n", "answer": "A Posix thread returnsvoid *(ie. a pointer), so it cannot return anything less than zero since it's not an integer.\n\nIn any case, the return value from a detached thread is always ignored, and the process will not exit whatever the value.\n"} {"question": "Doesalignof(N) == sizeof(N)where N is an integral type?\n\nI'm asking for both C and C++, hope this isn't a problem.\n", "answer": "It's machine-specific. On a 32-bit machine,alignof(int64_t)could easily be 4. Too, assumptions that are widespread now won't be for so very long.\n"} {"question": "Doesalignof(N) == sizeof(N)where N is an integral type?\n\nI'm asking for both C and C++, hope this isn't a problem.\n", "answer": "It's machine-specific. On a 32-bit machine,alignof(int64_t)could easily be 4. Too, assumptions that are widespread now won't be for so very long.\n"} {"question": "What combination of preorder,inorder and postorder Traversal generate a unique binary Tree?\n", "answer": "following combination can uniquely identify a tree.\n\nInorder and Preorder.\nInorder and Postorder.\nInorder and Level-order.\n\nAnd following do not.\nPostorder and Preorder.\nPreorder and Level-order.\nPostorder and Level-order.\n\nFor more infomation refer:Geeksforgeek\n"} {"question": "This question already has answers here:size of int variable(6 answers)Closed4 years ago.\n\nWhy in Turbo C compilersizeof(int)is 2 bytes and in gcc Linux compiler is of 4 bytes?\n", "answer": "sizeof(int)is not a constant across all platforms.\n\nIt varies from system to system.\n\nPS: Only sizeof object which is constant across all platforms issizeof(char)\n"} {"question": "I am looking for the clang equivalent of the cl command /FC. I need full paths for my build tool to parse out and open the code files with the errors.\n\nhttps://msdn.microsoft.com/en-us/library/027c4t2s.aspx\n", "answer": "CFLAGS+= -fdiagnostics-absolute-paths\n"} {"question": "I've asorted arraybut it'snot necessarily sequential, and I need to knowIF it contains any duplicates.\n\n```\nArray : | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 8 | 8 |\n```\n\nI know we can linearly traverse in O(n) check if it contains any duplicates, but I was wondering if it is possible using Binary Search.\n", "answer": "No, You can't do it with binary search. All algorithms will take at least linear time.\n"} {"question": "I am looking for the clang equivalent of the cl command /FC. I need full paths for my build tool to parse out and open the code files with the errors.\n\nhttps://msdn.microsoft.com/en-us/library/027c4t2s.aspx\n", "answer": "CFLAGS+= -fdiagnostics-absolute-paths\n"} {"question": "The code excerpt:\n\n```\nint main(int argc, char *argv[]){ \n PySys_SetArgv(argc, argv);\n```\n\nproduces error message\n\nerror: cannot convert ‘char**’ to ‘wchar_t**’ for argument ‘2’ to ‘void PySys_SetArgv(int, wchar_t**)’\n\nHow do I convertargv?\n", "answer": "You could look into whether your compiler supportswmain. If so, you can replacemainwith:\n\n```\nint wmain(int argc, wchar_t *argv[])\n{ \n PySys_SetArgv(argc, argv);\n```\n"} {"question": "I am trying to convert from arduino to avr-c. I get the errorSREGis undeclared. Do you know whatSREGis?.\n", "answer": "SREGis theStatusRegister. It is#define'd in one of the AVR headers, so you are probably missing an#include(perhapsavr/io.horavr/common.h).\n"} {"question": "As per my knowledge range of unsigned char in C is 0-255. but when I executed the below code its printing the 256 as output. How this is possible? I have got this code from \"test your C skill\" book which say char size is one byte.\n\n```\nmain()\n{\n unsigned char i = 0x80;\n printf(\"\\n %d\",i << 1);\n}\n```\n", "answer": "Because the operands to<<*undergointeger promotion. It's effectively equivalent to(int)i << 1.\n\n\n\n\n* This is true for most operators in C.\n"} {"question": "As per my knowledge range of unsigned char in C is 0-255. but when I executed the below code its printing the 256 as output. How this is possible? I have got this code from \"test your C skill\" book which say char size is one byte.\n\n```\nmain()\n{\n unsigned char i = 0x80;\n printf(\"\\n %d\",i << 1);\n}\n```\n", "answer": "Because the operands to<<*undergointeger promotion. It's effectively equivalent to(int)i << 1.\n\n\n\n\n* This is true for most operators in C.\n"} {"question": "If file is opened using fopen() and in different mode then is it necessary to close it number of time or it can be closed once at end of code ?\n", "answer": "Each time you open the file, you are going to receive different file descriptors or file handles. So you have to close each file handle usingfclose()if opened viafopen()orclose()if opened viaopen().\n"} {"question": "I saw someone doing this to have array index starting at 1 instead of 0 in C.\n\n```\na = (int *) malloc(sizeof(int)*3) - 1\n```\n\nIs there any risk in this?\n", "answer": "Theoretical risk : only null pointers and pointers to, into, or right after an object are valid. Other pointers trigger undefined behaviour on use (if they're dangling) or when creating them through pointer arithmetic.\n\nPractical risk : getting pelted by a random code reviewer.\n"} {"question": "I saw someone doing this to have array index starting at 1 instead of 0 in C.\n\n```\na = (int *) malloc(sizeof(int)*3) - 1\n```\n\nIs there any risk in this?\n", "answer": "Theoretical risk : only null pointers and pointers to, into, or right after an object are valid. Other pointers trigger undefined behaviour on use (if they're dangling) or when creating them through pointer arithmetic.\n\nPractical risk : getting pelted by a random code reviewer.\n"} {"question": "If for example I usedLoadImage()to load a bitmap from file in Thread A, can I use the returnedHBITMAPin Thread B?\n", "answer": "Yes you can, but remember a bitmap can only be selected into one DC at once. If you have two threads both drawing the same bitmap you'll need to coordinate access to it.\n"} {"question": "For example: when I round a float into an int, why should I use :\n\nint i = (int) round(f);\n\nInstead of :\n\nint i = int round(f);\n", "answer": "What is the difference between int and (int) in C?\n\nanintis the built-in type integer and(int)isType Casting.\n"} {"question": "```\nMin Profile Cycles [215914]\nMax Profile Cycles [934625]\nMax Profile [23]\nMax Profile Count [4]\n```\n\nHow to print all these console output into some .txt file in c so that whenever i will call that function it will print in txt file instead of printing in console.\n", "answer": "as your tag is C, you can fopen() in append-mode a file and instead of using printf() you use fprintf() (and fwrite() and similar) with this filehandle.\n"} {"question": "```\nMin Profile Cycles [215914]\nMax Profile Cycles [934625]\nMax Profile [23]\nMax Profile Count [4]\n```\n\nHow to print all these console output into some .txt file in c so that whenever i will call that function it will print in txt file instead of printing in console.\n", "answer": "as your tag is C, you can fopen() in append-mode a file and instead of using printf() you use fprintf() (and fwrite() and similar) with this filehandle.\n"} {"question": "How to I give the user the ability to name the output .txt file? Here is all I have right now.\n\n```\nFILE *f = fopen(\"output.txt\", \"a\");\n```\n", "answer": "You can read the input from user and append.txt\n\n```\nchar fileName[30];\n// ...\nscanf(\"%25s\", fileName); // max 25 characters because .txt have 4 (25+4 = 29)\nstrcat(fileName, \".txt\"); // append .txt extension\n// ...\nFILE *f = fopen(fileName, \"a\");\n```\n"} {"question": "Actually, I know it's necessary to free the memory allocated with malloc(), but I wonder if I can know there is some memory left being not collected if I forget to collect it with free().\n", "answer": "Valgrind would be your best bet\n\nhttp://valgrind.org/\n"} {"question": "Actually, I know it's necessary to free the memory allocated with malloc(), but I wonder if I can know there is some memory left being not collected if I forget to collect it with free().\n", "answer": "Valgrind would be your best bet\n\nhttp://valgrind.org/\n"} {"question": "How can I determine the length, in seconds, of the Ogg Vorbis stream with libvorbis and/or libvorbisfile?\n\nAs far as I can tell, there's nothing in thevorbis_infostructure that tells me the length of the stream.\n", "answer": "Using the lower level API, you can do this withov_time_total.\n"} {"question": "I have a 16 bit address 0-15, I need to check at value of bit corresponding to their position in C\n\nfor example at 15 place i have 1, 14 has 0, and soo on!\n\n|1|0|0|0|1|0|1|0|1|1|1|1|1|0|1|0|\n\nI was thinking to create 16 new addresses with all zero and the position i am looking\n", "answer": "Use a macro similar to this:\n\n```\n#define CHECK_BIT(x, i) ( ((x) & (1 << (i)) != 0 ) )\n```\n\nCHECK_BIT(x, i)will returntrueif the i'th bit ofxis one, false otherwise.\n"} {"question": "I am confused about this example:\n\n```\ntypedef int32_t voltage_dc_estimate_t[1];\n```\n\nEverything is OK but that[1]at the end of the type definition confuse me. Could someone please help me to understand that situation?\n", "answer": "[1]means an array of1element.\n\nvoltage_dc_estimate_tis a type of an array of1element of typeint32_t.\n"} {"question": "I'm trying to use #ifndef as below.\n\n```\n#ifndef MACRO1 || #ifndef MACRO2\n....\n#endif\n```\n\nI already tried:\n\n```\n#ifndef (MACRO1 || MACRO2) \n..\n#endif\n```\n\nBut for both cases am getting below error\n\nerror: extra tokens at end of #ifndef directive\n", "answer": "Use the#ifpreprocessor directive instead:\n\n```\n#if !defined(MACRO1) || !defined(MACRO2)\n```\n"} {"question": "I have:\n\n```\nconst char *ptr = \"int\";\n```\n\nIf I have to declare usingptr:\n\n```\nint a;\n```\n\nptrcan point to anything arbitrarychar,string,. \nI have to delcare a variable of that type whatptris pointing at.\nIs it possible?\n", "answer": "No. C++ is not an interpreted language.\"int\"has a meaning to the compiler, but at runtime there's nothing which understands\"int\".\n"} {"question": "I have:\n\n```\nconst char *ptr = \"int\";\n```\n\nIf I have to declare usingptr:\n\n```\nint a;\n```\n\nptrcan point to anything arbitrarychar,string,. \nI have to delcare a variable of that type whatptris pointing at.\nIs it possible?\n", "answer": "No. C++ is not an interpreted language.\"int\"has a meaning to the compiler, but at runtime there's nothing which understands\"int\".\n"} {"question": "I have:\n\n```\nconst char *ptr = \"int\";\n```\n\nIf I have to declare usingptr:\n\n```\nint a;\n```\n\nptrcan point to anything arbitrarychar,string,. \nI have to delcare a variable of that type whatptris pointing at.\nIs it possible?\n", "answer": "No. C++ is not an interpreted language.\"int\"has a meaning to the compiler, but at runtime there's nothing which understands\"int\".\n"} {"question": "I know how to find Big O for \"for loops\" and nested \"for loops\", but what happens when we have two for loops, not nested but two separate for loops in the same function.\n", "answer": "It just gets added.\n\nSee for e.g. :\n\n```\nfor(i=0;i\nint main()\n{\n int i = 012;\n printf(\"%d\", i);\n}\n```\n\nOn O/P the value ofiis printed as 10. I know (012)8= (10)10. But I'm confused about how C storesintvariable values. Can anybody explain it to me?\n", "answer": "They are stored in binary, you can use many representations to define them, but in the end it's the binary representation that is used.\n"} {"question": "I have a set of points in a 2D plane. I need to detect only the points that belong to the shape that borns from the union of this subset of points in order to cover the largest area: that is, the boundary points.\n\nThe following figure is an example:\n\n\n\nThe red points are those ones I need to detect.\n", "answer": "What you need is calledConvex hull.A lot of algorithms existto calculate it.\n"} {"question": "I have a set of points in a 2D plane. I need to detect only the points that belong to the shape that borns from the union of this subset of points in order to cover the largest area: that is, the boundary points.\n\nThe following figure is an example:\n\n\n\nThe red points are those ones I need to detect.\n", "answer": "What you need is calledConvex hull.A lot of algorithms existto calculate it.\n"} {"question": "I disassembled the following C call\n\n```\nexit(EXIT_SUCCESS);\n```\n\nand found out that it calls the exit procedure at an assembly level\n\n```\ncall exit\n```\n\nWhere can I find the source code for this procedure so that I can study it and find out exactly what is happening?\n", "answer": "In theC library of your system. Which then eventually invokes youroperating system.\n\nThe links are for linux with glibc, you forgot to mention your environment.\n"} {"question": "I disassembled the following C call\n\n```\nexit(EXIT_SUCCESS);\n```\n\nand found out that it calls the exit procedure at an assembly level\n\n```\ncall exit\n```\n\nWhere can I find the source code for this procedure so that I can study it and find out exactly what is happening?\n", "answer": "In theC library of your system. Which then eventually invokes youroperating system.\n\nThe links are for linux with glibc, you forgot to mention your environment.\n"} {"question": "so I have a string with the following value\n\n[7, 8]\n\nNow I wan't to store each value (only the numbers) in a 2D array [1][2].I'm pretty sure using sscanf is the best way to do this, but how do I tell sccanf to only read the integers?\n\nThanks in advance\n", "answer": "```\nsscanf(\"[%d,%d]\", Array[a][b], Array[c][d]);\n```\n"} {"question": "Whats difference in the working of\n\n```\nwhile(i++<100)\n```\n\nand\n\n```\nwhile(i++<100);\n```\n\nIs this correct that in 1st case,iincreases until its value reach to99but in 2nd case,;is an error that's why nothing is going to happen?\n", "answer": "No:\n\nwhile(i++<100);is a loop with a empty command (does nothing untiliis 100), (there is no compilation error).\n\nAndwhile(i++<100) {commands}is a same loop but does someting.\n"} {"question": "so I have a string with the following value\n\n[7, 8]\n\nNow I wan't to store each value (only the numbers) in a 2D array [1][2].I'm pretty sure using sscanf is the best way to do this, but how do I tell sccanf to only read the integers?\n\nThanks in advance\n", "answer": "```\nsscanf(\"[%d,%d]\", Array[a][b], Array[c][d]);\n```\n"} {"question": "Whats difference in the working of\n\n```\nwhile(i++<100)\n```\n\nand\n\n```\nwhile(i++<100);\n```\n\nIs this correct that in 1st case,iincreases until its value reach to99but in 2nd case,;is an error that's why nothing is going to happen?\n", "answer": "No:\n\nwhile(i++<100);is a loop with a empty command (does nothing untiliis 100), (there is no compilation error).\n\nAndwhile(i++<100) {commands}is a same loop but does someting.\n"} {"question": "How do I that? I don't want to use the Visual Studio IDE, yet I want to use the provided compiler (cl.exe) and the Developer Command Prompt for VS2013.\n", "answer": "I used to do it to via command line\n\n```\ncl /EHsc /MD main.cpp /Fetest.exe /I F:\\C++_Libraries\\SDL2\\SDL2-2.0.3\\include /link /LIBPATH:F:\\C++_Libraries\\SDL2\\SDL2-2.0.3\\lib\\x86 SDL2.lib SDL2main.lib /SUBSYSTEM:CONSOLE\n```\n"} {"question": "Please explain the difference between\n\n```\nchar* str = \"Hello\";\n```\n\nAnd\n\n```\nchar* str = {\"Hello\"};\n```\n", "answer": "ISO 9899-1990 6.5.7(\"Initialization\") says :\n\nAn array of character type may be initialized by a character string\n literal, optionally enclosed in braces.\n"} {"question": "Please explain the difference between\n\n```\nchar* str = \"Hello\";\n```\n\nAnd\n\n```\nchar* str = {\"Hello\"};\n```\n", "answer": "ISO 9899-1990 6.5.7(\"Initialization\") says :\n\nAn array of character type may be initialized by a character string\n literal, optionally enclosed in braces.\n"} {"question": "Create file using C in Ubuntu.\nI've tried that code and it doesn't work.\n\n```\n#include \n#include\nint main() \n{ \n char a[50];\n char command[150];\n printf(\"Enter The File's Name\");\n gets(a);\n strcpy(\"touch \");\n strcat(\"a\");\n system(command);\n return 0;\n}\n```\n", "answer": "Your strcpy should bestrcpy(command, \"touch\")and your strcat should bestrcat(command, a)\n\nBut there are much better ways to create an empty file...\n"} {"question": "Why doesn't this work?\n\n```\nprintf(\"%d \\n\\n\\n\\n\", atoi(\"11110010100\"));\n```\n\nit outputs -1774891788... I just want it outputted as it is. It seems to work just fine if the number is a bit smaller.\n", "answer": "atoireturns anint. You pass a string which contains a number bigger than whatint(in your implementation) can hold. So, you have an integer overflow.\n\nTo print the maximum value anintcan hold, includelimits.hand printINT_MAX.\n"} {"question": "Newbie question: why can't I getprintfto output the binary number as it is, instead of converting it?\n\n```\nint gpa = 01011001;\nprintf(\"pure: %i \\n\", gpa);\n```\n\ngives the output: 266753\n\nHow can I get it to output 01011001 or just 1011001?\n", "answer": "0preceding an integer literal is hold for octa-decimal number. Decimal equivalent of01011001is266753. Remove that preceding0to print as it is.\n"} {"question": "Create file using C in Ubuntu.\nI've tried that code and it doesn't work.\n\n```\n#include \n#include\nint main() \n{ \n char a[50];\n char command[150];\n printf(\"Enter The File's Name\");\n gets(a);\n strcpy(\"touch \");\n strcat(\"a\");\n system(command);\n return 0;\n}\n```\n", "answer": "Your strcpy should bestrcpy(command, \"touch\")and your strcat should bestrcat(command, a)\n\nBut there are much better ways to create an empty file...\n"} {"question": "I am using linux Lite. I have installed code Blocks. When i am creating any new project then it is working correctly. it compiling codes. But When any empty c file is creating and trying to compile then it is not working.Showing message that permission denied. I have checked the compiler setting for empty file. it is GNU GCC Compiler. How can i solve this?\n", "answer": "It would be happen due to root access. run code-blocks as root user and try it would be work.\n"} {"question": "I need to edit the values of an existing ListView row (i.e change the values of an Item and its Subitems).\n\nI need to do that programmatically and not by clicking on the ListView item at runtime to rename it.\n", "answer": "just useLVM_SETITEMas documented.\n"} {"question": "```\n#include\nvoid main ()\n{\n int a=4;\n const int *p=&a; \n *p--; \n}\n```\n\nin the above line it means that we can not change the value a via p, so in decrement statement it should give an error but it is not giving the error. can anyone explain why??\n", "answer": "*p--decrementspnot contents ofp.\n\nIf you do(*p)--you will get compilation error\n\n```\nerror: decrement of read-only location ‘*p’\n```\n"} {"question": "I know compiler does Structure padding because CPU can read one word at time ( Word size depends on architecture 16/32/64 ) but I am not able to understand padding behavior for below example.\n\n```\nstruct pad \n{ \n char ch;\n};\n```\n\nSize of \"struct pad\" comes as 1 Byte ( But According to padding concept I suspected 4 byte ( 32 bit architecture ).\n", "answer": "A char type can be accessed efficiently on any address boundary, so no padding is necessary.\n"} {"question": "I'm trying to do thisswprintf(hexResult, L\"%I64X\", result);from javascript, is this possible? Such thatCityHash64('C:\\Program Files (x86)\\Mozilla Firefox')is encoded asE7CF176E110C211B.\n\nThanks\n", "answer": "JavaScript numbers have atoStringmethod which takes a radix. UsingtoString(16)will get you the number in hex. Is this what you're looking for?\n"} {"question": "How can I delete the first digit of a given number using a user defined function (Suppose the function isDELTOP) ?\n\nFor Ex.,\n\n```\nx=DELTOP(1748);\n```\n\nI want the value ofxas748.\n\nWould anybody tell me how to write this function easily ?\n", "answer": "A C++11 one-liner would be\n\n```\nint DELTOP(int x) {\n return std::stoi(std::to_string(x).substr(1));\n}\n```\n"} {"question": "Does something like TextBox exist in ncurses?\n\nRequirements to TextBox:\n\nability to adequate handle KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT, KEY_BACKSPACE, KEY_DC and other.adequate transfer lines.save, if you need, text in char* buffer.\n", "answer": "ncursesitself provides lower-level functions from which a \"textbox\" can be built. For instance, thedialogandcdklibraries use (n)curses to provide these features.\n"} {"question": "Does something like TextBox exist in ncurses?\n\nRequirements to TextBox:\n\nability to adequate handle KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT, KEY_BACKSPACE, KEY_DC and other.adequate transfer lines.save, if you need, text in char* buffer.\n", "answer": "ncursesitself provides lower-level functions from which a \"textbox\" can be built. For instance, thedialogandcdklibraries use (n)curses to provide these features.\n"} {"question": "At the third line I get \"Expected a declaration\" for instr[0xB8][256]\n\n```\nvoid funcB8 ();\nvoid (*instr[256][257])();\ninstr[0xB8][256] = &funcB8;\n```\n", "answer": "You can initialize the array at a specific index outside a function:\n\n```\nvoid (*instr[256][257])() = { [0xB8][256] = &funcB8 };\n```\n\nor assign a value to the array, but to do that you have to do that in a function\n"} {"question": "So, I'm trying to write some JNA code to work with Unix sockets, and I'm trying to reference AF_UNIX for sockets. I looked through some of the gcc included files, but I couldn't find anything.\n", "answer": "It may be platform-dependent, which is why you should use the define. It should be insys/socket.h.\n"} {"question": "I'm writing a netfilter module and need to store current time value somewhere inside the module to calculate difference in time. What is the best way to do that?\n", "answer": "I didn't understood your question properly. Because you are not provided any piece of code. Any way you can keep your variable either indevice structure of module, or you can declare variable simply as aGlobal variable.\n"} {"question": "The following C code is apparently O(N) (according to my practice exam). However, I am not sure as to why it is O(N) and not O(Something*Something).\n\n```\nvoid doit(int N) {\n while (N) {\n for (int j = 0; j < N; j += 1) {\n }\n N = N / 2; \n }\n}\n```\n\nAnyone care to give me some insight to this problem?\n\nThanks in advance!\n", "answer": "Because N + N/2 + N/4 + ... = 2N.\n"} {"question": "I just started programming in C. And I don't really understand the following code:\n\n```\nprintf(\"%zu\",i);\n```\n\nor instead of%zuwhat are the other things that I can write (I know that they depend on the type of i) and which one is for what?\n", "answer": "It's a format modifier forsiz_tandsize_tis unsigned.\n\n```\nprintf(\"%zu\\n\", x); // print unsigned decimal\nprintf(\"%zx\\n\", x); // print hexadecimal\nprintf(\"%zd\\n\", y); // print signed decimal\n```\n"} {"question": "I just started programming in C. And I don't really understand the following code:\n\n```\nprintf(\"%zu\",i);\n```\n\nor instead of%zuwhat are the other things that I can write (I know that they depend on the type of i) and which one is for what?\n", "answer": "It's a format modifier forsiz_tandsize_tis unsigned.\n\n```\nprintf(\"%zu\\n\", x); // print unsigned decimal\nprintf(\"%zx\\n\", x); // print hexadecimal\nprintf(\"%zd\\n\", y); // print signed decimal\n```\n"} {"question": "I want to be able to do this in visual studio:\n\n```\nstruct A\n{\n int x;\n};\n\nstruct B\n{\n int y;\n struct A;\n};\n\nstruct B b;\nb.x //...\n```\n\nHow can I do this? In gcc you use -fms-extensions to compile it\n", "answer": "Youjust do it.MSVS supports this as an extension.\n"} {"question": "Basically, I can't figure this out, I want my C program to store the entire plaintext of a batch program then insert in a file and then run.\n\nI finished my program, but holding the contents is my problem. How do I insert the code in a string and make it ignore ALL special characters like %s \\ etc?\n", "answer": "You have to escape special characters with a \\, you can escape backslash itself with another backslash (i.e.\\\\).\n"} {"question": "Basically, I can't figure this out, I want my C program to store the entire plaintext of a batch program then insert in a file and then run.\n\nI finished my program, but holding the contents is my problem. How do I insert the code in a string and make it ignore ALL special characters like %s \\ etc?\n", "answer": "You have to escape special characters with a \\, you can escape backslash itself with another backslash (i.e.\\\\).\n"} {"question": "In C, we can build a debug version or a release version of the binary files (the object files and the executable). How can we do this in Go?\n", "answer": "In Go, it isn't typical to have a debug version or a release version.\n\nBy default,go buildcombines symbol and debug info with binary files. However, you can remove the symbol and debug info withgo build -ldflags \"-s -w\".\n"} {"question": "In C, we can build a debug version or a release version of the binary files (the object files and the executable). How can we do this in Go?\n", "answer": "In Go, it isn't typical to have a debug version or a release version.\n\nBy default,go buildcombines symbol and debug info with binary files. However, you can remove the symbol and debug info withgo build -ldflags \"-s -w\".\n"} {"question": "Is it possible to load akernel extension(kext) through aC APIinstead of using thesystem()call?\n", "answer": "Yes, you want theKextManagerAPI. In particular,KextManagerLoadKextWithIdentifier()is probably the function you'll want to use to load an installed kext, versusKextManagerLoadKextWithURL()if you want to load a kext that is not in /System/Library/Extensions or /Library/Extensions but e.g. in an .app bundle.\n"} {"question": "This question already has answers here:Fill with variable number of ones(2 answers)Closed8 years ago.\n\nI have a number in range 1-8.\n\nI want to convert it to\n\n```\n0b00000001 // 1\n0b00000011 // 2\n0b00000111 // 3\n0b00001111 // 4\n0b00011111 // 5\n0b00111111 // 6\n0b01111111 // 7\n0b11111111 // 8\n```\n\nCan it be done without a switch or a for loop?\nIdeally with a simple formula.\n", "answer": "What you are looking for is\n\n```\n(1 << v) - 1\n```\n"} {"question": "This question already has answers here:Fill with variable number of ones(2 answers)Closed8 years ago.\n\nI have a number in range 1-8.\n\nI want to convert it to\n\n```\n0b00000001 // 1\n0b00000011 // 2\n0b00000111 // 3\n0b00001111 // 4\n0b00011111 // 5\n0b00111111 // 6\n0b01111111 // 7\n0b11111111 // 8\n```\n\nCan it be done without a switch or a for loop?\nIdeally with a simple formula.\n", "answer": "What you are looking for is\n\n```\n(1 << v) - 1\n```\n"} {"question": "This is a piece of myCcode:\n\n```\nfor (i=2; i