question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I'm still new to C and ncurses. I was asked to do an assignment that involved making a multithreaded pong game. The game runs fine and ends with the correct lossing conditions but upon termination my terminal is all messed up. I get no echo, so I have to typestty echoto get that back, even then the terminal behaves st... |
Remove refresh after endwin. Calling refresh after endwin causes the program to go back into the curses mode.
|
This problem is about searching a string in a master array (contains the list of all UIDs). The second array contains all the strings to be searched.
For example:
First array(Master List) contains:UID1 UID2 UID3... UID99
Second array contains:UID3 UID144 UID50
If a match is found in first array then 1 is returned... |
sort the master string array and do binary search.
|
I have anXCodeproject withobjective-Cfiles. If I add a new (empty)C fileand try to build, I get a large number of errors right away while building a precompiled header, in ProcessPCH step. The errors are "fatal error: Could not build module 'Foundation'", and things inFoundation.hnot being found. Remove the C file a... |
Surround#import's with preprocessor directive#ifdef __OBJC__ #endif
|
I'm still new to C and ncurses. I was asked to do an assignment that involved making a multithreaded pong game. The game runs fine and ends with the correct lossing conditions but upon termination my terminal is all messed up. I get no echo, so I have to typestty echoto get that back, even then the terminal behaves st... |
Remove refresh after endwin. Calling refresh after endwin causes the program to go back into the curses mode.
|
This problem is about searching a string in a master array (contains the list of all UIDs). The second array contains all the strings to be searched.
For example:
First array(Master List) contains:UID1 UID2 UID3... UID99
Second array contains:UID3 UID144 UID50
If a match is found in first array then 1 is returned... |
sort the master string array and do binary search.
|
I have anXCodeproject withobjective-Cfiles. If I add a new (empty)C fileand try to build, I get a large number of errors right away while building a precompiled header, in ProcessPCH step. The errors are "fatal error: Could not build module 'Foundation'", and things inFoundation.hnot being found. Remove the C file a... |
Surround#import's with preprocessor directive#ifdef __OBJC__ #endif
|
I'm fairly new to Linux, and decided to clean up some directories. Found files encompassed in two # (#random.c#, #nfirst.c#)...what do those hashtags mean? And when i try to rm those files via terminal, it treats the hashtag as a comment...I've tried that double hyphen bypass (rm -- #first.c#) but it doesn't work. So ... |
Those are temporary files, likely created by theemacstext editor when it autosaves.
To remove them, you can dorm \#first.c\#, for example.
|
I'm attempting to create a C program that will scan for wifi networks. I'm not sure what the best ways to this are.
The one plausible idea I have so far is the following
Use C to run the bash code for wifi scanning, then pipe the results backCons: might require use of sudo
At this point I'm hoping someone is more fa... |
You can try using the AppleCoreWLAN Framework. It is written for Objective-C (which is a superset of C) but I believe you can figure out a way to use it from within a C++ or a C program.
Hope this helps.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions concerning problems with code you've written mustdescribe the specific problem— andinclude valid codeto reproduce it — in the question itself. SeeSSCCE.orgfor guidance.Closed9 years ago.Improve this question
I... |
Did you remember to link against the library? The "undefined reference" error is a linker error which means that the symbol you requested doesn't exist.
|
I am trying to use an interface in C with a functionfoothat has the following type
```
void foo(double x[]);
```
However the arrayxthat I want to pass to this function is too large for stack memory. Is there a way to pass a dynamic array tofoo, or increase the size of stack memory?
|
In a function signature,double x[]is equivalent todouble *x. You're passing a pointer anyway, and a pointer doesn't care whether it points at an object on the heap or an object on the stack. Just allocate your array in whatever way is appropriate (e.g. usingmallocif it's too large for the stack) and pass the resulting... |
I'm making a source file that is supposed to take in 2 directory paths (one in and one out). Then copy the specified file from one directory to the other. I've completed the code, except when I compile it, it prints:
warning: passing argument 3 of ‘fread’ makes integer from pointer without a cast [enabled by default]... |
fread()requires 4 arguments and you just needfgets()
Check both prototypes, if you want to read line by line, You can simply usefgets()
```
while (fgets(line, sizeof line, fp_in) != NULL)
{
//....
}
```
|
Is there a tool that can extract the member variables from a given struct or class from the source code?
What I'm expecting is the following
Let's say target.c is the following:
```
#include <stdio.h>
struct A {
int a;
int b;
};
int main()
{
blah...
}
```
And, if I do something like in bash:
```
$ extr... |
Programs like ctags, doxygen, gccxml all offer approaches to this... you might want to read about them online and decide which suits your needs.
|
C : compare two character arrays
Here's my rot function
```
int my_rot13(int c) {
if ('a' <= tolower(c) && tolower(c) <= 'z')
return tolower(c)+13 <= 'z' ? c+13 : c-13;
return c;
}
int my_rot13cmp(char *a, char *b) {
int i;
for (i=1; i<strlen(a); i++) {
if (my_rot13(a[i]) > my_rot13(... |
You have an embedded 0 character in your strings:
```
my_rot13cmp("\0D\n", "\0W\n");
```
This will causestrlen(a)inside my_rot13cmp to return 0 - since a nul character means the end of the string.
Remove those \0 in your strings, and start the loop ati=0
|
I wanted to create a program for fun to show to one of my friends. Don't be mean, I'm a beginner and have a little problem. The thing is I wanted the program to scan a word and if a word is my friends name "Bob" then it prints "noob", else it prints "pro".
This is what I did, but something seems not to work. It point... |
Try like this :
```
#include <stdio.h>
#include <string.h>
int main()
{
char x[30];
printf("Enter the noob's name: ");
scanf(" %s",x);
if (strcmp(x,"Bob")==0)
printf("noob\n");
else
printf("pro\n");
return 0;
}
```
|
I'm trying to usegets()to get a string from the user, but the program seems to be passing right overgets(). There is no pause for the user to give input. Why isgets()not doing anything?
```
char name[13];
printf("Profile name: ");
gets(name);
printf("\n%s", name);
```
|
Call getchar() before you call gets() or fgets(). Since gets() or fgets() is getting skipped due to an already present '\n' from previous inputs in stdin, calling getchar() would lead to itself getting skipped instead of gets() or fgets() or any other similar function. But remember its more of a hack and not a standar... |
When i am using a c++ IPC library, it return a warning message "you are using multiple multicast interfaces. ; going to use [eth1][192.168.1.11]". Does it indicate it is using domain socket under the hood?
|
Not at all - where did you get that idea? "eth1" is the name of a (physical) network interface, and "192.168.1.11" is an IPv4 address, probably one that's bound to that interface. A UNIX domain socket would have a name that looks like a filesystem path.
|
Is there a tool that can extract the member variables from a given struct or class from the source code?
What I'm expecting is the following
Let's say target.c is the following:
```
#include <stdio.h>
struct A {
int a;
int b;
};
int main()
{
blah...
}
```
And, if I do something like in bash:
```
$ extr... |
Programs like ctags, doxygen, gccxml all offer approaches to this... you might want to read about them online and decide which suits your needs.
|
C : compare two character arrays
Here's my rot function
```
int my_rot13(int c) {
if ('a' <= tolower(c) && tolower(c) <= 'z')
return tolower(c)+13 <= 'z' ? c+13 : c-13;
return c;
}
int my_rot13cmp(char *a, char *b) {
int i;
for (i=1; i<strlen(a); i++) {
if (my_rot13(a[i]) > my_rot13(... |
You have an embedded 0 character in your strings:
```
my_rot13cmp("\0D\n", "\0W\n");
```
This will causestrlen(a)inside my_rot13cmp to return 0 - since a nul character means the end of the string.
Remove those \0 in your strings, and start the loop ati=0
|
I wanted to create a program for fun to show to one of my friends. Don't be mean, I'm a beginner and have a little problem. The thing is I wanted the program to scan a word and if a word is my friends name "Bob" then it prints "noob", else it prints "pro".
This is what I did, but something seems not to work. It point... |
Try like this :
```
#include <stdio.h>
#include <string.h>
int main()
{
char x[30];
printf("Enter the noob's name: ");
scanf(" %s",x);
if (strcmp(x,"Bob")==0)
printf("noob\n");
else
printf("pro\n");
return 0;
}
```
|
I'm trying to usegets()to get a string from the user, but the program seems to be passing right overgets(). There is no pause for the user to give input. Why isgets()not doing anything?
```
char name[13];
printf("Profile name: ");
gets(name);
printf("\n%s", name);
```
|
Call getchar() before you call gets() or fgets(). Since gets() or fgets() is getting skipped due to an already present '\n' from previous inputs in stdin, calling getchar() would lead to itself getting skipped instead of gets() or fgets() or any other similar function. But remember its more of a hack and not a standar... |
I want to add numbers to an array using scanf
What did i do wrong? it says expected an expression on the first bracket { in front of i inside the scanf...
```
void addScores(int a[],int *counter){
int i=0;
printf("please enter your score..");
scanf_s("%i", a[*c] = {i});
}//end add scores
```
|
I suggest:
```
void addScores(int *a, int count){
int i;
for(i = 0; i < count; i++) {
printf("please enter your score..");
scanf("%d", a+i);
}
}
```
Usage:
```
int main() {
int scores[6];
addScores(scores, 6);
}
```
|
I am taking an Operating Systems class and we are modifying the linux kernel.
One of my particular tasks involves creating a struct and allocating space for it. I was looking through the kernel api but couldn't seem to find a way to get the sizeof an element in kernel space.
For example, would I be able to do:
stru... |
It's because you have declared nonewNodeto get size of.
Trysizeof(struct newNode).
|
I need to implement ps -auxj, grep "user id", and wc. I already have word count, but I'm not sure how to do the others while they have parameters. This is what I have so far.
```
int main() {
int pfd[2];
int pid;
if (pipe(pfd) == -1) {
perror("pipe failed");
exit(-1);
}
if ((pid = fork()) < 0) {
perror("... |
execgives details about how to pass arguments to the exec family of functions.
e.g.
```
execl("ls", "ls", "-l",(char *) 0);
```
you can choose from there whatever suits you.
|
I have a do-while loop:
```
float amount;
do
{
printf("Input dollar amount owed:\n");
amount = GetFloat();
}
while (amount <= 0);
```
followed by a while loop and printf:
```
int coins = 0;
while (amount >= 0.25);
{
amount = amount - 0.25;
coins++;
}
printf("Number of coins to use: %d\n", coins);
re... |
```
while (amount >= 0.25);
^ roh roh
```
I think what you meant was:
```
while (amount >= 0.25)
{
amount = amount - 0.25;
coins++;
}
```
while(x);is the same aswhile(x) { }
|
I am looking for a decent one line c statement to keep a character between'0'and'9'on increment
What I have right now is this:
```
char c;
...
c = (((c % 48 ) + 1) % 10) + 48;
```
Is there a better way of dong this?
|
Use'0'instead of hardcoding its ASCII value. Also I likec - '0'better thanc % '0'; it matches up with the+ '0'better.
```
c = (c - '0' + 1) % 10 + '0'
```
|
"%4.3d"
I know that %.3 would make it only a 3 number integer, but how would %4.3d affect the number as a whole?
Edit: Yes I have tried writing a program to do this. I just did not understand the output.
|
The.3is the precision specifier. This will cause the integer value to be padded with leading zeros if it's less than 3 digits.
The leading4is the width. This forces it to print at least 4 characters.
If you fed this 42, it would print042(with a leading space).
|
I have two threads. The main thread and two others created with *pthread_create*, for instance thread_1 and thread_2.
The main thread writes the output in the terminal that i used to run the program. Then, i want to create two new windows, in which thread_1 and thread_2 will write some text.
i tried to use the syste... |
Do you need the program to open the other two windows?
If not:
Have each thread write to a separate file.
Manually open two more windows.
Use the bash command 'tail -f' in each of the new windows to display the output of each file.
|
I want write simple C program to set ACL to one particular file on Linux. My starting code is trying to use function from "acl.h". I'm using Ubuntu 13.10, I've installed "Access control list utilities" - "acl 2.2.52-1". Here is my code:
```
#include <sys/acl.h>
#include <stdio.h>
int main () {
acl_t aclvar;
i... |
The libraries you link to needs to come last
```
gcc myAcl.c -lacl
```
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
I understand that you are implementing a hash function for a hash table.
Basically You can fold the uint64_t with an xor and xor the result with the uint32_t.
```
uint32_t hash( uint32_t a , uint64_t b ) {
return a ^ (b >> 32 ) ^ b;
```
}
|
I am new to C and pointers and I'd like know if its possible to pass an array pointer to a function instead of passing the array of characters itself. I am posting the snippet from the code.
```
char ipAddress[24];
int i, j;
for (i = 12; i <= 13; i++)
{
for (j = 1; j <= 254; j++)
{
sprintf(ipAddress,"... |
Arrays are always passed by pointer in C, not passed by value (copyed)
So
```
int runCommand (char x[24]);
```
is close equivalent of
```
int runCommand (char *x);
```
|
InAdvanced Programing in the UNIX Environment 2nd Edition, chapter 01, section 11, there is a sentence:
For example, the printf function may use the write system call to output a string,
but the strcpy (copy a string) and atoi (convert ASCII to integer) functions don't
involve the kernel at all.
What I don't und... |
It seems to mean that the function doesn't lead to system calls by saying 'not involve kernel", from the context of that sentence.
|
I am picking up C in order to speed up some bits of a large python project. In order to add new functions to a continuously running python script, I have it occasionally check a .py file and integrate it's contents. I was wondering if there was a way of doing the equivalent in C. Is there a way to have it pick up th... |
Yes, you need to usedlopento access the library rather than linking at compile time, thendlsymto access functions within it. To switch to a new library you'll need todlclosethe handle and create a new one - wrapping this in a module to handle all of it is not a terribly difficult task.
|
```
#include<stdio.h>
int main()
{
char arr[] = "somestring";
char *ptr1 = arr;
char *ptr2 = ptr1 + 3;
printf("ptr2 - ptr1 = %ld\n", ptr2 - ptr1);
printf("(int*)ptr2 - (int*) ptr1 = %ld", (int*)ptr2 - (int*)ptr1);
return 0;
}
```
I understand
```
ptr2 - ptr1
```
gives 3 but cannot figure ou... |
It's because when you substract two pointers, you get the distance between the pointer in number of elements, not in bytes.
```
(char*)ptr2-(char*)ptr1 // distance is 3*sizeof(char), ie 3
(int*)ptr2-(int*)ptr1 // distance is 0.75*sizeof(int), rounded to 0
```
EDIT: I was wrong by saying that the cast forces the p... |
I have two applications refering to a dll (A.dll). The dlls are refernced from both application's local directories. Application1 use Settings.Default to store string to the dll (A.dll). Will those strigs that are saved to settings of A.Dll by Applciation1 be accessible to Application2?
|
As far as I'm aware, each application setting should have it's own settings file. Furthermore, if you have used a user-scoped settings, then eachuserfrom each application will have their own settings files.
You can find full details from the following links:
Using Settings in C#
Application Settings Overview
|
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 have a cgi program in c where I am using a system call for getting the present working directory (pwd). ... |
Looks like you are on a Linux/Unix system.
You can get the pwd from the environment, you don't need to usesystem:
```
#include <stdlib.h>
```
char *pwd = getenv("PWD");
For your reference, here is one example on how you can get the output fromsystem(there are other ways):
Getting output of a system command from s... |
I know the__flbffunction can tell me if a stream is line buffered or not in Linux, but how to determine if a stream is full buffered or not?
|
Can't you use a combination of__flbfand__fbufsizeto see if the file is unbuffered, line buffered or block buffered?
Like
```
if (__flbf(some_file))
printf("File is line buffered\n");
else if (__fbufsize(some_file) == 0)
printf("File is unbuffered\n");
else
printf("File is block (aka fully) buffered\n");
... |
I'm a Objective-C dev and sometimes I have to deal with C/C++ code.
I have a function written in C++, it logs an event with name, for example, Level_12_Pack_10. I want to create a dynamic C++ string like that, then I can change level and pack numbers.
In Objective C, it's easy with some lines of code: [NSString string... |
I don't think C++ supports strings with built-in changeable variables like that. It would be too over-the-top to make a class to format the string like that. Probably the closest thing you can get is to use stringstreams:
```
#include <sstream>
string makeMyString(int level, int pack) {
stringstream ss;
ss << "Le... |
```
#include<stdio.h>
int main()
{
char arr[] = "somestring";
char *ptr1 = arr;
char *ptr2 = ptr1 + 3;
printf("ptr2 - ptr1 = %ld\n", ptr2 - ptr1);
printf("(int*)ptr2 - (int*) ptr1 = %ld", (int*)ptr2 - (int*)ptr1);
return 0;
}
```
I understand
```
ptr2 - ptr1
```
gives 3 but cannot figure ou... |
It's because when you substract two pointers, you get the distance between the pointer in number of elements, not in bytes.
```
(char*)ptr2-(char*)ptr1 // distance is 3*sizeof(char), ie 3
(int*)ptr2-(int*)ptr1 // distance is 0.75*sizeof(int), rounded to 0
```
EDIT: I was wrong by saying that the cast forces the p... |
I have two applications refering to a dll (A.dll). The dlls are refernced from both application's local directories. Application1 use Settings.Default to store string to the dll (A.dll). Will those strigs that are saved to settings of A.Dll by Applciation1 be accessible to Application2?
|
As far as I'm aware, each application setting should have it's own settings file. Furthermore, if you have used a user-scoped settings, then eachuserfrom each application will have their own settings files.
You can find full details from the following links:
Using Settings in C#
Application Settings Overview
|
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 have a cgi program in c where I am using a system call for getting the present working directory (pwd). ... |
Looks like you are on a Linux/Unix system.
You can get the pwd from the environment, you don't need to usesystem:
```
#include <stdlib.h>
```
char *pwd = getenv("PWD");
For your reference, here is one example on how you can get the output fromsystem(there are other ways):
Getting output of a system command from s... |
I know the__flbffunction can tell me if a stream is line buffered or not in Linux, but how to determine if a stream is full buffered or not?
|
Can't you use a combination of__flbfand__fbufsizeto see if the file is unbuffered, line buffered or block buffered?
Like
```
if (__flbf(some_file))
printf("File is line buffered\n");
else if (__fbufsize(some_file) == 0)
printf("File is unbuffered\n");
else
printf("File is block (aka fully) buffered\n");
... |
I'm a Objective-C dev and sometimes I have to deal with C/C++ code.
I have a function written in C++, it logs an event with name, for example, Level_12_Pack_10. I want to create a dynamic C++ string like that, then I can change level and pack numbers.
In Objective C, it's easy with some lines of code: [NSString string... |
I don't think C++ supports strings with built-in changeable variables like that. It would be too over-the-top to make a class to format the string like that. Probably the closest thing you can get is to use stringstreams:
```
#include <sstream>
string makeMyString(int level, int pack) {
stringstream ss;
ss << "Le... |
I want to Swap 4 variables without using a temp variable. Is that possible?
I want to do likea = b & b = c & c = d & d = a, without using an temp a new 5th variable.
**UPDATE: - ok.. got it! it can't be done without an another new variable!
how can i do it with an single temp variable ?**
|
You could use theXOR swapon successive pairs, to swapnvariables without a temp variable.
```
a b c d // Variables
-------
A B C D // Initial values
B A C D // swap(a,b)
B C A D // swap(b,c)
B C D A // swap(c,d)
```
That said, using a temporary variable is easier to understand, and is not necessarily less ... |
I am trying to achieve theTIMEOUTfunctionality in my UDP Stop-and-wait. That is, I make my receiver not sendACKon purpose and expect the sender re-transmit after theTIMEOUT.
However, as the therecvfromdocumentation says:
If no messages are available at the socket, the receive calls wait for a message to arrive, unle... |
Take a look at the functionsselectpollandepoll. They can help with the timeout. They are also very useful when waiting on mulitple file descriptors (sockets)
|
This question already has answers here:How to split a string to 2 strings in C(8 answers)Closed9 years ago.
What is the most effective way to split a string and select the last element?
i.e. we have a string "www.google.com"
i would like to split this string where a "." occurs and select the last element which woul... |
You can usestrrchr:
```
const char * tld = strrchr("www.google.com", '.');
// tld now points to ".com"
```
don't forget to check forNULLin case a dot cannot be found. Also note that it doesn't return a new string, just a pointer to the last occuring'.'in the original string.
|
I have a struct defined as :
```
typedef struct pt {
int x;
int y;
}point;
```
I also have a stack push function declared as :
```
void push(point p);
```
Now whenever i wish to call this function, I can do the following :
```
point p = {x_value, y_value};
push(p);
```
I wanted to know if there is a les... |
Define a "constructor" function:
```
point make_point(int x, int y)
{
point result = {x, y};
return result;
}
```
Then
```
push(make_point(x, y));
```
|
The exact code snippet that appeared in my exam was :
```
int main()
{
int n=234;
printf("%d,",printf("%d",n));
}
```
According to what I got when I compiled the code the answer came out to be :"2343,"For the explanation I asked my friend and he said that the outermostprintf()gives the number of digits in the n... |
That code is the same as :
```
int n=234;
int k = printf("%d",n);
printf("%d,",k);
```
If you now know whatprintfreturns, you can easily deduce what will be printed out by this program.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
In declarationint *a[10],ais array of pointer to int of 10 size, so size =sizeof (int*) * 10.
You can apply sizeof operator to print its size:
```
printf("sizeof = %zu", sizeof(a));
```
If suppose in some system sizeof pointer to int is 2 (as you says in question) then size will be 20 bytes.
|
Consider the following integer:
uint32_t p = 0xdeadbeef;
I want to get:
0..3 bits so I did:p & ((1 << 4) - 1);and that went good.
however, for 4..7 what I tried did not go as expected:
(p >> 16) & 0xFFFF0000
Why would it not extract the bits I want? Am I not movingp16 positions to the right and then taking out 4... |
If you want to get bits from 4..7
```
(p>>4) & 0xf
```
If you want to get bits fromNto(N+4-1)
```
(p>>N) & 0xf
```
AndNshould be <32 (if your system is 32 bits system). otherwise you will get undefined behaviour
|
This question already has answers here:What is the significance of the <: syntax in C? [duplicate](4 answers)When were the 'and' and 'or' alternative tokens introduced in C++?(8 answers)Closed9 years ago.
So I came across this piece of code:
```
%:include <stdio.h>
int main(int argc, char *argv<::>) <%
printf("... |
This code uses C digraphs, as explained here:http://en.wikipedia.org/wiki/Digraphs_and_trigraphs#C
The C standard (ISO/IEC 9899:201x, Punctuators §6.4.6:3) has this to say on the matter:
In all aspects of the language, the six tokens<: :> <% %> %: %:%:behave, respectively, the same as the six tokens[ ] { } # ##excep... |
Is it possible to create adynamic functionby allocating dynamic memory, writing some assembler opcodes to it (like0x90 0xC2forNOP RET), creating a function pointer which points to that dynamic memory and execute it like a regular function from within a C program?
Target should be a regular x86 Linux system.
|
In general yes, but you need to go into system-specific things to do so. That's not very surprising I guess, since the fact that you're going to use binary assembly instructions is making it pretty clear.
You need to be aware that you can't assume that heap memory on modern operating systems is executable, so you mig... |
I want to know, ifWriteProcessMemoryorReadProcessMemoryfunctions access program code, or data. Thanks.
|
It can access both.
Program text and data live in the same address space, and are somewhat intermingled for things like read-only data.
|
The code takes user input(html tag)
```
ex:
<p> The content is text only inside tag </p>
gets(str);
```
Task is to replace all occurences with anewline("\n")
```
while((ptrch=strstr(str, " ")!=NULL)
{
memcpy(ptrch, "\n", 1);
}
printf("%s", str);
```
The code above replaces only first ch... |
You're almost there. Now just usememmoveto move the memory left to the new line.
```
char str[255];
char* ptrchr;
char* end;
gets(str); // DANGEROUS! consider using fgets instead
end = (str + strlen(str));
while( (ptrch=strstr(str, " ")) != NULL)
{
memcpy(ptrch, "\n", 1);
memmove(ptrch + 1, ptrch + siz... |
I know that C program generally ends with return, where we return the status of the program. However, I want to return a string.
I will be calling the C-executable from a Python script and printing the returned string.
Sincemaincan't return a string, How do I do this?
|
the return value must be an integer (in general)
What you can do is have the C program print out results (using printf, for example) and have the python script read the standard output of the process (popen functions that give access to child_stdout)
|
Is there a C or C++ library available for parsing, editing, and writing/etc/network/interfaceson Linux (in the form described athttp://manpages.ubuntu.com/manpages/hardy/man5/interfaces.5.html)?
|
http://augeas.net/
Augeas is a configuration editing tool. It parses configuration files in their native formats and transforms them into a tree. Configuration changes are made by manipulating this tree and saving it back into native config files.
|
This question already has answers here:How to split a string to 2 strings in C(8 answers)Closed9 years ago.
What is the most effective way to split a string and select the last element?
i.e. we have a string "www.google.com"
i would like to split this string where a "." occurs and select the last element which woul... |
You can usestrrchr:
```
const char * tld = strrchr("www.google.com", '.');
// tld now points to ".com"
```
don't forget to check forNULLin case a dot cannot be found. Also note that it doesn't return a new string, just a pointer to the last occuring'.'in the original string.
|
I have a struct defined as :
```
typedef struct pt {
int x;
int y;
}point;
```
I also have a stack push function declared as :
```
void push(point p);
```
Now whenever i wish to call this function, I can do the following :
```
point p = {x_value, y_value};
push(p);
```
I wanted to know if there is a les... |
Define a "constructor" function:
```
point make_point(int x, int y)
{
point result = {x, y};
return result;
}
```
Then
```
push(make_point(x, y));
```
|
The exact code snippet that appeared in my exam was :
```
int main()
{
int n=234;
printf("%d,",printf("%d",n));
}
```
According to what I got when I compiled the code the answer came out to be :"2343,"For the explanation I asked my friend and he said that the outermostprintf()gives the number of digits in the n... |
That code is the same as :
```
int n=234;
int k = printf("%d",n);
printf("%d,",k);
```
If you now know whatprintfreturns, you can easily deduce what will be printed out by this program.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
In declarationint *a[10],ais array of pointer to int of 10 size, so size =sizeof (int*) * 10.
You can apply sizeof operator to print its size:
```
printf("sizeof = %zu", sizeof(a));
```
If suppose in some system sizeof pointer to int is 2 (as you says in question) then size will be 20 bytes.
|
Consider the following integer:
uint32_t p = 0xdeadbeef;
I want to get:
0..3 bits so I did:p & ((1 << 4) - 1);and that went good.
however, for 4..7 what I tried did not go as expected:
(p >> 16) & 0xFFFF0000
Why would it not extract the bits I want? Am I not movingp16 positions to the right and then taking out 4... |
If you want to get bits from 4..7
```
(p>>4) & 0xf
```
If you want to get bits fromNto(N+4-1)
```
(p>>N) & 0xf
```
AndNshould be <32 (if your system is 32 bits system). otherwise you will get undefined behaviour
|
This question already has answers here:What is the significance of the <: syntax in C? [duplicate](4 answers)When were the 'and' and 'or' alternative tokens introduced in C++?(8 answers)Closed9 years ago.
So I came across this piece of code:
```
%:include <stdio.h>
int main(int argc, char *argv<::>) <%
printf("... |
This code uses C digraphs, as explained here:http://en.wikipedia.org/wiki/Digraphs_and_trigraphs#C
The C standard (ISO/IEC 9899:201x, Punctuators §6.4.6:3) has this to say on the matter:
In all aspects of the language, the six tokens<: :> <% %> %: %:%:behave, respectively, the same as the six tokens[ ] { } # ##excep... |
Is it possible to create adynamic functionby allocating dynamic memory, writing some assembler opcodes to it (like0x90 0xC2forNOP RET), creating a function pointer which points to that dynamic memory and execute it like a regular function from within a C program?
Target should be a regular x86 Linux system.
|
In general yes, but you need to go into system-specific things to do so. That's not very surprising I guess, since the fact that you're going to use binary assembly instructions is making it pretty clear.
You need to be aware that you can't assume that heap memory on modern operating systems is executable, so you mig... |
Do I need to callCloseHandle()on handles returned byEnumWindows()?
|
You only ever use CloseHandle() on handles returned by functions in kernel32. They are reference counted, closing the last handle destroys the object. File, mutexes, events, that sort of object.
Window handles are different, their lifetime is determined by the user. Or an explicit DestroyWindow() call in a program... |
```
static Player players[32];
Player* Player_constructor() {
Player* player = malloc(sizeof(Player));
// Do some initializations
return player;
}
...
...
...
players[0] = Player_constructor();
```
The issue is thatplayers[0]is typePlayerandPlayer_constructoris typePlayer*.
How can I overcome this issue... |
You do not need dynamic allocation here: your array ofPlayerstructures can be used directly, withoutmalloc. One simple way to deal with initialization is rewriting yourPlayer_constructoras follows:
```
void Player_constructor(Player* player) {
// Do some initializations
}
...
Player_constructor(&players[0]);
```
|
I wanted to backup mysql db using a c program,here is what I came up with:
```
#include <stdio.h>
#include <stdlib.h>
main(){
system("D:\mysql\bin\mysqldump.exe dbname -u root -p > C:\db_backup.sql");
}
```
It says "D:mysql is not recognized as an internal or external command."
But when I tried... |
In a C string, the backslash is a meta character that indicates something different about whatever character follows. The most obvious example is\n, which is replaced with a carriage return.
When you truly wish to have a backslash in your string, you must specify\\.
|
I'm reading Linux Device Drivers, and noticed you can print the current line and file using, for instance, printk. How is this implemented? How does Linux keep track of the line containing the printk statement? I haven't seen similar capabilities in "normal C code" written in userspace.
Here's an example from LDD3:
... |
__FILE__and__LINE__are C preprocessor macros, this is not kernel specific.
|
I'm trying to use masks and manipulating specific bits in a byte.
For example:
I want to write a program in C that flips two bits at particular positions e.g. the bit at position 0 and the one at the third position.
So,11100011, would become01110011.
How can I swap these bits?
|
Flipping a bit is done by XOR-ing with a mask: set bits at the positions that you want to flip, and then execute a XOR, like this:
```
int mask = 0x90; // 10010000
int num = 0xE3; // 11100011
num ^= mask; // 01110011
```
Here are a few notes:
bits are commonly counted from the least significant position, so yo... |
At the moment I simply use the WM_MOUSEMOVE message, but it limits the mouse movement to the maximum resolution. So what's the best way of capturing the mouse with Win32 (on a OpenGl window)? I don't want to use freeglut or any extra library.
|
For games and realtimeDirectInputis very suitable, it's moderately hard to use.
That is not core win32 api, the winapi way of getting the input is eitherGetCursorPos/SetCursorPosdriven by your own update loop, so you query and reset with your own frequency.
OrSetCaptureand then uponWM_MOUSEMOVEyou callSetCursorPos.
... |
Do I need to callCloseHandle()on handles returned byEnumWindows()?
|
You only ever use CloseHandle() on handles returned by functions in kernel32. They are reference counted, closing the last handle destroys the object. File, mutexes, events, that sort of object.
Window handles are different, their lifetime is determined by the user. Or an explicit DestroyWindow() call in a program... |
```
static Player players[32];
Player* Player_constructor() {
Player* player = malloc(sizeof(Player));
// Do some initializations
return player;
}
...
...
...
players[0] = Player_constructor();
```
The issue is thatplayers[0]is typePlayerandPlayer_constructoris typePlayer*.
How can I overcome this issue... |
You do not need dynamic allocation here: your array ofPlayerstructures can be used directly, withoutmalloc. One simple way to deal with initialization is rewriting yourPlayer_constructoras follows:
```
void Player_constructor(Player* player) {
// Do some initializations
}
...
Player_constructor(&players[0]);
```
|
I wanted to backup mysql db using a c program,here is what I came up with:
```
#include <stdio.h>
#include <stdlib.h>
main(){
system("D:\mysql\bin\mysqldump.exe dbname -u root -p > C:\db_backup.sql");
}
```
It says "D:mysql is not recognized as an internal or external command."
But when I tried... |
In a C string, the backslash is a meta character that indicates something different about whatever character follows. The most obvious example is\n, which is replaced with a carriage return.
When you truly wish to have a backslash in your string, you must specify\\.
|
I'm reading Linux Device Drivers, and noticed you can print the current line and file using, for instance, printk. How is this implemented? How does Linux keep track of the line containing the printk statement? I haven't seen similar capabilities in "normal C code" written in userspace.
Here's an example from LDD3:
... |
__FILE__and__LINE__are C preprocessor macros, this is not kernel specific.
|
I'm trying to use masks and manipulating specific bits in a byte.
For example:
I want to write a program in C that flips two bits at particular positions e.g. the bit at position 0 and the one at the third position.
So,11100011, would become01110011.
How can I swap these bits?
|
Flipping a bit is done by XOR-ing with a mask: set bits at the positions that you want to flip, and then execute a XOR, like this:
```
int mask = 0x90; // 10010000
int num = 0xE3; // 11100011
num ^= mask; // 01110011
```
Here are a few notes:
bits are commonly counted from the least significant position, so yo... |
At the moment I simply use the WM_MOUSEMOVE message, but it limits the mouse movement to the maximum resolution. So what's the best way of capturing the mouse with Win32 (on a OpenGl window)? I don't want to use freeglut or any extra library.
|
For games and realtimeDirectInputis very suitable, it's moderately hard to use.
That is not core win32 api, the winapi way of getting the input is eitherGetCursorPos/SetCursorPosdriven by your own update loop, so you query and reset with your own frequency.
OrSetCaptureand then uponWM_MOUSEMOVEyou callSetCursorPos.
... |
This question already has answers here:Array of zero length(5 answers)Closed9 years ago.
Make a structure and give it three members like this,
```
struct student{
int rollno;
char name[10];
int arr[];
}stud1, stud2;
```
now give 4 records of marks t... |
The sample itself is wrong because automatic objects (stud1 and stud2) can not be declared. But you can write
```
struct student *s = malloc(sizeof *s + number_of_arr_elems * sizeof s->arr[0]);
```
|
Why my C program doesn't work when I declare the main function like this (I inverted the arguments position) :
```
int main(char * argv, int argc){
}
```
I compiled it without problem but I got errors when I run it.
Thanks.
|
Due to the incorrectmain()signature, this is not a valid C program.
Try enabling compiler warnings. My compiler tells me about the problem:
```
$ gcc -Wall test.c
test.c:1:5: warning: first argument of 'main' should be 'int' [-Wmain]
test.c:1:5: warning: second argument of 'main' should be 'char **' [-Wmain]
```
S... |
wy can't I do tab[i] = "return of my function" ?
```
void creat_tab(int x, int y)
{
int tab[x][y];
int i;
int tmp;
tmp = y * 2;
i = 0;
while (i <= x)
{
if (i == 0 || i == x)
tab[i] = place_full_border(tab[i], x, y); /* here */
else if (i == 1)
tab[i] = place_first... |
tab[i] (with only one subscript) is still an array, not a single element, so you cannot assign to it (it's not an lvalue). You can only assign to the array by iterating through the elements.
|
In the code below:
```
#include <stdio.h>
int main()
{
int a = 1;
int b = 1;
int c = a || --b;
int d = a-- && --b;
printf("a = %d, b = %d, c = %d, d = %d", a, b, c, d);
return 0;
}
```
i was expecting the output to be:
a=0,b=1,c=1,d=0
because due to short circuiting in the line below... |
In first case
```
int c = a || --b;
```
After thisa=1,b=1andc=1
avalue is1, because of short circuit evaluation--bdid not performed
```
int d = a-- && --b;
```
a--ispost decrementso decrement ofawon't effect in expression
where as--bispre decrementso effects here
Your condition becomes
```
int d= 1 && 0 ;
```
... |
This question already has answers here:Why ++i++ gives "L-value required error" in C? [duplicate](5 answers)Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed9 years ago.
In the following code segment, I was expecting the answer to be 5 but it shows compile time error:
```
#i... |
(++i) returns an rvalue. This cannot be incremented.
|
I have declared char arraychar BCommand[100]="00LI002LE99",i just want to use002and99.
Here is the code i have tried:
```
char Lcommand[3],Lecommand[3];
unsigned char SlaveNodeID=0,NodeValue=0,ChSum2=0;
Lcommand[0]=BCommand[4];
Lcommand[1]=BCommand[5];
Lcommand[2]=BCommand[6];
Lecommand[0]=BCommand[9];
Lecomma... |
I think You needintvalues, You can use this if you want integer value of002and99.
```
int SlaveNodeID = (BCommand[4] - '0') * 100 + (BCommand[5]-'0') * 10 + (BCommand[6] - '0');
int NodeValue = (BCommand[5] - '0') * 10 + (BCommand[6]-'0');
printf("%3d",SlaveNodeID);
printf("%2d",NodeValue);
```
if you want the... |
What I am saying is that lets say the user inputs a floating point number for ex 4.624.
Then you you have to read this value using scanf and then you might use it to do some sort of calculation by plugging it in a formula or something similar. How can you read that number to two digits after the decimal point which in... |
```
float x = 4.624;
float x_truncated_to_two_decimal_places = floor(x*100.0) / 100.0;
```
or
```
float x_rounded_to_two_decimal_places = round(x*100.0) / 100.0;
```
depending on what you want.
|
i Want to catch keyboard key on a real time game, for example im printing each 0,3s with usleep(300000) something like that
```
// #####
// ##a##
// #####
```
and I want to move my 'a' arround with the directional keyboard key (left, right...) the problem is each time I call read the program is paused till I enter a... |
You have two choices:
multi-threadingasynchronous I/O
|
This has no runtime error
```
int main()
{
char *p = "Hello";
}
```
This gives runtime error
```
int main()
{
int *p;
*p = 5;
}
```
I cant understand the reason why this is happening. Would appreciate any kind of help.
|
Your first example points pointerpto a literal string, sopis pointing to valid memory.
Your section declares the pointerpbut does not point to to any memory address. Then the next statement*p = 5dereferencesp, which tries to store5at the memory address stored in pointerp. Since you have not pointedpto valid memory,... |
This question already has answers here:some error in output in using macro in C(3 answers)Closed9 years ago.
Why doesn't this math work with macros in C?
```
#include <stdio.h>
#define FOO 6
#define BAR 32
#define MULT FOO * BAR
main() {
int x = 28296;
int y = x / MULT;
printf("%d / %d = %d\n", x, MULT... |
#definetells the preprocessor to replace the code before compilation, so your line actually says:
```
int y = x / 6 * 32;
```
since * and / operators have the same precedence, and are evaluated from left to right, you get (x/6) * 32. The compiler would probably do this calculation for you since x is known to it.
In... |
My main question is why is it that the fflush(stdin); function not working?
Whenever I run the the code, I am not able to get the second input with space ex. Hello World but instead I get Hello?? thanks
```
#include <stdio.h>
main(){
int x;
double y;
char string[100];
/*
* strin... |
Becausefflush(stdin)is undefined behavior.fflush()is only defined by the C standard for output streams, and update streams where the last operation was an output.
|
Silly doubt, how can i print numbers in sequence in C programming according to its variable value.
my Code
```
#include <stdio.h>
void main()
{
int i,j,result;
for (i=1;i<=4;i++)
{
for (j=i;j<=i;j++)
{
printf("%d\n%d",i,j+1);
}
}
}
```
getting output as
```
1
22
33
44
```
Expectin... |
```
void main()
{
int i,j,result;
for (i=1;i<=4;i++)
{
for (j=1;j<=i;j++)
{
printf("%d",i);
}
printf("\n");
}
}
```
|
This question already has answers here:Array of zero length(5 answers)Closed9 years ago.
Make a structure and give it three members like this,
```
struct student{
int rollno;
char name[10];
int arr[];
}stud1, stud2;
```
now give 4 records of marks t... |
The sample itself is wrong because automatic objects (stud1 and stud2) can not be declared. But you can write
```
struct student *s = malloc(sizeof *s + number_of_arr_elems * sizeof s->arr[0]);
```
|
Why my C program doesn't work when I declare the main function like this (I inverted the arguments position) :
```
int main(char * argv, int argc){
}
```
I compiled it without problem but I got errors when I run it.
Thanks.
|
Due to the incorrectmain()signature, this is not a valid C program.
Try enabling compiler warnings. My compiler tells me about the problem:
```
$ gcc -Wall test.c
test.c:1:5: warning: first argument of 'main' should be 'int' [-Wmain]
test.c:1:5: warning: second argument of 'main' should be 'char **' [-Wmain]
```
S... |
wy can't I do tab[i] = "return of my function" ?
```
void creat_tab(int x, int y)
{
int tab[x][y];
int i;
int tmp;
tmp = y * 2;
i = 0;
while (i <= x)
{
if (i == 0 || i == x)
tab[i] = place_full_border(tab[i], x, y); /* here */
else if (i == 1)
tab[i] = place_first... |
tab[i] (with only one subscript) is still an array, not a single element, so you cannot assign to it (it's not an lvalue). You can only assign to the array by iterating through the elements.
|
In the code below:
```
#include <stdio.h>
int main()
{
int a = 1;
int b = 1;
int c = a || --b;
int d = a-- && --b;
printf("a = %d, b = %d, c = %d, d = %d", a, b, c, d);
return 0;
}
```
i was expecting the output to be:
a=0,b=1,c=1,d=0
because due to short circuiting in the line below... |
In first case
```
int c = a || --b;
```
After thisa=1,b=1andc=1
avalue is1, because of short circuit evaluation--bdid not performed
```
int d = a-- && --b;
```
a--ispost decrementso decrement ofawon't effect in expression
where as--bispre decrementso effects here
Your condition becomes
```
int d= 1 && 0 ;
```
... |
This question already has answers here:Why ++i++ gives "L-value required error" in C? [duplicate](5 answers)Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed9 years ago.
In the following code segment, I was expecting the answer to be 5 but it shows compile time error:
```
#i... |
(++i) returns an rvalue. This cannot be incremented.
|
I have declared char arraychar BCommand[100]="00LI002LE99",i just want to use002and99.
Here is the code i have tried:
```
char Lcommand[3],Lecommand[3];
unsigned char SlaveNodeID=0,NodeValue=0,ChSum2=0;
Lcommand[0]=BCommand[4];
Lcommand[1]=BCommand[5];
Lcommand[2]=BCommand[6];
Lecommand[0]=BCommand[9];
Lecomma... |
I think You needintvalues, You can use this if you want integer value of002and99.
```
int SlaveNodeID = (BCommand[4] - '0') * 100 + (BCommand[5]-'0') * 10 + (BCommand[6] - '0');
int NodeValue = (BCommand[5] - '0') * 10 + (BCommand[6]-'0');
printf("%3d",SlaveNodeID);
printf("%2d",NodeValue);
```
if you want the... |
This question already has answers here:Can I use break to exit multiple nested 'for' loops?(24 answers)Closed9 years ago.
How would I accomplish the following?
```
for (x=0;x<3;x++) {
for (y=0;y<3;y++) {
if (z == 1) {
// jump out of the two for loops
}
}
}
// go on to do other t... |
Assuming you don't need the values ofyandx, just assign them the values that will case both loops to exit:
```
for (x=0;x<3;x++)
{
for (y=0;y<3;y++)
{
if (z == 1)
{
y = 3 ;
x = 3 ;
}
}
}
```
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
Change this code:
```
function1(int *hello) {
function2(&hello);
}
```
to:
```
function1(int *hello) {
function2(hello); // <-- no "&" in this call!
}
```
Then you can do this:
```
function2(int *hello) {
*hello = 123; // <-- dereference pointer hello
}
```
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
Change this code:
```
function1(int *hello) {
function2(&hello);
}
```
to:
```
function1(int *hello) {
function2(hello); // <-- no "&" in this call!
}
```
Then you can do this:
```
function2(int *hello) {
*hello = 123; // <-- dereference pointer hello
}
```
|
I have a 128 bit variable filled with 4 separate integers. [1,2,3,4]. I want to shift right, so I can get [2,3,4,0]. What's the fastest way to do this.
My current code:
```
__m128 v1;
v1 = (__m128)_mm_srli_si128( _mm_castps_si128(v1) , 4 );
```
this succeeds in shifting the bits, but I am trying to go for speed an... |
Don't worry about it.__m128and__m128iare two different ways of interpreting the contents of an XMM register, so the cast disappears in compilation. My compiler (clang on Mac OS 10.9) compiles the whole thing down to a single instruction as it stands:
```
psrldq $0x4, %xmm0
```
|
This question already has answers here:Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?(19 answers)Closed9 years ago.
Why does modifying a pre-initialized string literal cause a segmentation fault? For example:
```
char *str = "Hello world";
str[0] ... |
it is in a read only section of the process's address space because the string literal is a constant. (thestrvariable is not in read only space but it should be made to point to a valid writable location before you can use it the way you do.)
|
This question already has answers here:What is the behavior of integer division?(6 answers)Closed9 years ago.
Is it guaranteed in C that1/2 == 0? I need that for an implementation of binary search:
```
/*
* len is the array length
* ary is an array of ptrs
* f is a compare function
* found is a ptr to the found ... |
Yes, this is guaranteed. According to the C ISO spec, §6.5.5/5:
The result of the / operator is the quotient from the division of the first operand by the
second;
The quotient of 1 / 2 is 0, so1 / 2 == 0is guaranteed to be true in C.
Hope this helps!
|
I am trying to extract the minor device number from the tty_nr attribute in /proc/pid/stat. According to the documentation it is said that, minor device number is a combination 0-7 and 20-30 bits in tty_nr. How can I extract these bits from the tty_nr number?
|
There are macros already defined for this purpose. Use theMAJOR()andMINOR()macros that are defined inlinux/kdev_t.h.
|
As the title suggests how do i print 17 in the hexadecimal format(0x11).
I have triedprintf("%04x",number);but it prints the number as 0011(correct but not what i want).
|
Try this its clean and simple.
Hexadecimal ->printf("%#x",17);
Octal ->printf("%#o",17);
More about#. Here's the linkhttp://www.cplusplus.com/reference/cstdio/printf/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.