question
stringlengths
25
894
answer
stringlengths
4
863
``` BOOL foo(void){ static BOOL displayed = FALSE; static BOOL initialized = FALSE; if (displayed) return FALSE; //more code displayed = TRUE; return FALSE; } ``` what's the meaning of a static local variable in C ? if this method is called a second time, thedisplayedwon't be re-...
Static local variables are initialized once only, before program startup. Their values then persist between invocations. From the standard, section 6.2.4/3 Storage durations of objects: An object whose identifier is declared without the storage-class specifier _Thread_local, and either with external or internal li...
I'm doing some work on key press handing in a firmware project. I've been googling to try to find what the typical duration of a key press is, particularly the minimum for a fast typist. Surprisingly I can't find any figures for this anywhere.
There are some recent studies on keypress timings that have published there timings. Here are two: http://www.cs.cmu.edu/~keystroke/(Data gathered by Kevin Killourhy and Roy Maxion as accompaniment to "Comparing Anomaly-Detection Algorithms for Keystroke Dynamics"). Pressure-Sensitive Keystroke Dynamics(Gathered by ...
I have achar *message;which contains some content. I wish to read this message from a specific index (for example 20) and until end of thechar*. Is there any clever way to do this? I have been looking atmemcpy()and the possibility to copy a "sub-string" frommessageinto a newchar *tmp;, but I can't seem to figure out h...
You may try like this: ``` char *tmp= message + 20; ```
Can I bind a file descriptor returned by open call to a socket? I am trying to do something like, ``` filefd = open("path",O_RDWR); ... bind (filefd, (struct sockaddr *) &servaddr, sizeof(servaddr)); connfd = accept (filefd, (struct sockaddr *) &cliaddr, &clilen); ``` Why does the accept call return -1?
From an applications point of view, the difference is how you create and use the descriptor. Some system-calls can take any kind of descriptor, while others require a specific type of descriptor. In your case thebindcall would have returned-1too, if you checked for the error. When a system-call returns-1you should ch...
I made a small program that puts line numbers in front of each line in a file! This is working perfectly fine, but their is just one problem. I get this as result: 1 Text one 2 Text two 3 Text three But I want the output to me like: ``` 1 Text one 2 Text two 3 Text three ``` I use this code to execute the sed...
``` sed 'N;N;N;s/\n//g;s/[0-9]*/& /' YourFile ``` remove \n (base on a structure of 4 line per real line, then add a space after first number but why using sed to deconstruct what could be done easily construct directly otherwise (cat -n, grep -n, ...) ?
the bit shift operator in C is not operating as I expect, which without doubt is my misunderstanding, but can someone explain what's happening? ``` unsigned char in = 155; unsigned char res; res = (in << 6) >> 7; ``` should be the same as ``` res = in << 6; res = res >> 7; // can also use res >>= 7; ``` but it's ...
Calculations are done inints. In the second case, you're assigning tores, which will truncate to 8 bits, before shifting back. In the first case you aren't, so the truncation doesn't occur and the high bits are preserved and shifted back down.
i have something like this. ---a- aaa-- a---- ---a- b--a- How can i reach all the a's from b in minimum steps? And how can i approach this with graph?
a* algorithmmight serve You well. It's vatiations are a common solution to finding shortest (least costly paths) in game development. As for graph representation define a structure called Node and Connection. you can use a std::vector for storing verticles and std::vector for connections (edges). ``` typedef struct ...
I am not very experienced in C. I am trying to have some code that works like this: Declare array of strings;Function that erases array of strings and inserts a new set of strings (number unknown) How can I do this? I know I can doconst char *a[2];but that requires entering an array size when I declare it....
You can use pointers to pointers. ``` char **strings; ``` Here is how you would create it: (where<size>is the size of the array) ``` strings = malloc(sizeof(char*) * <size>); ``` Now setting/getting elements is pretty simple: ``` strings[0] = "hello"; printf("%s", strings[0]); ``` Just a warning, the memory is n...
I am attempting to learn unity3D but am like getting to a Java Pro but i wanted to get into 3D game development and a checked out Unity3D and I found out it can be written using C++ or C# or JavaScript but since it can be written in JavaScript, can it also be written in Java or C?
Javascript is different to Java. A nice analogy that I have heard before is: "Java is to Javascript, what a car is to carpet". Therefore, no you cannot useUnity3Din Java. However, here is a post that you can look at:Best 3D Java Engine.
``` void write(const record* list[]) { FILE* out=fopen("output.txt","w"); if(!out) { printf("error"); exit(1); }else { } } ``` fwrite takes a array as the first argument, but my array is a array of pointers. I want the content of the pointer pointing ...
``` int i; for (i = 0; i < length; i++) { fwrite(list[i], sizeof (record), 1, out) ; } ``` wherelengthis the size of the array. You must modify your program and pass the length to yourwritefunction.
I want to know how to execute a command from a c program,on windows os. To be more specific how to write a c program whose output will not be printed but directly goes to command prompt and get executed there? please help me
I think you need to use system() command in your C code. For example: ``` system("pause"); ``` where "pause" is the command to be executed in cmd. reference:http://www.cplusplus.com/reference/cstdlib/system/ I hope i got your question right.
From an initialized Pointer to Array of Characters like this: ``` char *someChar[]={"Some","Text","Here"}; ``` How would I be able to call for instance, the letter x of "Text", I can't move it's addresssomeChar[1]to some offset to acces x, since this is not a 2-dimensional array. Using*someChar[1][2]gives the Inval...
That would besomeChar[1][2]. someChar[1]is the second array element, which is a pointer to the first letter of"Text".
Given, in the function called, ``` void callFunct1 (arg_t **q) { if (t==1) // *q = NULL; else memcpy((*q)->items, listOfContents, size of listOfContents); // listOfContents is const static, no memcpy required }; EXPORT_SYMBOL(callFunct1); ``` Given t == 0 How may I ensure that the memcpy is getting the c...
since for the q memory is not allocated so you need to allocate the memory first forr the q and then copy the contents to q.To the memcpy address of the structure should be passed &((*q)->items) and similarly for source structure(OR)change the function to callFunct1 (arg_t *q) and can be called as belowarg_t q;callF...
The code below runs fine in C. But in C++ (std-C++00), the compilation fails. ``` #include <complex.h> int main() { float complex a = 0.0; return 0; } ``` Here's the errors i am facing ``` Error: complex is not pat of 'std' Error: expected ';' before a ``` I have read the solution to the problem I am fac...
``` #include <complex> int main() { // Both a and b will be initialized to 0 + 0i. std::complex<float> a; std::complex<float> b = 0.0f; return 0; } ```
I want to know how to execute a command from a c program,on windows os. To be more specific how to write a c program whose output will not be printed but directly goes to command prompt and get executed there? please help me
I think you need to use system() command in your C code. For example: ``` system("pause"); ``` where "pause" is the command to be executed in cmd. reference:http://www.cplusplus.com/reference/cstdlib/system/ I hope i got your question right.
From an initialized Pointer to Array of Characters like this: ``` char *someChar[]={"Some","Text","Here"}; ``` How would I be able to call for instance, the letter x of "Text", I can't move it's addresssomeChar[1]to some offset to acces x, since this is not a 2-dimensional array. Using*someChar[1][2]gives the Inval...
That would besomeChar[1][2]. someChar[1]is the second array element, which is a pointer to the first letter of"Text".
Given, in the function called, ``` void callFunct1 (arg_t **q) { if (t==1) // *q = NULL; else memcpy((*q)->items, listOfContents, size of listOfContents); // listOfContents is const static, no memcpy required }; EXPORT_SYMBOL(callFunct1); ``` Given t == 0 How may I ensure that the memcpy is getting the c...
since for the q memory is not allocated so you need to allocate the memory first forr the q and then copy the contents to q.To the memcpy address of the structure should be passed &((*q)->items) and similarly for source structure(OR)change the function to callFunct1 (arg_t *q) and can be called as belowarg_t q;callF...
The code below runs fine in C. But in C++ (std-C++00), the compilation fails. ``` #include <complex.h> int main() { float complex a = 0.0; return 0; } ``` Here's the errors i am facing ``` Error: complex is not pat of 'std' Error: expected ';' before a ``` I have read the solution to the problem I am fac...
``` #include <complex> int main() { // Both a and b will be initialized to 0 + 0i. std::complex<float> a; std::complex<float> b = 0.0f; return 0; } ```
This question already has answers here:How do I best silence a warning about unused variables?(23 answers)Closed9 years ago. I am programming in C Linux. I have a few functions in my code that i receive as parameters X parameters, but i do not use all of the parameters in it. I am getting a warning of unused variab...
Assuming this ``` int f(int x, int y) { return y; } ``` to provoke the warning mentiond by the OP. For gcc just do this ``` int f(int x __attribute__ ((unused)), int y) { return y; } ``` to have the waninng disappear. A more generic trick is to just do: ``` int f(int x, int y) { x = x; return y; } ```...
How to use an image as a button in GTK in c language in code blocks? I have tried making the button of same color as that of the background and then adding image on it. But there is a outline or shadow still there. So, how can i remove those shadows or is there a way to directly use an image as a button?
One way is outlined by@Shabhaz, by putting the image in anEventBox, and handling the button-press event. The other way is by placing the image in the button and customizing the style of the button to remove the outline and the shadow. You would callgtk_rc_parse_string()to define an outline-less button class, andgtk_w...
I have two C codes. test.c is ``` #include <stdlib.h> int main () { int a; a = 5; return a; } ``` test2.c is ``` #include <stdlib.h> int main () { int a; a = 6; return a; } ``` When I run them and I check the address in memory of the "a"s with gdb I get the same address. Why is this so? ...
The address of "a" is on the stack frame for your program. This is avirtualaddress, independent of where in physical memory your program is actually loaded. Therefore, it would not be surprising if both (almost identical) programs used the same address.
Here is my C Program Code : ``` #include<stdio.h> unsigned int count = 1; int main(void) { int b = 10; int a[3]; a[0] = 1; a[1] = 2; a[2] = 3; printf("\n b = %d \n",b); a[3] = 12; printf("\n b = %d \n",b); return 0; } ``` And the output as ``` b=10 b=12 ``` Can anyone explain why it is a...
You are writing beyond the bounds of the array. This would invokeundefined behavior.
Within an assignment, which I program in C, I need to concatenate the symbol '#' and an integer, for instance 16, to the string "#16". This is not to be printed out, but to be passed on as an argument to another function. By my understanding, I should use the function sprintf. However, I am getting segmentation errors...
sprintftakeschar*, notchar. ``` int sprintf(char *str, const char *format, ...); ``` And yes, prefer usingsnprintf
``` typedef struct { char*title; int year; int length; //in minutes } record; record list[1024]; int j; for(j=0;j<1024;++j) list[j]=NULL; ``` I am trying to initialize an array of struct and let each element point to null initially. gcc gives me an error "incompat...
You can initialize your array at declaration time this way: ``` record list[1024] = {{0}}; ```
I was surprised to see that adding an a-priori non defined "double sin(double)" function in a C code that is JIT'ed actually worked... This is explained in LLVM doc, the JIT engine automatically falls back to dlsym("sin") which works as my code was linked with libm However, I want to avoid this and have no built-in f...
You can callExecutionEngine::DisableSymbolSearching(true)to disable automatically resolving with the linked code.
Let's say I provide the following long option arguments structure: ``` static const struct option long_opts[] = { { "version", no_argument, NULL, 'v' }, { "help", no_argument, NULL, 'h' }, { NULL, 0, NULL, 0 } }; ``` How can I specify an additional option, named '--myoption', but with...
If you don't put that option intoshortoptsthen no short option for that parameter will be used. E.g.: ``` #define MYOPT 1000 static struct option long_options[] = { {"myopt", no_argument, 0, MYOPT }, } [...] c = getopt_long(argc, argv, "", long_options, &option_index); switch (c) { case MYOPT: /* Do stuff....
If I am given a void pointer to an array of elements, is there a way in 'C' to find out what type of elements (i.e. data-type of elements) are stored in the array? What could possibly happen if I typecast this void pointer to a random data-type and try to traverse the array?
Short answer: No, undefined behaviour. Long answer: You have to cast the pointer into something that's appropriate. There are ways to figure it out, but only if you pass, along with the void pointer itself, information about the width of each element in the array.
char *searcharray = malloc(size); for (i = 0; i < size; i++) { fscanf(filePtr, "%c", searcharray[i]); } Here is my code. And Everytime i keep getting the warning message: warning: format '%c' expects argument of type 'char *', but argument 3 has type 'int' How is the variable searcharray being determined as an in...
What's happening: searcharray[i]has typechar.In a varargs function, thecharwill be promoted to anint. Your bug: fscanfexpects the variables that it will place data into to be passed by pointer.So you should be doing:fscanf(filePtr, "%c", &searcharray[i]);
I have this function ``` long processFile(char * fileName) { struct stat statBuf; mode_t mode; int result; result = stat(fileName, &statBuf); if (result == -1); return -1; if(S_ISDIR(mode)) return(processDirectory(fileName)); else return 1; } ``` If the "fileName" ...
``` if (result == -1); return -1; ``` Remove the semicolon from the first line.
I want to read 20 strings from a file which may or may not contain white spaces.Those strings are in consecutive lines in a file. I want to create a character array from a line which will not contain white spaces. How to do that? eg: ``` aaa bbbbccc abcedefghij ``` and so on. I want to create a char array which w...
The easiest (probably not the fasted) way would be to read character wise usingfgetc(). After having read a character, inspect it and skip each type of character you do not want. To detect all kind of white-spaces useisspace(), to detect blanks only useisblank(). Start copying the characters you want to a new alloc...
Consider the following code: ``` unsigned short i; unsigned short a; unsigned char *pInput = (unsigned char *)&i; pInput[0] = 0xDE; pInput[1] = 0x01; a = ((unsigned short)(*pInput++)) << 8 | ((unsigned short)(*pInput++)); ``` Why the value of a is 0xDEDE, not 0xDE01?
The code invokesundefined behavior. The reason is thatpInputis modifying more than once between twosequence points. You may get anything, either expected or unexpected result. Nothing can be said. C99 states that: Between the previous and next sequence point an object shall have its stored value modified at most onc...
Basically, I want to make a Pointer to an object from stu_data and then initialize all the variables in it(including the variables of the clg_data structure within). Problem is that I don't know how to access the second structure with a Pointer. There's an example of metryingto do that below (in void main()). ``` typ...
p->clg_datais not a pointer. Use.to access its members ``` p->clg_data.college_id = 3; ```
I have a quick question: I'm in the Datastructure course and we are writing a program to find distance between cities. It says that we should put the city names as keys (prefereably using a hashtable) and the nodes as values in the table. I'm wondering if the nodes have a value that I assign or are they just placehol...
Sounds like a good question to ask your professor. Normally, a node in this kind of problem would probably be some kind of object or data structure that specifies what other nodes (cities) it connects to, and probably the distance to each adjacent node. So you could store the entire node in your hash table, or you cou...
Hello i'm new to C and have some confusion Regardingfprintf I'm trying to create a Data table and i want it to look exactly like this: ``` Rectangle A Rectangle B SW corner Height Width SW corner Height Width ``` Most of my confusion is coming from the white spaces, surely there is a...
You can use width specifier: ``` printf("[%5d] [%-5d]\n", 42, 42); ```
I have the following struct: ``` /** The description of an ordinary 8+3 DOS directory entry. */ struct dirent { byte d_name[8]; //!< space padded name byte d_ext[3]; //!< space padded extension byte d_attr; //!< the file attributes ...... }; printf("%s\n", de.d_name); ``` The prob...
To print a char array that is space-padded (but not necessarily null-terminated) you can use a width specifier for printf: ``` printf("%.*s\n", sizeof de.d_name, de.d_name); ```
I know how to getCWD's path name through thegetcwdfunction , and I'm using thestrtokfunction to get thedirectory name(means current working folder), is there anything available to get this thing through a simple query or a function?
Ifgetcwd()returns"/this/is/my/cwd"and you want just"cwd"then you might like to usebasename()on what was returned bygetcwd(). ``` #include <unistd.h> /* for getcwd() */ #include <libgen.h> /* for basename() */ [...] char cwd[PATH_MAX] = ""; char * cwd_base = NULL; if (NULL == getcwd(cwd, sizeof(cwd))) { ...
I'm learning to work with the pointers, I did a simple exercise but unfortunately it does not work I would be happy if you help me to fix it. The Exercise - just got a value and send it to function thet Raises him one. The code- ``` #include <stdio.h> void incNum(int* p) { *p++; } int main() { int number = 20; i...
Your function call is wrong. It should be like ``` incNum(p); ``` In your function change*p++to(*p)++to increment the value ofnumberby1.
I am using the clone feature in linux c. However, I encountered the error CLONE_VM undeclared (first use in this function) when I tried to compile my code. I went to google for solutions and one of the site mentioned that#include <sched.h>must be included inside the code. I have already included#include <sched.h>in ...
Add the following lines to the beginning of your code ``` #define _GNU_SOURCE /* See feature_test_macros(7) */ #include <sched.h> ``` You could find out which header files and/or macros are needed by man 2 syscall_nameman 3 library_function_name By the way, the implication of_GNU_SOURCEand more coul...
Here is my code (about an infinite loop) from my book, but when I run the program and add i.e.5and5, and I type1to exit, I get12. ``` int main() { unsigned int num; unsigned long sum; for ( ; ; ) { printf("Enter a number from 2-65535 or enter 1 to end a program.\n"); scanf("%u", &num)...
sumis not initialized. It hasindeterminatevalue.
Most of the time _WIN64 macro was working well with Microsoft Visual Studio 2008 but TARGET_X64 not working well.Please explain these two macros with specific example.
The Visual C++ compiler predefines_WIN64when compiling for a 64-bit target. To test for x64/amd64 specifically, test for_M_X64instead. Consultthe documentationfor other macros that are predefined by the compiler. TARGET_X64is defined by neither the Windows SDK nor the Visual C++ libraries or toolchain. It must be ...
I'm having a hard time understanding this statement here: ``` for( int i=0; i< out_length; i++){ int num=i < length_a ? array_a[i] : 0; ... ... ``` what I googled: expr1 ? expr2 : expr3If expr1 evaluates to a non-zero value, expr2 is evaluated, otherwise expr3 is evaluated. The value of the expression as a w...
expr1 ? expr2 : expr3 Equivalent if else is: ``` if(expr1) { //Evaluate expr2 } else { //Evaluate expr3 } ``` So your statement in the code evaluates as: ``` int num=i < length_a ? array_a[i] : 0; ``` means ``` if(i<length_a) { num = array_a[i]; } else { num = 0; } ```
Need to write a program to take input from a user in the form of an int and validate that what they entered is not a char from a-z. Is there another way to do this other than: if((num != 'a') && (num != 'b') && (num != 'c') && (num != 'd') etc.....) printf("You entered %d", num);
Yes, use theisdigit()function provided in thectype.hheader file
I am trying to split a timestamp in C into a suitable format, this format is to behh:mm:ss. The timestamp is stored as a positive integer in the formathhmmss. Is there a way to format this in C? I have no code to show as I have no idea where to start really, my idea is store the timestamp in a character array, then ...
``` int timestamp = 10203; int hour = timestamp / 10000; int minute = timestamp % 10000 / 100; int second = timestamp % 100; printf("%02d:%02d:%02d\n", hour, minute, second); ``` Be careful when the timestamp starts with0, because010203is an octet integer literal, the result may not be what you expected.
A project in C is being forced upon me. I do not have much C knowledge, but I'm assuming the answer is simple. ``` struct s1 { char *text; int num; }; struct s2 { struct s1 vals[5]; int numbers; }; ``` Assume s2 is already populated. How do access num from s1? I was assuming I would do something like ...
Usetemp.vals[0].num. The->operator can only be used if you are using a pointer to a struct. You are using a struct directly.
This is a peice of code ``` maxfd = fileno(stdin)+1; FD_SET(fileno(stdin), &static_rdset); printf("Hello"); select(maxfd+1, &rdset,NULL,NULL, NULL); ``` Problem is that Hello is printed only after I press enter i.e. when stdin is readable.
printf(), when STDOUT is a terminal, does line-buffering. As you have not added a linefeed after "Hello", it remains in the userspace buffer andprintf()does not actuallywrite()"Hello" to STDOUT. Then you callselect()which waits for user input. That achieved, your program exits, but flushes the STDOUT buffer first. T...
I want to mount a block device, especially, optical drives, for instance, /dev/sr0 (or /dev/cdrom) in my application (wrtten in C++) in Linux in order to read each file from the device. I found a mount() function and wrote next code: ``` mount("/dev/sr0", "/path/to/mount/point", "udf", MS_RDONLY, ""); ``` It works v...
Is it impossible to mount a device without root-permission programmatically? Yes, it is not possible. Fromman 2 mount: Appropriate privilege (Linux: the CAP_SYS_ADMIN capability) is required to mount file systems.
This question already has answers here:Optimizing Lua for cyclic execution(2 answers)Closed9 years ago. I have Lua embeded in my C/C++ app. If I run script with ``` lua_pcall( luaState, 0, LUA_MULTRET, 0 ); ``` for the first time, all is OK (return 0). But I need to run script again after some time. Calling same fu...
Push it twice on the stack or store it as a global variable.
I am trying to copy from one string to another, but the second string should omit the space. I tried to approach this by saying, if a character in the original string is a space, do not copy it. Instead, copy the next character. However, the program deletes everything after the space. Any ideas? ``` char deleteSpaces...
Here is a solution: ``` void deleteSpaces(char src[], char dst[]){ // src is supposed to be zero ended // dst is supposed to be large enough to hold src int s, d=0; for (s=0; src[s] != 0; s++) if (src[s] != ' ') { dst[d] = src[s]; d++; } dst[d] = 0; } ```
I'm trying to track a certain applications behaviour, I've grabbed the visible thread that draws the Window, having that thread is there any way to determine the process it belongs to?
You can useGetProcessIdOfThreadapi for newer versions of windows. For older versions you have to find it manually using the ToolHelp library functionsThread32First/Thread32Nextsearching for the threadid and getting the process id from the THREADENTRY32 structure.
I have this simple C program, which changes any array element to 2 inside a function. Although it works, what confuses me is that shouldn't I be passing the array address to the function, instead of the array itself? It's not been working that way... ``` void function(int *val, int element){ *(val+element) = 2; }...
When you pass an array (val) into a function, it decays into a pointer to the first element of the array. The address of the array (&val) points to the exact same address as that ofvalbut has a different type - a type that has the size of the entire array. Here, you are required to pass justval.
I am doing an online course in programming, And I've got assignment to complete, So my problem is I'm not able to useexit(0); in this online compiler, I dont know which compiler is this, however the course is powered by Google. Whatsoever, the error i get is : ``` Program:18:1: warning: implicit declaration of funct...
You need to includestdlib.hforexit.
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.Closed9 years ago.Improve this question ``` #include<stdio.h> int main() { int rowch,row,*order[1]; char columnch, column; scanf("%c%d%s%c%d...
Wrong use ofscanf()format parameter. Checkscanf()result. ``` // int ... *order[1]; // scanf("...%s...",...,&order,...); ``` Should be ``` char order[80]; // select size as needed. if (scanf("%c%d%79s%c%d", &columnch, &rowch, order, &column, &row) != 5) { // Handle format error exit(1); } ``` [Edit] With OP...
``` if(tree->left) if(!(*tree)) ``` Do they mean: ``` if(tree->left==0) if((*tree)==1) ``` I did not find anything about this.
In C there are not booleans but only integers. The if statement just check for equality with 0, evaluating 0 as false and everything else as true, so your examples are equivalent to ``` if(tree->left != 0) if((*tree)==0) ```
I wrote this macro for searching number in array: ``` #define FIND(VALUE,ARR,INDEX){\ int i;\ INDEX = -1;\ for(i = 0;i <sizeof(ARR)/sizeof(VALUE); i++){\ if(ARR[i] == VALUE){\ INDEX = i;\ }\ }\ \ } ``` My questions is, will it be a problem if I defineint iin the macro and ...
Theiin the macro will hide any otherideclared either in the surrounding context or globally. Whether one regards this as a problem or not depends on the need to be able to access the hiddeni.
If i don't pass zero to the array this works absolutely fine why so? When does it really count to add pass zero or specify array has is empty? Please give me an example. ``` #include <stdlib.h> #include <stdio.h> int main() { int i= 34; char array[10]={0}; itoa(i, array, 10); printf("%s\n", array)...
Here, you don't need to initialize the array to zero.itoadoesn't require that the buffer it's using is initialized. It'll just write over anything you initialize the array to, anyway. If you were doing something that actually needed the array to start out full of zeros, the= {0}would be necessary. If you don't initia...
I am trying to change the kernel of the freebsd and I need to use the librarylist.hwhich is in the directory:/usr/src/lib/libc/include/isc. There are two lines in this file which make errors: ``` #include <assert.h> #include <isc/assertion.h> ``` I could find the fileassert.hand put it in the directory but I couldn'...
You can't use /usr/src/lib/libc/include/isc in the kernel. This is part of the user space libc, same goes for assert.h. You can use thesys/queue.hfile if you need linked lists, see e.g.here For assertions in the kernel, use theKASSERT() macro.
I'm having problem withSEGFAULTwhen printing array withprintfusingforloop. Here's my source: ``` #include <stdio.h> int main(){ int a; int b[4]; unsigned short i; scanf("%i", &a); for(i = 0; i <= 3; i++){ b[i] = a % 10; a = a / 10; } ...
ihas a type ofunsigned short, but in your for loop: ``` for(i = 3; i >= 0; i--) ``` i >= 0will NEVER be false becauseiis unsigned.Just changeito a signed type: ``` int i; ``` and it would be fine.
``` if(tree->left) if(!(*tree)) ``` Do they mean: ``` if(tree->left==0) if((*tree)==1) ``` I did not find anything about this.
In C there are not booleans but only integers. The if statement just check for equality with 0, evaluating 0 as false and everything else as true, so your examples are equivalent to ``` if(tree->left != 0) if((*tree)==0) ```
I wrote this macro for searching number in array: ``` #define FIND(VALUE,ARR,INDEX){\ int i;\ INDEX = -1;\ for(i = 0;i <sizeof(ARR)/sizeof(VALUE); i++){\ if(ARR[i] == VALUE){\ INDEX = i;\ }\ }\ \ } ``` My questions is, will it be a problem if I defineint iin the macro and ...
Theiin the macro will hide any otherideclared either in the surrounding context or globally. Whether one regards this as a problem or not depends on the need to be able to access the hiddeni.
If i don't pass zero to the array this works absolutely fine why so? When does it really count to add pass zero or specify array has is empty? Please give me an example. ``` #include <stdlib.h> #include <stdio.h> int main() { int i= 34; char array[10]={0}; itoa(i, array, 10); printf("%s\n", array)...
Here, you don't need to initialize the array to zero.itoadoesn't require that the buffer it's using is initialized. It'll just write over anything you initialize the array to, anyway. If you were doing something that actually needed the array to start out full of zeros, the= {0}would be necessary. If you don't initia...
I am trying to change the kernel of the freebsd and I need to use the librarylist.hwhich is in the directory:/usr/src/lib/libc/include/isc. There are two lines in this file which make errors: ``` #include <assert.h> #include <isc/assertion.h> ``` I could find the fileassert.hand put it in the directory but I couldn'...
You can't use /usr/src/lib/libc/include/isc in the kernel. This is part of the user space libc, same goes for assert.h. You can use thesys/queue.hfile if you need linked lists, see e.g.here For assertions in the kernel, use theKASSERT() macro.
I'm having problem withSEGFAULTwhen printing array withprintfusingforloop. Here's my source: ``` #include <stdio.h> int main(){ int a; int b[4]; unsigned short i; scanf("%i", &a); for(i = 0; i <= 3; i++){ b[i] = a % 10; a = a / 10; } ...
ihas a type ofunsigned short, but in your for loop: ``` for(i = 3; i >= 0; i--) ``` i >= 0will NEVER be false becauseiis unsigned.Just changeito a signed type: ``` int i; ``` and it would be fine.
I am trying to change the kernel of the freebsd and I need to use the librarylist.hwhich is in the directory:/usr/src/lib/libc/include/isc. There are two lines in this file which make errors: ``` #include <assert.h> #include <isc/assertion.h> ``` I could find the fileassert.hand put it in the directory but I couldn'...
You can't use /usr/src/lib/libc/include/isc in the kernel. This is part of the user space libc, same goes for assert.h. You can use thesys/queue.hfile if you need linked lists, see e.g.here For assertions in the kernel, use theKASSERT() macro.
I'm having problem withSEGFAULTwhen printing array withprintfusingforloop. Here's my source: ``` #include <stdio.h> int main(){ int a; int b[4]; unsigned short i; scanf("%i", &a); for(i = 0; i <= 3; i++){ b[i] = a % 10; a = a / 10; } ...
ihas a type ofunsigned short, but in your for loop: ``` for(i = 3; i >= 0; i--) ``` i >= 0will NEVER be false becauseiis unsigned.Just changeito a signed type: ``` int i; ``` and it would be fine.
How do you increase the post-fix operator by more than the default of one?(i.e. applying a post-fix operator to 4 so that it increases the value to 6 instead of 5) This question pertains to a for loop I want to create where I am to check every second number of a given string to validate. I thought incrementing the i ...
You cannot overload the ++ operator for built in types, no. The simplest way would be to use ``` var += step; ``` and ``` for(i=0; i<end; i+=4) { ... } ``` Note that using the less than instead of equality leads you to not stress about end point not lining up exactly. Of course there is always ``` for(i=0; i<...
This question already has answers here:How do I check if an integer is even or odd? [closed](30 answers)Closed9 years ago. How can I check if a variable (an int) is even (that is, not odd) in C without using "%" operator? I am running on linux platform. Thank you.
``` if (!(v & 1)) ``` should be true for even numbers
I'm trying to call a function written in C which passes in a pointer to an array. In C++ I have the following: ``` double* x = new double[10]; populateArray(x); ``` In C: ``` void populateArray(double* vars); { vars = (double*) malloc(10*sizeof(double)); int i; for(i = 0; (i < 10); i++) { ...
Problem arises because you are changing local variablevars. Change to: ``` double* x; //you don't need to allocate here if you are allocating later populateArray(&x); ``` And: ``` void populateArray(double** vars) { *vars = malloc(10*sizeof(double)); //also no need to cast malloc int i; for(i = 0; ...
I'm doing a simple bit of maths on a PIC microcontroller, running code in C and using MPLABX and the xc16 compiler. This is the code: ``` double mydouble = 0.019440; long long int mypower = 281474976710656; long long int result = mypower*mydouble; ``` Printing out 'result' gives me 5,471,873,794,048; while it shoul...
xc16 handles both double and float as 32-bit data types by default. You need to give the compilation option-fno-short-doubleto use 64-bit doubles. You may also be able to just uselong doubleas a data type, but I can't compile at the moment to verify that. (As a test, 5,471,873,794,048 is also exactly the result you ...
What does the following c code trying to do. I am not sure what does it calculate the value of width to ``` (width+31)&~31 ``` Thank you.
It is rounding up to the next multiple of 32. It only works because 32 is a power of 2. ``` The bit pattern for 31 is ...000000000011111 The bit pattern for ~31 is ...111111111100000 ``` When you and ~31 with any positive integer, you get a multiple of 32 (five low order bits are all zeroes).
I would like to use a function from another directory. So I put this line on the top, ``` #include "~/ffmpeg/include/libavcodec/avcodec.h" ``` and ran ``` gcc filename.c ``` and getting this error ``` error: avcodec.h: No such file or directory ``` The spelling is correct and the file exists. Why does the compil...
Use: ``` #include <avcodec.h> /* NOT "avcodec.h" */ ``` Then: ``` gcc -I/include/file/path/where/avcodec.h/lives ``` If you use-I, use the angle-brackets, if you want to include based on a path relative to the file containing the#include, use the quotes. I would use: ``` #include <libavcodec/avcodec.h> ``` a...
I'm writing a program A and use syslog() to do logging. Instead of logging to default /var/log/messages or other default system log files, can I specify my own log file and use syslog() to log to it? (I really want to make use of syslogd's facility to manage this log file.) What configurations is needed in /etc/syslog...
You'll need to pick a logging facility, presumably one of LOG_LOCAL0 through LOG_LOCAL7 (though it's unlikely anyone will notice LOG_NEWS or LOG_UUCP being overwritten), and then create a line in syslog.conf in the form of: ``` localn.* my_logfile ```
I have inserts.txt file which contains some "INSERT ..." commands and an empty Sqlite3 database. I typed this command in commanline: ``` sqlite3 database.db '.read inserts.txt' ``` after that my database was populated. But if there are some wrong queries in txt file I get some errors like ``` Error: no such table:...
If you're writing a C program using sqlite3 C API, use thesqlite3_errmsg()to get a human-readable error message. Otherwise please clarify your question.
I have write the following code , but the compiler tell me that 'S_FIFO' is not declared , i was think that the problem is that library that containe 'S_FIFO' is not include , so i have included the last 3 library , but the problem does not solved ? ``` #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #...
You've included the correct library, but spelled the function name and macro names wrong. It should bemknod()function with the macroS_IFIFO.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed9 years ago.Improve...
There's nothing you need to do. It's legal C++ as is.
I want to execute a C program in Linux usingforkandexecsystem calls. I have written a programmsg.cand it's working fine. Then I wrote a programmsg1.c. When I do./a.out msg.c, it's just printingmsg.cas output but not executing my program. ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> /* for fork */ #...
argv[0] contains your program's name and you are Echo'ing it. Works flawlessly ;-)
Can somebody spot what's the problem with the following program, it doesn't print the numbers of the array like it supposed to ``` #include<stdio.h> #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0])) int array[] = {23,34,12,17,204,99,16}; int main() { int d; for(d=-1;d <= (TOTAL_ELEMENTS-2);d++) ...
You need to cast the condition: ``` d <= (int)(TOTAL_ELEMENTS-2) ``` sizeofreturns the number of bytes in unsigned format. Before CastandAfter Cast. Macros are not type-safe by themselves, without the cast both values get converted to unsigned values, and the result is false.
I found this code on SO. ``` unsigned char * SerializeInt(unsigned char *buffer, int value) { /* Write big-endian int value into buffer; assumes 32-bit int and 8-bit char. */ buffer[0] = value >> 24; buffer[1] = value >> 16; buffer[2] = value >> 8; buffer[3] = value; return buffer + 4; } ``` You can see ...
Whatever is the endianness of your system, yourSerializeIntfunction will storevaluein big endian in the arraybuffer. It is stored as big endian as it writes the most significant byte first. Remember that when you evaluatevalueit has no endiannessper se, it's like any mathematical value.
This question already has answers here:String has contents even though there is no input from user(4 answers)Closed9 years ago. I am trying to find the prefix between two words,but it seems like what I have is not correct. Firstif(strlen(root) == 0)always evaluates to 0. Why? ``` The longest common prefix of astroph...
Yourrootcontains garbage values, you need to initalize itchar root[256 + 1]={0};And after your while loop,root[i]='\0'; Now, try it.
I want to divide a graph to subgraphs that each subgraph made from maximum 3 vertices and sum of weight of edges is minimized, the main graph is complete ( have all possible edges ), and edges are weighted. the main problem that i want to solve is finding close three threes points on a map.
I'm sure this problem is NP-Complete. It's called theminimum k-cut problem. Try to take a look at thisarticle. It talks about approximation algorithms to solve such problems.
It seems simple but I couldn't get it to work. I want to print out the format of an image by using ``` cvGetCaptureProperty(image, CV_CAP_PROP_FOURCC) ``` whereimageis an object of CvCapture struct. This function returnsdouble. I did convert it to char* so that I can print out the format but it didn't work. Any sug...
Get adouble*and convert that: ``` double f = cvGetCaptureProperty(image, CV_CAP_PROP_FOURCC); char* fourcc = (char*) (&f); // reinterpret_cast ``` However,this OpenCV highgui tutorialsuggests the following with the C++ interface: ``` int ex = static_cast<int>(inputVideo.get(CV_CAP_PROP_FOURCC)); // Transform from ...
I'm trying to read in user input for a file name, to which I then attempt to open the file specified. The problem I'm getting is that there seems to be junk characters added on to the end of the input. (I discovered this when trying to printf() the userInput variable). ``` if(read(0, userInput, 128) < 0) write(2,...
You haven't posted enough info to post a definite answer, but here's my educated guess: C strings are null terminated. If you read only a partial string and don't terminate it, but try to print it as a C string, you'll get undefined behaviour - in practice, you'll see the garbage following it.
I am trying to grab frames from a point grey firefly mv, and I have written an interface for my program using dc1394 driver. The driver works fine when I the firefly is connected to a USB 2.0 port, but when I connect to a USB 3.0 port, dc1394 throws the following error on the function call dc1394_capture_setup() ``` ...
Turns out that the problem can be solved with by updating to firmware version 1.6, and updating the linux kernel. It doesn't work at 3.5, it does work at 3.11. I'm not sure about in between.
Does anyone know what an identifier does in a C function parameter list? The code looks like ``` #define IDENTIFIER_NAME int foo(int IDENTIFIER_NAME x); ``` I appreciate any answer.
Since#definedoes not provide a replacement forIDENTIFIER_NAME, C preprocessor removes the string from the source code. This trick may be used for writing custom tools that process C files to collect identifier names: one could write a very simple script that findsIDENTIFIER_NAMEin the source, grab the next token, and...
I found another thread containing some information, but I still am a bit confused. I think this is correct, however. I figured that global scope and file scope were the same thing, though? My options are local/function scope, global scope, file scope. This is referring to C, if that makes a difference. ``` QUESTION ...
I figured that global scope and file scope were the same thing, though? File scope means the identifier is only "known" within the specific file it appears in, e.g.main.c. Global scope means it is visible to the entire program, no matter whichcfile it is defined in.
For example, if my program tries to create a directory usingCreateDirectory()inC:\ProgramFiles (x86)\[install directory]\, it will fail due to permissions issues. I have heard that the ideal location isC:\Users\[username]\AppData\Local\, but are there other "safe" locations? Of course it may vary depending on the ve...
C:\ProgramData is other location which is used commonly. This below is helpfull,http://blogs.msdn.com/b/cjacks/archive/2008/02/05/where-should-i-write-program-data-instead-of-program-files.aspx
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question appears to be off-topic becauseit lacks sufficient information to diagnose the problem.Describe your problem in more detail orinclude a minimal examplein the question itself.Closed9 years ago.Improve this q...
Hard-code the traversal of two strings in a while loop. If they're the same, output either string1[i] or string2[i]. If they're different, write a star.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question I have a library written in C that in turn is build upon the GMP library. I want to know...
I think php'sexecorshell_execfunctions can help you out ... this functions are used forExecute an external program take a look at this... http://www.php.net/manual/en/function.exec.php
I am trying to parse through a file, and store the results using a struct, but I keep getting a segmetaion error and I cant seem to figure out why. ``` while (token ! = NULL) { token =strtok(NULL, " "); if (token[0] == 'd') { if (token[1] == 'e') { ...
What about check following token is NULL. ``` token =strtok(NULL, " "); ``` You should also NULL check it. ``` if(token != NULL) { } ```
What is an easy way to convert a string "1 0 2 1 4 5 6 195" to an int array (or a vector)? I am aware of the possible solutions but they all seem too complicated for my purposes (string is formatted as given in example). std::string or char[] are both ok.
``` #include <string> #include <vector> #include <sstream> #include <iterator> // get string std::string input = "1 0 2 1 4 5 6 195"; // convert to a stream std::stringstream in( input); // convert to vector of ints std::vector<int> ints; std::copy( std::istream_iterator<int, char>(in), std::istream...
I'm trying to swap 2 nodes with a XOR linked list my struct : ``` typedef struct s_node { struct s_node *ptr; int data; } t_node; ``` and my function (where I want to swap x and y) a is the prev of x and b the next of y ``` void swap_node(t_node *a, t_node *x, t_node *y, t_node *b) { //Swapping x->pt...
I understood The trick is : for to get the next of a is : XOR(a->ptr, x) and for the prev of b is XOR(b->ptr, y) so ``` a->ptr = xor_node(xor_node(y, a->ptr), x); b->ptr = xor_node(xor_node(x, b->ptr), y); ```
I am trying to parse through a line a line of text from a .txt file and set it to a string. It is parsing most of the lines, except for the first 4 characters. This is what I'm trying to parse: 12X6 de8 dw3 ds5 g8,7 m3,4 p2,2 h2,2 And this is my code: ``` FILE * rooms; int i; char c; char roomString[ROOM_STRING_LEN...
Yourfscanf()call consumes the first word of the input. Remove that call. ``` if(rooms == NULL) { printf("error opening file\n"); } //fscanf(rooms, "%s", roomString); while((c=fgetc(rooms))!='\n') ```
How can I (quickly) calculate the number of Wednesdays that have occurred in the current year? For example a functionnum_wednesdays()would return1when called on January first of 2014,1on January 7th, and2on January 8th 2014. EditThis is what I settled on. ``` int num_wednesdays() { time_t now, then; struct tm * ...
Easiest way: since Wednesdays occur every 7 days, you only need to find when the first Wednesday of the year occurred and then calculate the number of 7-day periods since that day.
(I didn't know the correct terminology for this in order to do a search or give an appropriate title) I have always wondered: does it matter (speedwise or compiled sizewise) if one uses a function call to provide the argument to another function? I can see hownotdoing that can aid code readability but sometimes using...
The order in which the parameters are evaluated is undefined. If the functions are pure, this should not matter, but if they have side-effects, it could.
For example, how are the following statements equal to each other? a) 0116 = 0x4E b) 97 = 00141 = 0x0061 c) 45 = 0x2d= 0055 Ive tried looking it up but it still doesn't make sense to me. Thanks.
If it begins with0xor0X, it is a hexadecimal number, ie. base16. Else if it begins with just0, it is an octal number, ie. base8. Else it is a decimal number, ie. base 10. (the following is non-standard - a gcc extension) if it begins with0b, it is a binary number, ie. base2.
I want to write a function that gets a number X and if X=5 it returns 7 , if X=7 it return 5 otherwise, return something else. There is the trivial way - to use "if" blocks Another way - to use a map (5 mapped to 7, 7 mapped to 5) Third way - to write the matching linear mathematical equation BUT I'm looking for the ...
``` int fun(int p) { return p^2; } ```
I'm a C newbie. I want to enter a string using fgets and have it execute as a shell command. I know its possible to do something like ``` echo `ls` ``` in Perl. I want to do something similar in C. What am I doing wrong? Here is some of the code I'm using: ``` printf("Enter a command: "); fgets(buf, sizeof(buf), st...
Try usingsystemcommand. The C library function int system(const char *command) passes the command name or program name specified by command to the host environment to be executed by the command processor and returns after the command has been completed.
I executed following piece of code: ``` int a[] = {5,1,15,20,25}; int i,j,m; i = ++a[1]; j = a[1]++; m = a[i++]; printf("%d %d %d",i,j,m); ``` and I got output as follow :- ``` 3 2 15 ``` The part which I don't understand is how I got value ofias3 It should be2right? Or is it related with C compiler's right to l...
Them = a[i++]line incrementedifor a second time, from 2 to 3.
I roughly read http://linux.die.net/man/2/forkandhttp://linux.die.net/man/3/fork got confused. can anybody briefly explain to me difference between fork(3) and fork(2) thank you
fork(2) is the kernel call and fork(3) is the posix library call
I want to write a function that gets a number X and if X=5 it returns 7 , if X=7 it return 5 otherwise, return something else. There is the trivial way - to use "if" blocks Another way - to use a map (5 mapped to 7, 7 mapped to 5) Third way - to write the matching linear mathematical equation BUT I'm looking for the ...
``` int fun(int p) { return p^2; } ```
I'm a C newbie. I want to enter a string using fgets and have it execute as a shell command. I know its possible to do something like ``` echo `ls` ``` in Perl. I want to do something similar in C. What am I doing wrong? Here is some of the code I'm using: ``` printf("Enter a command: "); fgets(buf, sizeof(buf), st...
Try usingsystemcommand. The C library function int system(const char *command) passes the command name or program name specified by command to the host environment to be executed by the command processor and returns after the command has been completed.