question
stringlengths
25
894
answer
stringlengths
4
863
How would I go about writing a program in C that repeatedly prints out a string, but at different speeds. Basically, how to increase time between each return in a loop?
How would I go about writing a program in C that repeatedly prints out a string, but at different speeds. You can merly increase a program's speed. But you can delay it more or less. ``` #include <stdio.h> int main(void) { while (1) { printf("Hello World!\n"); <delay more or less here> } } ``` Under...
I want to load a big array to GPU shared memory. when I employ that just like bellow: int index = threadidx.x;shared unsigned char x[1000];x[i] = array[i]; Then if we call a kernel code with 1000 threads and one block, for every thread a memory access will occur? Is it possible to load this array by a single memory...
No it can't be done with a single access. Using threads in parallel to load shared memory, just as you have shown, is the fastest way. Shared memory canonlybe loaded by memory operations performed by threads in CUDA kernels. There are no API functions to load shared memory. If you have an array that is larger than...
when i trying to compile an old c source code using msys2 this error happens: "configure: error: POSIX regex functions required and missing!" Please any idea? Is that a library that can be added or it's an error related to the code itself?
It's not clear whether you want to build an MSYS2 or a native program. Anyway .. MSYS2 has the following regex libraries. You can search for them yourself via: ``` pacman -Ss regular ``` From the mingw{32,64} (i.e. native) repositories: ``` mingw-w64-{x86_64,i686}-oniguruma mingw-w64-{x86_64,i686}-pcre ``` From t...
This question already has answers here:scanf: floating point format not linked [duplicate](3 answers)Closed8 years ago. I am getting a runtime error while running the following code. ``` #include<stdio.h> int main() { struct emp { char name[20]; float sal; }; struct emp e[10]; int...
Add the following anywhere outsidemainafter all the includes. ``` void dummy(float *a) { float b=*a; //perform some floating access dummy (&b); //calling a floating point function } ``` You need not call this function
Whenever i define this string as a number, it gives me the error'Passing const char to incompatible type double'. When i define the string as xlSheetWriteStr there are no issues but when i define it as a number it gives me the error. Here is the code with the issue - ``` xlSheetWriteNum(sheet, 2, 1,[self.personcityT...
The fourth parameter toxlSheetWriteNumexpects a double and not a string value. Try this: ``` xlSheetWriteNum(sheet, 2, 1, [self.personcityTextField.text doubleValue], 0); ```
Ifsis a string (say"thisisthe"), how do I store the first byte into a another strings2? ``` #include <stdio.h> int main() { char s[]="thisisthe"; char s1=s[0]; // Store the first byte of s as a char. char s2[]=s[1]; // store the second byte of s as a string. printf("%s\n",s2); return 0; } ```
In C, a string it an array of characters terminated by a NUL. ``` char s2[2]; s2[0] = s[1]; s2[1] = '\0'; ``` But maybe you just want ``` char c2 = s[1]; printf("%c\n", c2); ```
How to perform a divisionANDa modulo at the same time. Is it possible for the processor ? Like : ``` int a, b = 8 / 3; //a = 2, b = 2 ``` Or is there an operation which is better than : ``` int a = 8 / 3; int b = 8 % 3; ``` Maybe this is better ? ``` int a = 8 / 3; int b = 8 - a * 3; ``` Thanks.
Consider the following function: ``` std::pair<int, int> divmod(int x, int y) { return { x / y, x % y }; } ``` Compiling this withg++ -std=c++11 -O1 -Sspits out the following assembly code: ``` movl %edi, %eax cltd idivl %esi salq $32, %rdx movl %eax, %eax orq %rdx, %rax ret ``` As you can see, ...
I'm writing a C program in class that requires us to input dates as integers in a structure defined as: ``` typedef struct date{ int month; int day; int year; }Date; ``` Now that really would not be a problem except it requires that you can only input it as mm/dd/yyyy. I was thinking if maybe I can in...
``` scanf("%d/%d/%d",&d,&m,&y); ``` Is probably what you are looking for. This will ignore the / in the input
I have to read a csv file usingfscanffunction (I cant use any other function likestrtok_sto parse the line) and im having the following problem. Here is the code: ``` fp1 = fopen (argv [1],"r"); var = fscanf (fp1,"%d,%d,%[^,]s,%[^,]s",&aux.points,%aux.titles,aux.name,aux.nation); ``` I'm trying to print each param...
Try this as the string: "%d,%d,%[^,],%[^,]" I eliminated the "s" because [...] acts as the specifier. Think of the [...] as a super s.
First off I'm primarily a Java programmer, but I've been tasked with doing some network stuff in C. I've got a function with the following signature: ``` foo(int, void (*) (int, char *, int)) ``` It's thevoid (*)that's throwing me for a loop. This is supposed to call another function (static) ``` bar(int, char *, i...
foo(1,myfunction(1,&anCharArray,10))fails with a number of errors. Try instead: ``` foo(1, myfunction) ``` The second parameter offoofunction is a function pointer but you were passing the return value of a function call.
This question already has answers here:scanf: floating point format not linked [duplicate](3 answers)Closed8 years ago. I am getting a runtime error while running the following code. ``` #include<stdio.h> int main() { struct emp { char name[20]; float sal; }; struct emp e[10]; int...
Add the following anywhere outsidemainafter all the includes. ``` void dummy(float *a) { float b=*a; //perform some floating access dummy (&b); //calling a floating point function } ``` You need not call this function
Whenever i define this string as a number, it gives me the error'Passing const char to incompatible type double'. When i define the string as xlSheetWriteStr there are no issues but when i define it as a number it gives me the error. Here is the code with the issue - ``` xlSheetWriteNum(sheet, 2, 1,[self.personcityT...
The fourth parameter toxlSheetWriteNumexpects a double and not a string value. Try this: ``` xlSheetWriteNum(sheet, 2, 1, [self.personcityTextField.text doubleValue], 0); ```
Ifsis a string (say"thisisthe"), how do I store the first byte into a another strings2? ``` #include <stdio.h> int main() { char s[]="thisisthe"; char s1=s[0]; // Store the first byte of s as a char. char s2[]=s[1]; // store the second byte of s as a string. printf("%s\n",s2); return 0; } ```
In C, a string it an array of characters terminated by a NUL. ``` char s2[2]; s2[0] = s[1]; s2[1] = '\0'; ``` But maybe you just want ``` char c2 = s[1]; printf("%c\n", c2); ```
I'm new to Emacs. How can I set the Flycheck package to use C standard 99 (C99 mode)? For the following code: for(int i = 0; i < n; i++)... Flycheck will throw me:for loop initial declarations are only allowed in C99 mode.
Setflycheck-clang-language-standardorflycheck-gcc-language-standard(depending on what tool you installed) to"gnu99", viaDirectory VariablesorFile Variables. For the former, typeM-x add-dir-local-variable RET c-mode RET flycheck-clang-language-standard RET "gnu99". To set the standard globally, use a C mode hook to s...
I have written the following code: ``` #include <stdio.h> /* max_number.c: outputs the largest number of five numbers entered */ void main(void) { int i, num, max; for (i = 1; i <= 5; i++) { printf("Enter a number: "); scanf("%d", &num); if (num >= max) max = num; } printf("The maximum n...
Variablemaxis not initialized. Try ``` int i, num, max = INT_MIN; ```
Even a simple HelloWorld program is taking about 30 seconds to run. Is there a way to speed up the execution? I tried it in codeblocks using MinGW. I have also tried it with Borland c++ 5.5 command line tools. In both the cases it took about 20 to 30 seconds to run, however compilation was quick. ``` #include<stdio.h...
Are you running antivirus software? My guess is that yours insists on heavy scanning of newly created executables before allowing them to run. Another possibility is that (at least) one directory in the pathname for the executable file (or for some DLL it depends upon) has a very large number of files in it. On some ...
Determine if all even place bits (counting from left to right) are set to 1. For instance,0101 0101would count whereas1011 1000would not count. If the the bit has 1's in all even places, return 1, or else return 0. Constraints: must only use bitwise operators. Cannot use conditionals. Biggest integer you can use in ...
Assuming that>>counts as a bitwise operator, the following only needs constants up to 16. ``` int allEven(unsigned x) { x &= x >> 16; x &= x >> 8; x &= x >> 4; x &= x >> 2; return x&1; } ```
Hello I am wondering why this works since on tutorials and such it always lists that arrays must be of fixed size except when dynamically making one with malloc. ``` #include <stdlib.h> #include <stdio.h> int main(int argc, char **argv) { if(argc < 2) return 0; int tmp[ atoi(argv[1]) ]; ...
C99 introducesvariable length arraywhose length is not a constant expression. The declaration ``` int tmp[ atoi(argv[1]) ]; ``` declarestmpas VLA.
I want to end my main function if the user enters a value out of range. For some reason, this doesn't seem to work. ``` fscanf(stdin, "%d", &T); if(!(T >= 1 || T <=500)) exit(0); ``` What is the best way to go about doing this?
For any value ofT,T >= 1 || T <=500becomestrue. This is because each and every value is either greater than1orless than500. IfTis0then it is less than500and ifTis501then it is greater than1. This results in!(T >= 1 || T <=500to befalsealways. Try this instead ``` if( T < 1 || T > 500 ) exit(0); ``` or you can corre...
What would be the best way to read this data from atxtfile? ``` 12 name1 2 1 65000 13 name2 5 3 30000 17 name3 2 3 30000 20 name4 3 2 58000 ``` Notice that the whitespace may change with every line. I was thinking in doing something like this: ``` while (fscanf(f...
There is no need to use Regex. Simply use fscanf as mentioned by user3121023 ``` while ( fscanf ( file, "%d %s %d %d %d", &digit[i], &str[i], &number[i], &value[i]) == 4) { i++;} ```
When i am working of with character strings. I have something like this: ``` #include <stdio.h> #define MAXLINE 1000 main(){ int c; int i=0; char s[MAXLINE]; while(c=(getchar()) !=EOF) { s[i] = c; ++i; } } ``` I want to ask after i write something likeHELLOand then hitenterto break line does the '\n' adds ...
The way your code is written, there is no NUL character added tos. Since you are reading the input one character at a time, if you wantsto be NUL-terminated you'll need to add the NUL yourself.
I spend most of my time solving problems on Topcoder/SPOJ. So definitely I thought of performance (execution time) of my code on my system before submitting the code. So, on searching I foundtimecommand in linux. But the problem is that it also includes the time for inputting the values for several test cases, in ad...
You need this: ``` ./myprogram < input.txt ``` Or if you insist on the Useless Use of Cat: ``` cat input.txt | ./myprogram ``` You can puttimein front of./myprogramin either case.
How can I skip a value and go to the next one infscanf()? For example I have the following data in my input file: ``` 11112222 3.95 4 22.5 ``` What I should do in order to scan the second value? (I want to skip 11112222 to scan 3.95) And one more thing: if I want tofscanf()a specific data type, how can I do that? (...
You can use a*modifier to scan a value and throw it away rather than storing it. For example: ``` if (scanf("%*d%lf", &var) != 1) …process input error… ``` will read the first two lines of your input file and store the value from the second into the double variablevar
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
Just download and install the free and prebuilt Codesourcery/Mentor Arm cross-compiler and toolchain fromhere.
I'm using GCC to compiler and I want to print the full path of the file using__FILE__, but GCC shows only the name of the file. In MSVC is the same, but you can use an argument/FC (Full Path of Source Code File in Diagnostics)and it works. Is there any equivalent to GCC? ``` int main(int argc, char ** argv) { std...
I couldn't find any equivalent, but I realized that__FILE__macro expands to the name of the current input file via the path used by the preprocessor to open the file. So it will depend on what is passed to the compiler. I solved it usingCMakeas build system. WhenCMakecreates the MakeFile it uses the full path in the ...
Is it necessary to call functions likesetbuf()andsetvbuf()when I openFILEstreams to adjust buffering?Isn't I/O buffering handled automatically?
No, buffering is handled automatically, butmaybe not in the fashion you want or need. You might want flushing on each write, only on newline, only on full buffer, and the default is wrong for your case. Or you might want a bigger buffer for efficiency. In all those cases, adjust the default.Though, in general the d...
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 There is static linkage, dynamic linkage. What is type where it imports compiled functions from a library ...
In static linking, the compiled functions are stored into the executable or dynamic library (if you're creating one). In dynamic linking, the compiled function is stored in a separated library (DLL in Windows or shared object in Linux). A small piece if code is added to the executable to load that shared library at r...
I am trying to write a function which can take array of any dimension and print values in the array successfully. But I am not able to move forward because we have to declare all the dimensions except left most one when declaring function. Is there any possibility that we can write a generalised function which can tak...
Usingrecursionfor each dimension and template (so in C++), following may help: ``` template <typename T> void print(const T&e) { std::cout << e << " "; } template <typename T, std::size_t N> void print(const T (&a)[N]) { std::cout << "{"; for (const auto& e : a) { print(e); } std::cout <<...
This question already has answers here:Random numbers in C(10 answers)Closed9 years ago. I have a function to get a random number returned from functionroll_dicehowever it seems to be a problem when i´m calling it agian, it gives me the same number, somehow its not given a new seed when called agian. ``` int roll_di...
time(NULL)returns seconds and your function is very fast so you are probably seeding with the same number in both runs. You should only seed your random number generator once.
I came across a interview question which reads as follows: "Write a simple C/C++ Macro to find maximum of two numbers without using std library or ternary operator". I need your help in solving this. I know this is trivial but I couldn't find it. So, posting it here. ``` #include<iostream> #define max(x,y) /*LOGIC ...
Use Boolean operations to get 0 or 1 and then just add them up: ``` #define max(x,y) (((int)((x)<(y)) * (y)) + ((int)((y)<=(x)) * (x))) ```
I have a thread function defined as below: what is the different between exit() and pthread_exit()? ``` result = pthread_create(&consumer_thread, NULL, consumer_routine, &queue); if (0 != result) { fprintf(stderr, "Failed to create consumer thread: %s\n", strerror(result)); exit(1); } result = pthread_join(...
Theexitfunction terminates the process normally, flushing buffers, callingatexithandlers, and so on. Thepthread_exitfunction terminates the calling thread, terminating the process only if it's the last thread in the process. Otherwise, the other threads in the process can continue to operate.
How can I tell what version of the C library python's zlib module was built with? Specifically, I want to tell whether it was a new enough version to support ZLIB_RSYNC=1 This is different than the version of the zlib pythonmodule, but instead the version of the underlying C library
It iszlib.ZLIB_VERSION: ``` >>> import zlib >>> zlib.ZLIB_VERSION '1.2.7' ```
This is the code that I used. It works perfectly, but I don't understand why it works. I just kept changing my original logic until I started using -1 in the counter loop. ``` #include<stdio.h> #include<math.h> int main(){ int number, reverse, sum =0; scanf("%d", &number); int temp = number; int ctr;...
same basic math but so much easier to understand: ``` unsigned int number = 123456789; unsigned int reversed = 0; do { reversed *= 10; reversed += number % 10; number /= 10; } while (number > 0); ```
Let's have two lines of code: ``` &car->speed &(car->speed) ``` Are these two lines equivalent? Will I get in both cases address to thespeed?If they are equivalents, what is better to choose as coding convention?
Are these two lines equivalent? Will I get in both cases address to the speed? Yes.->has higher precedence than that of unary&, therefore&car->speedand&(car->speed)are equivalent. If they are equivalents, what is better to choose as coding convention? Go with second as it shows the intended behaviour that you are i...
I came across a interview question which reads as follows: "Write a simple C/C++ Macro to find maximum of two numbers without using std library or ternary operator". I need your help in solving this. I know this is trivial but I couldn't find it. So, posting it here. ``` #include<iostream> #define max(x,y) /*LOGIC ...
Use Boolean operations to get 0 or 1 and then just add them up: ``` #define max(x,y) (((int)((x)<(y)) * (y)) + ((int)((y)<=(x)) * (x))) ```
I have a thread function defined as below: what is the different between exit() and pthread_exit()? ``` result = pthread_create(&consumer_thread, NULL, consumer_routine, &queue); if (0 != result) { fprintf(stderr, "Failed to create consumer thread: %s\n", strerror(result)); exit(1); } result = pthread_join(...
Theexitfunction terminates the process normally, flushing buffers, callingatexithandlers, and so on. Thepthread_exitfunction terminates the calling thread, terminating the process only if it's the last thread in the process. Otherwise, the other threads in the process can continue to operate.
How can I tell what version of the C library python's zlib module was built with? Specifically, I want to tell whether it was a new enough version to support ZLIB_RSYNC=1 This is different than the version of the zlib pythonmodule, but instead the version of the underlying C library
It iszlib.ZLIB_VERSION: ``` >>> import zlib >>> zlib.ZLIB_VERSION '1.2.7' ```
This is the code that I used. It works perfectly, but I don't understand why it works. I just kept changing my original logic until I started using -1 in the counter loop. ``` #include<stdio.h> #include<math.h> int main(){ int number, reverse, sum =0; scanf("%d", &number); int temp = number; int ctr;...
same basic math but so much easier to understand: ``` unsigned int number = 123456789; unsigned int reversed = 0; do { reversed *= 10; reversed += number % 10; number /= 10; } while (number > 0); ```
Let's have two lines of code: ``` &car->speed &(car->speed) ``` Are these two lines equivalent? Will I get in both cases address to thespeed?If they are equivalents, what is better to choose as coding convention?
Are these two lines equivalent? Will I get in both cases address to the speed? Yes.->has higher precedence than that of unary&, therefore&car->speedand&(car->speed)are equivalent. If they are equivalents, what is better to choose as coding convention? Go with second as it shows the intended behaviour that you are i...
This question already has an answer here:Getting my own IP address by connect()ing using UDP socket?(1 answer)Closed9 years ago. I'm trying to get my own IP address by trying to connect() to 8.8.8.8 usingUDPsocket and then callinggetsockname()function. I've written a functionget_my_ip(), and the code worked when it ...
You must initialize addrlen. ``` addrlen = sizeof remoteaddr; getsockname(sockfd, (struct sockaddr*)&remoteaddr, &addrlen); ```
I've for the first time begun using SetupAPI on Windows and notice that I always need to put the size of a struct into the struct before calling a function that populates the struct. For instance: ``` SP_DEVICE_INTERFACE_DATA dintf_data; dintf_data.cbSize = sizeof(dintf_data); SetupDiEnumDeviceInterfaces(di, NULL, &...
Yup, you got it, API versioning. The OS checks the size passed in to determine which version of the structure you are using. As features are added for newer versions of the API, fields are added (never removed), to increase the size, so the OS can know easily exactly which version you are using.
From which file ifconfig command takes input for displaying ip address, inet addr and h/w addr ?. I want this information for my presentation. Any file apart from /etc/network/interfaces is there ? Looking foreword for help.
It's in the manual man. just run commandman ifconfigin your terminal and at bottom it says it comes from these three files: ``` FILES /proc/net/socket /proc/net/dev /proc/net/if_inet6 ``` Hope it works.
If the following array contained shell code in a C program on a LINUX machine ``` char buf [100] ``` then how does the following execute this shell code : ``` ((void(*)())buf)() ```
Simple. It castsbufto a pointer-to-function taking no arguments and returningvoid, and then invokes that function. However, that probably won't work since the page containingbufis highly unlikely to be marked as executable.
I have the following struct (On C) : ``` typedef struct Piece { ePieceType PieceType;//enum ePlayer Player;//enum int IsFirstMove; } sPiece; ``` (On C#): ``` [StructLayout(LayoutKind.Sequential)] public struct Piece { public PieceTypeEnum PieceType; //same enum order like ePieceType public Play...
The answer is: Just declare it Piece [] and pass an array with 64 elements Posted in comments by Hans Passant(but somehow did not raise it as an answer).
I'd like to know why I am getting this, Error: ``` error: dereferencing pointer to incomplete type strncpy(variables->part1[i], environ[i], placement); ``` main Code: ``` struct vars { char **part1; char **part2; } ; static struct vars *variables; exportenviron(&variables); ``` function Code: ``` void e...
The file containingexportenvironisn't seeing the actual definition of your struct: instead, it only knows thatstruct varsexists, but not what's in it. For example, perhaps you have a header filevars.hincluded by the .c file withexportenvironin it, andvars.hcontains onlystruct vars;
I am reading the current directory and printing it out using ``` printf("%s\n", file->d_name); ``` but it also prints out "." and ".." files. How can I exclude them?
The simple way: just make sure the file name isn't"."or".."before you display it. :P ``` if (strcmp(file->d_name, ".") && strcmp(file->d_name, "..")) { printf("%s\n", file->d_name); } ```
I am doing in a simplistic experiment as below: ``` glPushMatrix(); glGetDoublev(GL_MODELVIEW, modelMatrix); glTranslatef(...); glGetDoublev(GL_MODELVIEW, modelMatrix); glPopMatrix(); ``` However, after the translation, there is not change in the modelview matrix. I am wondering why is that, and how can I see the e...
Your code is invalid. The correct enum forglGet...()isGL_MODELVIEW_MATRIX, notGL_MODELVIEW(which is a constant for useglMatrixMode()), so all you get is some GL error, and the memory atmodelMatrixwill be not touched at all, so it is probably just left uninitialized.
Using C, can the functionfreadbe used to read a null terminated string? I have to read a file that starts with an ip as 4 unsigned chars followed by an integer describing the number of null terminated strings. After that, I need to read the strings until the last one before another ip list starts. I greatly apprecia...
freaddoes not stop reading at any delimiter,'\0'or otherwise. It attempts to read the exact number of bytes requested, and will only stop earlier if it encounters end-of-file or a read error. On POSIX 2008 conforming systems, thegetdelimfunction provides an easy way to "read until'\0'". Otherwise, you're stuck with a...
I'm trying to create a game for my CS assignment and I'm stuck with this for loop that won't end my game even though the lives are already at zero. ``` for(life = 3, ai_life = 3; ai_life != 0, life != 0; --ai_life, --life) ```
Please read up what thecomma operatordoes ``` for(life = 3, ai_life = 3; ai_life != 0 && life != 0; --ai_life, --life) ```
I create empty c++ project(VS-2010) that contain c file & header: I change the sub system of this project to console. then I compile and run it. Now I want to use the dll of this project on C# (I know how to do it, it's not my question)!! where I found the dll? (or I didn't create it????) On the debug folder I ...
It doesn't create a .dll, but a .obj file. So you should be able to include board.obj. To clarify, the board.obj file contains object code, which is partially compiled code. Visual Studio is able to link against object code since Visual Studio 2005 (Source).
How can I callnotify-sendfrom C code with a message stored in my string ? ``` #include <stdlib.h> int main(int argc, char *argv[]) { system("mount something somewhere"); system("notify-send message"); return 0; } ```
Just send the string as a parameter tosystem(). For example: ``` #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char command[100], msg[100]; strcpy(command,"notify-send "); strcpy(msg,"\"Hello World\""); strcat(command,msg); system(command); return 0; } ```
Lets say I am in /home/myuser there are 90,000 files there inside 3000 directories. How can I write a bash function or with linux commands to get one random file? It could be C as well I suppose
You can list all your files and then pick a random line between them: ``` find /home/myuser | sort -R | head -n1 ``` However this is not very efficient, and could take a while, but is easy to understand. You can work from here.
I've written a C program consisting of file operations (a .txt file). When I open the output file in notepad, I don't read the contents in Latin script (or in simpler words - letters of the English alphabet), but some other script. However when I open the file in C (usingfopenetc.), I get the output in English (Latin ...
Sounds like the classic "Bush hid the facts" problem. In the Notepad file open dialog, you can see a drop-down that allows specifying an encoding. Since the file does not start with an unicode BOM, Notepad has to guess the encoding of the file (it does so as soon as you highlight the file in the list). And sometimes,...
I'd like to know why I am getting this, Error: ``` error: dereferencing pointer to incomplete type strncpy(variables->part1[i], environ[i], placement); ``` main Code: ``` struct vars { char **part1; char **part2; } ; static struct vars *variables; exportenviron(&variables); ``` function Code: ``` void e...
The file containingexportenvironisn't seeing the actual definition of your struct: instead, it only knows thatstruct varsexists, but not what's in it. For example, perhaps you have a header filevars.hincluded by the .c file withexportenvironin it, andvars.hcontains onlystruct vars;
I am reading the current directory and printing it out using ``` printf("%s\n", file->d_name); ``` but it also prints out "." and ".." files. How can I exclude them?
The simple way: just make sure the file name isn't"."or".."before you display it. :P ``` if (strcmp(file->d_name, ".") && strcmp(file->d_name, "..")) { printf("%s\n", file->d_name); } ```
I am doing in a simplistic experiment as below: ``` glPushMatrix(); glGetDoublev(GL_MODELVIEW, modelMatrix); glTranslatef(...); glGetDoublev(GL_MODELVIEW, modelMatrix); glPopMatrix(); ``` However, after the translation, there is not change in the modelview matrix. I am wondering why is that, and how can I see the e...
Your code is invalid. The correct enum forglGet...()isGL_MODELVIEW_MATRIX, notGL_MODELVIEW(which is a constant for useglMatrixMode()), so all you get is some GL error, and the memory atmodelMatrixwill be not touched at all, so it is probably just left uninitialized.
Using C, can the functionfreadbe used to read a null terminated string? I have to read a file that starts with an ip as 4 unsigned chars followed by an integer describing the number of null terminated strings. After that, I need to read the strings until the last one before another ip list starts. I greatly apprecia...
freaddoes not stop reading at any delimiter,'\0'or otherwise. It attempts to read the exact number of bytes requested, and will only stop earlier if it encounters end-of-file or a read error. On POSIX 2008 conforming systems, thegetdelimfunction provides an easy way to "read until'\0'". Otherwise, you're stuck with a...
I'm trying to create a game for my CS assignment and I'm stuck with this for loop that won't end my game even though the lives are already at zero. ``` for(life = 3, ai_life = 3; ai_life != 0, life != 0; --ai_life, --life) ```
Please read up what thecomma operatordoes ``` for(life = 3, ai_life = 3; ai_life != 0 && life != 0; --ai_life, --life) ```
I create empty c++ project(VS-2010) that contain c file & header: I change the sub system of this project to console. then I compile and run it. Now I want to use the dll of this project on C# (I know how to do it, it's not my question)!! where I found the dll? (or I didn't create it????) On the debug folder I ...
It doesn't create a .dll, but a .obj file. So you should be able to include board.obj. To clarify, the board.obj file contains object code, which is partially compiled code. Visual Studio is able to link against object code since Visual Studio 2005 (Source).
I have a C array declared like char*arrayOfVarNames[3]; This array is populated by some api and the strings in this array are again used by an objective-C method. I want to know if there are any null strings in the arrayOfVarNames[3] before passing to the objective-C method.NSString *tempString = [NSString stringWit...
A simpleifstatement: ``` NSString *tempString = nil; if (arrayOfVarNames[i]) { // It's not NULL tempString = [NSString stringWithCString:arrayOfVarNames[i] encoding:NSUTF8StringEncoding]; } else { tempString = @""; // or some other appropriate action } ```
How could I redirect output to multiple targets, say stdout, file, socket and so? say, i have a system here and connected to some network. When it fails, the guy supervises it via ssh should be able to notice it, or the GUI client should receive the error info, or, in the worst case, we can still find something in th...
I think you are looking for the "tee" command.
I have written the following the code, but the problem is it is not showing the desired output. ``` #include<stdio.h> int main() { unsigned x=1; signed char y=-1; if(x>y) printf("x>y\n"); else printf("x<=y\n"); return 0; } ``` the above program should output x>y because 1st condi...
the program is giving wrong output because of type casting from signed char to unsigned int. try to avoid char to int implicit type casting.
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 I downloaded netbeans for C/C++. I followed every instructions and downloaded MinGW, and msys and added tho...
UPDATE: Turns our I did not install base package from MingW. After messing around with it a little bit, I got it working. Thanks everyone!
In C, how can I use sscanf over a buffer that contains new line character. Example buffer: ``` buf = "Name: Sam\nID: 123\nLocation: 123\nDest: abc\0"; ``` I want to do something like: ``` sscanf(buf, "%[^\n]s\n%[^\n]s\n%[^\n]s\n%[^\0]s", line1, line2, line3, line4); ``` butsscanfis only picking line1. Any ideas o...
Thanks to WhozCraig for the answer: "Lose the s in those specs, "%[^\n]\n%[^\n]\n...". sscanf is looking for a string of anything-but-newline, then an 's' (which it doesn't find, then... you hopefully get the point)."
I am new to programming, and the following line confused me: switch_block_conn[from_side][to_side][from_track].nelem = 0 Is this line actually describing an array? What is it doing?
From the syntax in the given code sample, assuming it is valid code, it is implied that: switch_block_connis a 3-d array. You can infer this from the 3 array index operations.The individual elements inswitch_block_connare structs. You can infer this from the.operator used.Those structs have (among potentially other m...
``` int gcd(int x, int y) { int t; while (y) { t = x; x = y; y = t % y; } return x; } ``` Does it stop when y = 0? I thought the loop stops when y isn't defined.
Yes, it stops when y is 0, what you have ``` while (y) ``` is short hand for ``` while (y != 0) ```
Hi I am having trouble getting this function to work. Basically, the the function should return a 1 if all even place bits are 1 and 0 otherwise. This program always prints 0 for some reason. Here is the code : ``` #include <stdio.h> int allEvenBits(int); int main() { printf("%d\n", allEvenBits(0xFFFFFFFE)...
You are checking theodd bitsfor the even should be with0xAAAAAAAA: ``` const unsigned int ODD_BITS_SET = 0x55555555; const unsigned int EVEN_BITS_SET = 0xAAAAAAAA; unsigned int allOddBits(unsigned int X) { return (X & ODD_BITS_SET) == ODD_BITS_SET; } unsigned int allEvenBits(unsigned int X) { return (X & EVEN_BITS_SE...
This question already has answers here:mkdir c++ function(4 answers)Closed9 years ago. I am trying to create a file in C by trying to execute the following code segment, but I am getting an "identifier "mkdir" is not defined". I am working on a Windows Machine using Visual Studio. ``` #include<stdio.h> #include<sys...
Use WinApi'sCreateDirectory()function or use_mkdir()(notice the underscore sign). Example of CreateDirectory() - you need to include windows.h header file: ``` #include<windows.h> int main() { CreateDirectory ("C:\\test", NULL); return 0; } ```
i want to use struct ifreq, but it cannot be access when i make: the code is : ``` 1 #include <sys/types.h> 2 #include <sys/ioctl.h> 3 #include <sys/socket.h> 4 #include <net/if.h> 5 #include <stdio.h> 6 #include <stdlib.h> 7 #include <unistd.h> 8 #include <netdb.h> 9 #include <string.h> 10 #include ...
As statedhere, you should use-std=gnu99instead of-std=c99when compiling.
This question already has answers here:How does dereferencing of a function pointer happen?(5 answers)Closed9 years ago. Just a minimum working example: ``` #include <stdio.h> void foo(char* str) { printf("%s\n", str); } main() { foo("foo"); (* foo)("* foo"); } ``` which outputs ``` foo * foo ``` I th...
In C, functions are not values, you cannot "dereference a pointer to a function" and get something (a value) that makes sense. Therefore, trying to dereference and call such a pointer has no additional effect, it's the same as calling through the pointer in the first place.
Please note that the program is for sorting strings using insertion sort. The error report is : ==13660==Source and destination overlap in strcpy(0x7FF00066E, 0x7FF00066E)==13660== at 0x4A06E47: strcpy (mc_replace_strmem.c:106) the line causing this is: ``` strcpy (arg_array[min_index],arg_array[index_1]); ``` It ...
I hope I am not oversimplifying your problem... You can add a check and avoid the call whenmin_indexandindex_1are the same. ``` if ( min_index != index_1 ) { strcpy (arg_array[min_index],arg_array[index_1]); } ```
I am curretly working on a project where is have to search references and go to them to fix some issues, and I often have to find references inside those references also. What happends is that the old reference is deleted from the search window. I was wondering if there is a way to open the new reference in a new sub ...
There is search history menu in the search window.show previous searchesis the button you are looking for.
i want to use struct ifreq, but it cannot be access when i make: the code is : ``` 1 #include <sys/types.h> 2 #include <sys/ioctl.h> 3 #include <sys/socket.h> 4 #include <net/if.h> 5 #include <stdio.h> 6 #include <stdlib.h> 7 #include <unistd.h> 8 #include <netdb.h> 9 #include <string.h> 10 #include ...
As statedhere, you should use-std=gnu99instead of-std=c99when compiling.
This question already has answers here:How does dereferencing of a function pointer happen?(5 answers)Closed9 years ago. Just a minimum working example: ``` #include <stdio.h> void foo(char* str) { printf("%s\n", str); } main() { foo("foo"); (* foo)("* foo"); } ``` which outputs ``` foo * foo ``` I th...
In C, functions are not values, you cannot "dereference a pointer to a function" and get something (a value) that makes sense. Therefore, trying to dereference and call such a pointer has no additional effect, it's the same as calling through the pointer in the first place.
Please note that the program is for sorting strings using insertion sort. The error report is : ==13660==Source and destination overlap in strcpy(0x7FF00066E, 0x7FF00066E)==13660== at 0x4A06E47: strcpy (mc_replace_strmem.c:106) the line causing this is: ``` strcpy (arg_array[min_index],arg_array[index_1]); ``` It ...
I hope I am not oversimplifying your problem... You can add a check and avoid the call whenmin_indexandindex_1are the same. ``` if ( min_index != index_1 ) { strcpy (arg_array[min_index],arg_array[index_1]); } ```
I am curretly working on a project where is have to search references and go to them to fix some issues, and I often have to find references inside those references also. What happends is that the old reference is deleted from the search window. I was wondering if there is a way to open the new reference in a new sub ...
There is search history menu in the search window.show previous searchesis the button you are looking for.
I have been trying to install X11 in Eclipse for C. I have to design visualization applications in C using X11. I am used to Eclipse for java. I need your help for the detailed steps to get X11 directory and getting Xlib.h, xatom.h,xos.h,xutil.h file access through eclipse. I have been trying very hard but not able t...
X11 is a windowing system widely used on Linux and Unix systems. You have 2 options: Go native and install you favorite Linux distro, either as a VM or on actual hardware, then install eclipse on that.Try using Cygwin. Cygwin allows you to run *nix apps on Windows and X server is one of the apps supported.You can fin...
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 realized that most of the problems that I solve on a day to day basis are done via...
the programming techniques that you use to solve the problems can be divided into types of algorithms (not into the loop or technique they use in there program, like you mentioned). some of the methods are.. ``` 1. Divide and conquer 2. greedy 3. dynamic programming ``` you can refer thislinkto read more..
We recently had a discussion at work about signal handlers in C (Unix enviornment). Someone mentioned that ``` (f)printf() is certainly thread-safe but not signal-handler safe. ``` What does the above statement mean? What aspect of (f)printf() make it not signal-handler safe? Is it because it accesses the stdout an...
There is actually fairly little that is legal to do in a signal handler directly. Instead, one must usually set some flag or trigger to do the real work outside the signal handling context. While handling a signal, the only functions you can call are those which are "async signal safe," which is described in detail ...
``` int foo(int n) { int sum = 0; for(int k=1; k <= n; k = k * 2) { sum += k; } return sum; } ``` I have the following function. Now, according to me the runtime complexity of foo(n) should be big-o(logn). Now, I am asked to find out the run time complexity of foo(n*n*n*n). What should ...
It is O(log n4) → O(4 log n) → O(log n)
We recently had a discussion at work about signal handlers in C (Unix enviornment). Someone mentioned that ``` (f)printf() is certainly thread-safe but not signal-handler safe. ``` What does the above statement mean? What aspect of (f)printf() make it not signal-handler safe? Is it because it accesses the stdout an...
There is actually fairly little that is legal to do in a signal handler directly. Instead, one must usually set some flag or trigger to do the real work outside the signal handling context. While handling a signal, the only functions you can call are those which are "async signal safe," which is described in detail ...
``` int foo(int n) { int sum = 0; for(int k=1; k <= n; k = k * 2) { sum += k; } return sum; } ``` I have the following function. Now, according to me the runtime complexity of foo(n) should be big-o(logn). Now, I am asked to find out the run time complexity of foo(n*n*n*n). What should ...
It is O(log n4) → O(4 log n) → O(log n)
I'm new to JNI. I'm confused with jbyteArray and jbyte pointer. Can anyone tell me what is the difference between jbyteArray and jbyte pointer? Thanks.
AjbyteArrayis a handle to a Java object of typebyte[]. Ajbytepointer, or in other words,jbyte*, is a native C data type, that can take the address of a nativesigned char[]array, for example, but it does not map to any Java data type. An object referenced by ajbyteArrayis a Java object, so like any other Java object, ...
So I am trying to assign a char variable with the value "#" or "%" or "!" and if the variable does not have that value, I am prompting the user with an error. While compiling, I am getting the error "error: comparison between pointer and integer". Now, my code where the error is happening is this segment: ``` if ((...
Chars in C must be surrounded by single quotes: ``` if (((a == '!') || (a == '%') || (a == '#')) && (w > 0 && h > 0)) ```
``` #include <stdio.h> #include <math.h> int main (void){ double a,b,c, x, y, z1, z2; printf("Enter the coefficients of a polynomial(ax^2+bx+c): "); scanf("%lfx^2+%lfx+%lf",&a,&b,&c); z1=(-b+sqrt(b*b-4*a*c))/2*a; z2=(-b-sqrt(b*b-4*a*c))/2*a; printf("%lf and %lf",z1,z2); getch(); return 0; } ``` I want an IF stat...
Set values of a,b,c =1 by default.. Now create a condition that example if a user enter char rather than int or float . it does nothing {use error handling for that,} Or take all a,b,c input as string then typecast to to double, and use error handler if error occur assign it value 1
This question already has answers here:Will strlen be calculated multiple times if used in a loop condition?(18 answers)Closed9 years ago. In a given loop eg: ``` for(int i=0 ; i < strlen(s) ; i++){ //do something } ``` Is the strlen(s) calculated for every iteration of the loop? How do the C and C++ languages ...
Yes,strlen(s)will be evaluated on each iteration. If you won't be changing the string in the loop, it is better (faster) to store the value in and then include it in the for loop. Fastest way to do this is: ``` for(int i=0, length = strlen(s) ; i< length ; i++){ //do something } ```
This question already has answers here:multiple assignment statements in printf in c [duplicate](2 answers)Closed9 years ago. Suppose i have the following code: ``` #include <stdio.h> main() { int a,b,c; b=1; c=2; printf("%d\n",10,b=20,b=30,c=50,c=100); printf("%d\n",b); printf("%d\n",c);...
The order of evaluation of argument expressions and their pushing on the stack are different things. The order of evaluation of argument expressions are unspecified in C. So it might be that at first b = 20 will be evaluated and then b = 30 or vice versa. The order of placing arguments in the stack is the following:...
``` #include<iostream> using namespace std; int main() { signed int ar[3]={-5,4,1}; unsigned ar[0]=5; cout<<ar[0]; return 0; } ``` I have to do in such a way that the resultant array is in descending order so that maximum element would be 5 so 5 will be on top , the ab...
If an element in the array is less than zero, multiply it by -1. Don't turn it into an unsigned number, that's probably not going to do what you think it does. Also, as mentioned, what you are doing in your code snippet isn't even modifying the element in the array, it's trying to declare a new array. So basically you...
``` struct node { int x; struct node *next; }; void allocateMemory(struct node *some_node) { some_node = malloc(sizeof(struct node)); } ``` In another function: ``` struct node add(struct node *root, struct node *thisNode, int value) ``` I try to call this: ``` allocateMemory(thisNode->next); ``` I g...
Here in that code : ``` void allocateMemory(struct node *some_node) { some_node = malloc(sizeof(struct node)); } ``` You can write : ``` void allocateMemory(struct node **some_node) { *some_node = malloc(sizeof(struct node)); } ``` And while calling : ``` allocateMemory(&thisNode->next); ```
sorry if my question sounds confused. Here is my code ``` void display_Item_At_Location(char in[][SIZE_OF_ARRAY]) { int loc; int i; printf("Which line would you like to display?\n"); scanf("%d", &loc); for(i = 0; i < SIZE_OF_ARRAY; i++) { printf("%c", in[loc][i]); } retur...
If your strings are NULL-terminated, you could skip theforloop and just do: ``` fprintf(stdout, "%s\n", in[loc - 1]); ``` for a given valuelocwithin index bounds (assuminglocvalue is 1-indexed).
I need to extract the the bits 2,3, and 4 from an uint8 and interpret it as an in. For example if I have 0x1A and 0x1C as mask: 0x1A 0001 1010 Value 0x1c 0001 1100 mask if I do 0x1A & 0x1C I get 0001 1000 which is 24 in base when instead I need just the three bits that are masked 110 (6 in base 10)
Use thebitwise shift operator>>to shift the value 2 bits to the right. Either mask and then shift: ``` result = (value & 0x1C) >> 2; ``` Or shift and then mask (note the mask must be shifted too): ``` result = (value >> 2) & 7; ``` Makes no difference; both approaches will transform the 8-bit valuea7a6a5a4a3a2a1a...
is there any ways to press keys mouse/keyboard with sdl in C? if yes, how? if no, do you know any ways to do that in C?
Create anSDL_eventstructure and fill in the fields as documented inhttp://wiki.libsdl.org/SDL_KeyboardEventandhttp://wiki.libsdl.org/SDL_Keysymthen useSDL_Pushevent()to put the event into the event queue:http://wiki.libsdl.org/SDL_PushEvent ``` SDL_Event event; event.type = SDL_KEYDOWN; event.timestamp = lastEvent...
Here is a code asked to me in an online test. Consider this code. ``` int i = -1, j = -1; (i=0)&&(j=0); (i++)&&(++j); printf("%d, %d\n", i, j); ``` The above code will print ``` 1, -1 ``` Can somebody explain why the output is coming out to be1, -1and not1, 1.
C implements short-circuit evaluation on a few operators. One of these is&&. This means that if the left hand side of the&&evaluates tofalse, then the right hand side will not be evaluated. Additionally, there is a difference between++iandi++.i++will returniand storei+1. On the other hand,++iwill returni+1and storei+...
I am trying to find a way, if it is possible, to copy the values that are pointed by a host array of pointersptsthat points to some elements of another host arrays(float2type). The values that need to be dereferenced fromptswith the->operator are in random positions in thesarray. Is there a way to copy these values p...
If the values you want to copy are in random locations, and you want to copy only those values to the device, you will need to write a separate loop in host code that aggregates those values first into a single contiguous buffer. You can then copy that buffer using an ordinary approach likecudaMemcpy.
This question already has answers here:strange output in comparison of float with float literal(8 answers)Closed9 years ago. I found many questions.But none helps me ``` float x = 0.1; x == 0.1 ``` The above code returns false. since i try to compare double precision value with single precision x. ``` float ...
``` x == 0.1 ``` 0.1is not of typefloatbut of typedouble.floatanddoubledon't have the same precision.0.1fis of typefloat. Why it works with0.5is because0.5has an exact representation in bothfloatanddouble(in binary IEEE-754) types.
I notice that the JavaScript engine (SpiderMonkey) in Mozilla Firefox, has a reliable random number generator, using the 'Math.random()' function Therefore, I want to take/implement the code behind the 'Math.random()' javascript function (from the SpiderMonkey project) into my C program. Is this possible/legal? Or is...
There are BSD-licensed C implementations of the Mersenne Twister PRNG out there. The Wikipedia article on the Mersenne can direct you further (http://en.m.wikipedia.org/wiki/Mersenne_twister) as well as implementations by the algorithm's authors (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html)....
How is\nencoded into a file written in binary mode by a C program? In text mode, under Linux,\nwill be the ASCII value of the line feed (LF) character, and under Windows,\nwill be the ASCII values of CR and LF characters. Thanks.
In a C program,'\n'is always the single character value 0x0a (it would make no sense to have'\n'magically be a two-character constant!). If you wrote to atext fileunder Windows, this would get translated to CR LF (0x0D 0x0A). But, if you write to abinary file, it will always be written as the byte 0x0A, no matter what...
I want to send a file as an email attachment, but at present there is an email filter that prevents that. Is there a simple method or library to encapsulate a file of any length inside an uncompressed ZIP file? I'd like to avoid adding an actual ZIP library that compresses, if I can. For one thing, the file I'm sendin...
The zip format has a stored method (method 0) that would allow you to simply enclose the file in the appropriate headers. See the PKWareappnote.txtfor a description of the format. You would need to calculate the CRC-32 of the data to include in the headers.
Is it possible to write something like this: ``` printf(@" - - - - "); ``` I can do it in C#, but can't in C. It gives me an error in CodeBlocks. Am I allowed to do such ? Error message:error: stray '@' in program.
No. That syntax doesn't exist in C. If you want a multiple-line string, write it as multiple double-quoted strings with no other tokens in between them. They will be combined. ``` printf( "some string" "more of the string" "even more of the string" ); ``` (You will, of course, need to add a\nat the end ...
What does the following code do in obj-C -- how does it get a number between 0 and 1? ``` float prob = (arc4random() % 100) / 100.0 ```
From theOS X manual: ``` DESCRIPTION The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8 bit S-Boxes. The S-Boxes can be in about (2**1700) states. The arc4random() function returns pseudo-random num-bers numbers bers in the range of 0 to (2**32)-1, and therefor...