question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I am misunderstanding something about C pointers:
```
void putString(char* StringPtr, int length){
for(int i=0; i< length; i++)
{
USART_send(*StringPtr);
StringPtr++;
}
}
void parseMsg(char* in_string, int str_len) {
int i = 0;
putString(in_string, str_len);
for(i ... |
That's becausetest[i]is of typecharnot of typechar *.
You can either assign to char:
```
char temp = test[i];
```
or take its address:
```
char *temp = &test[i];
```
|
Is there a better function or way to measure time thanclock()function on Windows? I have a short operation and when I tryclock()orgettickcount()it says it took 0.0 seconds. I need a way to measure it by miliseconds or nanoseconds.
|
You can useQueryPerformanceCounterandQueryPerformanceFrequency:
```
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main(void)
{
LARGE_INTEGER frequency;
LARGE_INTEGER start;
LARGE_INTEGER end;
double interval;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&s... |
Here's my code.
```
#include<stdio.h>
void main(){
FILE *fp;
int a,b;
fp=fopen("hello.txt","r");
while(!feof(fp)){
fscanf(fp,"%d %d",&a,&b);
printf("%d %d\n",a,b);
}
}
```
My hello.txt is
```
1 2
3 4
```
My Output is
```
1 2
3 4
4 4
```
Why is my last line being printed ... |
You must never perform an input operation without immediately checking its result!
The following should work:
```
while (fscanf(fp,"%d %d",&a,&b) == 2)
{
printf("%d %d\n",a,b);
}
```
This will stop at the first conversion failure or end of the file. Alternatively, you could distinguish between conversion failur... |
```
#include<stdio.h>
using namespace std;
void fun(int** a){}
int main()
{
int n;
scanf("%d",&n);
int a[n][n];
fun(a);
return 0;
}
```
Getting this error in C++, but it is working fine in C
but working for typecasted to (void*)a
and then converting to array=(int**)a:
```
test_.cpp:9:8: error: ca... |
Double arrays do NOT convert to double pointers.
Pass a double array to your function like so:
```
void fun(int arr[][5]);
```
Now it will work.
|
Why does the following code use 1.2GB of memory to execute? I was expecting memory usage to be relatively flat regardless of the number passed to generate_series, instead it is steadily increasing. Please - tell me I'm doing something wrong!
```
if (!PQsendQuery(conn, "select generate_series(1, 10000000)"))
exit(... |
It appears that by default libpq buffers the entire result, rather than reading it in chunks.
In 9.2 there is a way to change this behaviour, seeSingle row mode.
I've tried this out, adding a call to PQsetSingleRowMode(conn), directly after PQsendQuery(), drops memory usage down to a few MB. Problem solved!
|
I want to implement logging functionality in C and log messages to both stdout and some file.
I would like to write something like fprintf(logout, "msg"); with somehow declared FILE* logout which will redirect strings to both stdout and some file. Is it possible?
|
If this is on Linux, you can open a pipe to theteecommand:
```
FILE *logout = popen("tee logfile", "w");
```
|
In Linux, Whilestdoutto command line, I want to update specific area, such as theapt-getoutput:
```
54% [Waiting for headers] [Waiting for headers] 211 kB/s 3s
```
thepercentage,kB/sandsecondwill update each second.
If we useprintfthen we will get multiple lines output them. I have tried followingprintf:
``... |
Use the carriage return. It will move the cursor back to the start of the line, from which you can overwrite what was in the line before. For example:
```
printf("Hello, world!\rX");
```
Will be visible as:
```
Xello, world!
```
Make sure you flushstdoutoften if you want it to be visible:
```
fflush(stdout);
```
|
I'm trying to use th function similar_text in PHP in my application written in C, I tried googling and downloaded the source but can't I find it. Any one knows where to find the C implementation of the function in php source code? I'm thinking of using using it instead of building my own one.
|
You should start to have a look at:
```
ext/standard/string.c line: 2999
```
This is for php 5.4.10.
You can find this out for yourself using:
```
grep -r 'similar_text' PHP_SOURCE_FOLDER
```
|
```
#include <stdio.h>
#include <math.h>
#include <limits.h>
int main(void)
{
unsigned long x = 0;
x = x ^ ~x;
printf("%d\n", x);
x = (unsigned long)pow(2, sizeof(x)*8);
printf("%d\n", x);
x = ULONG_MAX;
printf("%d\n", x);
return 0;
}
```
I am using CodeBlocks12.11, and MinGW 4.7.0... |
You have to print unsigned variables withu. A long is prefixed withl, hence you needluin this case.
```
printf("%lu\n", x);
```
|
Say you have a file in a git repository:
a.txt
What APIs should be used to create a commit that removes that file?
For example inthis questionthe file is committed without creating it on disk. Is it now possible to remove that file without using the index (stage area)?
I was expecting a similar flow, maybe creating... |
Removing a file is similar to adding a file - you remove the index entry to stage the delete, then you can create a commit from the index.
You probably want to usegit_index_remove_bypath, which will remove the file from the indexandresolve any conflicts that file had.
|
I have a function that gets an operand of a specific enum type that is predefined. For safety reasons, I want the function to test if the operand belongs to the specific enum type. How can I do that?
|
If yourenumlooks something like:
```
enum /* ... */
{
V1,
V2,
/* ... */
VN
};
```
You can use the condition:
```
if (v < V1 || v > VN)
{
/* invalid */
}
```
However, if you give specific values, you have to check against every value. Macros can help you a bit.
There is also an aspect on the standard on... |
In Linux, Whilestdoutto command line, I want to update specific area, such as theapt-getoutput:
```
54% [Waiting for headers] [Waiting for headers] 211 kB/s 3s
```
thepercentage,kB/sandsecondwill update each second.
If we useprintfthen we will get multiple lines output them. I have tried followingprintf:
``... |
Use the carriage return. It will move the cursor back to the start of the line, from which you can overwrite what was in the line before. For example:
```
printf("Hello, world!\rX");
```
Will be visible as:
```
Xello, world!
```
Make sure you flushstdoutoften if you want it to be visible:
```
fflush(stdout);
```
|
I'm trying to use th function similar_text in PHP in my application written in C, I tried googling and downloaded the source but can't I find it. Any one knows where to find the C implementation of the function in php source code? I'm thinking of using using it instead of building my own one.
|
You should start to have a look at:
```
ext/standard/string.c line: 2999
```
This is for php 5.4.10.
You can find this out for yourself using:
```
grep -r 'similar_text' PHP_SOURCE_FOLDER
```
|
```
#include <stdio.h>
#include <math.h>
#include <limits.h>
int main(void)
{
unsigned long x = 0;
x = x ^ ~x;
printf("%d\n", x);
x = (unsigned long)pow(2, sizeof(x)*8);
printf("%d\n", x);
x = ULONG_MAX;
printf("%d\n", x);
return 0;
}
```
I am using CodeBlocks12.11, and MinGW 4.7.0... |
You have to print unsigned variables withu. A long is prefixed withl, hence you needluin this case.
```
printf("%lu\n", x);
```
|
Say you have a file in a git repository:
a.txt
What APIs should be used to create a commit that removes that file?
For example inthis questionthe file is committed without creating it on disk. Is it now possible to remove that file without using the index (stage area)?
I was expecting a similar flow, maybe creating... |
Removing a file is similar to adding a file - you remove the index entry to stage the delete, then you can create a commit from the index.
You probably want to usegit_index_remove_bypath, which will remove the file from the indexandresolve any conflicts that file had.
|
I am new to programming C.. please tell me what is wrong with this program, and why I am getting this error:error C2143: syntax error : missing ';' before 'type'....
```
extern void func();
int main(int argc, char ** argv){
func();
int i=1;
for(;i<=5; i++) {
register int number = 7;
print... |
Visual Studio only supports C89. That means that all of your variables must be declared before anything else at the top of a function.
EDIT: @KeithThompson prodded me to add a more technically accurate description (and really just correct where mine is not in one regard). All declarations (of variables or of anythi... |
I want to split the string "abc 123 456" into the string ("abc") and 2 numbers (123,456). What is the format should I put in the below code?
```
char *s;
int a,b;
sscanf("acb 123 456", format, s, &a, &b);
```
|
You want:
```
"%s%d%d"
```
But you also need to allocate buffer space for the string you extract:
```
char s[100];
int a,b;
sscanf("acb 123 456", "%s%d%d", s, &a, &b);
```
|
```
bail:
if ( err && image ) {
CGImageRelease( image );
image = NULL;
}
if ( provider ) CGDataProviderRelease( provider );
if ( colorspace ) CGColorSpaceRelease( colorspace );
*imageOut = image;
return err;
```
I looked at some code and found this. I have never seen this befo... |
It's a label that thegotostatement jumps to.
The code you're looking at,SquareCamViewController.m, uses a macro namedrequire, like this:
```
require( error == nil, bail );
```
This macro is defined in theAssertMacros.hheader file. It takes a label as its second argument, and usesgotoif the first argument evaluates... |
I was wondering why binary numbers can't be used with bitwise operators?
```
//works
msgSize = (*(msgbody+1) & 0x80)?*(msgbody+5):*(msgbody+3);
//doesn't compile
msgSize = (*(msgbody+1) & 0b10000000)?*(msgbody+5):*(msgbody+3);
```
|
Binary literals aren't supported in C; If they're available, they're an extension. I would suggest that your compiler is emitting an error because it doesn't recognise the binary literal0b10000000. Hence, your compiler probably emits an error on this, too:
```
int main(void) {
int msgSize = 0b10000000;
return... |
I create a server at port 1234 of localhost. In the client code, I initiated astruct sockaddr_in server_addrand filled it with the server's IP address and port number. When I try to connect a client to the server, I get "Address already in use":
bind(client_sockfd, server_addr, sizeof server_addr)
So the OS thinks t... |
You need to usebind()only for the server and in the client use
int connect(int socket, const struct sockaddr *address,
socklen_t address_len);.
See this tutorial for information about sockets in Linux:
http://www.linuxhowtos.org/C_C++/socket.htm
|
```
#include<stdio.h>
int main()
{
char s[]="chomsky the great";
printf("try0 %s\n",s+s[3]-s[9]);
printf("try1 %s\n",s+s[3]-s[1]);
return 0;
}
```
o/p in gcc compiler is
try0 ky the great
try1 ky the great
i'm not able to track what the program is actually doi... |
```
s+s[3]-s[9] = s + *(s+3) - *(s+9) = s + 'm'- 'h' = s + 109 - 104 = s + 5 = s[5]
```
So the printf starts printing at s[5]
examples what printf prints:
```
printf("%s",s) = chomsky the great
printf("%s",s[0]) = chomsky the great
printf("%s",s[2]) = omsky the great
printf("%s",s[5]) = ky the great
```
|
I am investigating a way to access remotely statistics about a linux server, the kind of information thatconkywould display.
Is there a way to interface with conky and obtain the statistics it displays? If not, can you recommend a good way to obtain this kind of statistics? (C/Cpp lib, or maybe python)?
|
You could have conky write to stdout (theout_to_consoleoption) and redirect that to a file. Of course you'd still need to gain external access to the file.
Conky gets most of its data from the files insysfsandprocfs. You could write a program that gathers the information you need from there and puts it on a webpage t... |
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
f->nextis a copy of the value stored incurr. Ifcurrchanges, that will not affectf->nextif nothing is assigned to the latter. Neithercurrnorf->nextever point todir -> head_file; they are both copies.
|
I want to generate shapes like the one following (image file e.g. PNG):
I'm looking for a c / c++ library which will allow me to realize the following algorithm:
The basic algorithm would be:
Make circlePartition Circle randomlyFill in one segementTwirl whole shape (see link)Save Image as PNG
Link: Twirl filter... |
The 'easiest' solution I can think of is to use theGraphicsMagicklibrary - specifically, theMagick++API. With aMagick::Image, you can useDrawableobjects, flood-fills, and even aImage::swirlmethod. Saving as a PNG can be as simple as a call toImage::write("filename.png")
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
I have to write a C program which c... |
The correct format for printing an unsigned long is%lu, not%u
|
This question already has answers here:How to convert a char array to a string?(5 answers)Closed10 years ago.
I'm trying to findhow to convert achararray into astd::string, but I can't find anything to do this.
If it is impossible,could you explain me how can I read an std::string but byscanf()andgets()I can't.
Bes... |
The simplest way of making a string from a character array is using a constructor that takes a pointer and the length, like this:
```
char charArray[] = {'w', 'x', 'y', 'z'};
std:string s(&charArray[1], 2); // s is "xy"
// ^ ^
// | |
// Pointer to the |
// st... |
Im trying to write a simple function that get name and return it after adding an extension to it.
for example, if i have the char pointer to "abcd" the function should return "abcd.as"
I tried to write this function that get char pointer and return a pointer to a new char after adding the extension. But is not workin... |
You have to allocate memory forFixFileName:
```
char* Extension = ".as";
char* FixFileName = malloc(strlen(FileName) + strlen(Extension) + 1);
```
Don't forget tofree()the memory when you're done with it. For obvious reasons, this has to be done outside the function.
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
Let's consider:
```
m = - - i--;
```
Here,- -applies the unary minus twice. This is effectively a no-op. Thus the above can be simplified to
```
m = i--;
```
This is equivalent to:
```
m = i;
i = i - 1;
```
Thus the correct output is0 1.
|
I am new to programming C.. please tell me what is wrong with this program, and why I am getting this error:error C2143: syntax error : missing ';' before 'type'....
```
extern void func();
int main(int argc, char ** argv){
func();
int i=1;
for(;i<=5; i++) {
register int number = 7;
print... |
Visual Studio only supports C89. That means that all of your variables must be declared before anything else at the top of a function.
EDIT: @KeithThompson prodded me to add a more technically accurate description (and really just correct where mine is not in one regard). All declarations (of variables or of anythi... |
I want to split the string "abc 123 456" into the string ("abc") and 2 numbers (123,456). What is the format should I put in the below code?
```
char *s;
int a,b;
sscanf("acb 123 456", format, s, &a, &b);
```
|
You want:
```
"%s%d%d"
```
But you also need to allocate buffer space for the string you extract:
```
char s[100];
int a,b;
sscanf("acb 123 456", "%s%d%d", s, &a, &b);
```
|
```
bail:
if ( err && image ) {
CGImageRelease( image );
image = NULL;
}
if ( provider ) CGDataProviderRelease( provider );
if ( colorspace ) CGColorSpaceRelease( colorspace );
*imageOut = image;
return err;
```
I looked at some code and found this. I have never seen this befo... |
It's a label that thegotostatement jumps to.
The code you're looking at,SquareCamViewController.m, uses a macro namedrequire, like this:
```
require( error == nil, bail );
```
This macro is defined in theAssertMacros.hheader file. It takes a label as its second argument, and usesgotoif the first argument evaluates... |
I was wondering why binary numbers can't be used with bitwise operators?
```
//works
msgSize = (*(msgbody+1) & 0x80)?*(msgbody+5):*(msgbody+3);
//doesn't compile
msgSize = (*(msgbody+1) & 0b10000000)?*(msgbody+5):*(msgbody+3);
```
|
Binary literals aren't supported in C; If they're available, they're an extension. I would suggest that your compiler is emitting an error because it doesn't recognise the binary literal0b10000000. Hence, your compiler probably emits an error on this, too:
```
int main(void) {
int msgSize = 0b10000000;
return... |
I am reading a file of the following form:
```
c h a r a c t e r s
```
with fscanf:
```
fscanf(file, "%c", address);
```
in a loop. Will it read spaces as well? I want to ignore spaces. Should I use
```
fscanf(file, "%c ", address);
```
instead?
However, there is no space after the last character in line, so I'm... |
Put the space in front of the format.
```
scanf(" %c", address)
```
The space really means "readzero or morewhitespace", so" %c"means "ignore optional whitespace and read a character (necessarily not whitespace)".
|
Is there difference in C if I declare function like this:
```
Type * AK_init_observer();
```
and like this:
```
Type* *AK_init_observer();
```
|
Yes, the return types are different. The first returns a pointer toType, whereas the second returns a pointer to pointer toType.
|
I am trying copy an array(temp)from another arraya.
But I have it is not happening.
Fig-1
```
int main()
{
typedef int arr_1[3];
arr_1 arr[4];
arr_1 *temp;
arr_1 a[3] = {1, 2, 3};
memset(&temp, 0, sizeof(temp));
memcpy(temp, a, sizeof(temp));
}
```
But when I tried with a simple program like... |
Becausetempis not an array, it's a pointer and thereforesizeof(temp)has absolutely no relation to the array.
You want to change thememcpyto usesizeof(a). You will also want to givetempa sane value before copying to it, otherwise the program has undefined behavior.
|
I am studying about string in C and I have this question . I've had a look at some question in stackoverflow but I cant find the same Question,if there is pls give me the link :D
For exp,I have a string"D://test.txt"
Now I want to convert it to"D://test1.txt"
I know that I have to find.in the string,then put the nu... |
Usestrchr()(orstrrchr()) to find the dot. Both functions have their prototype in<string.h>.
There is no ready-made function for inserting a character in the middle of a string. You have to write your own.
|
I have a header file suppose abc.h, where i have function declaration as:
```
static int function1();
```
I have included this header file in abc.c and has defined the function and used it.
```
static int function1()
{
< function definition>
}
```
After compiling I am getting warning:
```
warning: function1 decl... |
A static function can be declared in a header file, but this would cause each source file that included the header file to have its own private copy of the function, which is probably not what was intended.
Are u sure u haven't included theabc.hfile in any other .c files?
Because declaring a function as static, requ... |
I have a text file called commands.txt which contains some commands followed by some arguments. Example:
```
STOP 1 2 4
START 5 2 1 8
MOVE
CUT 0 9
```
I want to read every line from this text file and to print something like this
```
STOP: 1 2 3
START: 5 2 1 8
MOVE:
CUT: 0 9
```
I read every line with fgets and th... |
take a look atthis, and use whitespace characters as the delimeter.
|
I am working on a UDP server/client application.
I want my server to be able to handle 40 clients at a time. I have thought of creating 40 threads at server side, each thread handling one client. Clients are distinguished on the basis of IP addresses and there is one thread for each unique IP address.
Whenever a cli... |
There are different approaches for scale able server application, one thread per client seems good if no of clients are not many, another most efficient approach to accomplish this task is to use thread pool. These threads are work as task base when ever you have any new task assign this task to free worker thread.
|
Is there difference in C if I declare function like this:
```
Type * AK_init_observer();
```
and like this:
```
Type* *AK_init_observer();
```
|
Yes, the return types are different. The first returns a pointer toType, whereas the second returns a pointer to pointer toType.
|
I am trying copy an array(temp)from another arraya.
But I have it is not happening.
Fig-1
```
int main()
{
typedef int arr_1[3];
arr_1 arr[4];
arr_1 *temp;
arr_1 a[3] = {1, 2, 3};
memset(&temp, 0, sizeof(temp));
memcpy(temp, a, sizeof(temp));
}
```
But when I tried with a simple program like... |
Becausetempis not an array, it's a pointer and thereforesizeof(temp)has absolutely no relation to the array.
You want to change thememcpyto usesizeof(a). You will also want to givetempa sane value before copying to it, otherwise the program has undefined behavior.
|
I am studying about string in C and I have this question . I've had a look at some question in stackoverflow but I cant find the same Question,if there is pls give me the link :D
For exp,I have a string"D://test.txt"
Now I want to convert it to"D://test1.txt"
I know that I have to find.in the string,then put the nu... |
Usestrchr()(orstrrchr()) to find the dot. Both functions have their prototype in<string.h>.
There is no ready-made function for inserting a character in the middle of a string. You have to write your own.
|
I have a header file suppose abc.h, where i have function declaration as:
```
static int function1();
```
I have included this header file in abc.c and has defined the function and used it.
```
static int function1()
{
< function definition>
}
```
After compiling I am getting warning:
```
warning: function1 decl... |
A static function can be declared in a header file, but this would cause each source file that included the header file to have its own private copy of the function, which is probably not what was intended.
Are u sure u haven't included theabc.hfile in any other .c files?
Because declaring a function as static, requ... |
I have a text file called commands.txt which contains some commands followed by some arguments. Example:
```
STOP 1 2 4
START 5 2 1 8
MOVE
CUT 0 9
```
I want to read every line from this text file and to print something like this
```
STOP: 1 2 3
START: 5 2 1 8
MOVE:
CUT: 0 9
```
I read every line with fgets and th... |
take a look atthis, and use whitespace characters as the delimeter.
|
I am working on a UDP server/client application.
I want my server to be able to handle 40 clients at a time. I have thought of creating 40 threads at server side, each thread handling one client. Clients are distinguished on the basis of IP addresses and there is one thread for each unique IP address.
Whenever a cli... |
There are different approaches for scale able server application, one thread per client seems good if no of clients are not many, another most efficient approach to accomplish this task is to use thread pool. These threads are work as task base when ever you have any new task assign this task to free worker thread.
|
I am struggling with gsoap's return parameter binding. I have a function which returnschar**which is composed like this:{char*, ..., char*, NULL}. I want the generated web service to be able to transmit and process multiple strings in one parameter. Gsoap however generates only:<element name="retVal" type="xsd:string"... |
If I undesrstand your question
You can develop your own function which call the gSoap function to get the returned string from the gSoap function then split the gSoap sting to sub strings and put them into an array and then return your array of strings
|
I'm have a pthread function, which sleeps most of the time usingusleep()I would like to send a signal from the main process to the thread to interrupt the sleeping sometimes.
The problem is that I can't find any reference of which signal exactly to send usingpthread_kill()
theusleep()man page, states thatSIGALRMshou... |
The tools to synchronize between threads are not signals andusleep(ornanosleep) but combinations ofpthread_mutex_tandpthread_cond_t. Just have your thread wait on a condition (this can be done with a timeout) and have yourmainthread send a "signal" on the condition variable.
|
This question already has answers here:What is the meaning of "__attribute__((packed, aligned(4))) "(3 answers)Closed10 years ago.
I came across this piece of code in one of MicroChip's example codes. I'm unable to understand what it exactly means
```
typedef struct __attribute__((packed))
{
BYTE command;
BY... |
__attribute__is agcccompiler option that specifies a separate behavior of the compiler on compilation.
In your case it says to the compiler not to use padding between structure members.
|
My Files are
main.c
```
#include"A.h"
#include"B.h"
```
A.c
```
#include"A.h"
```
B.c
```
#include"B.h"
```
I have a file with a couple of structures that I have defined that I am supposed to use in all the files i.eA.c , B.c, main.cand even the header files forA and B.
Hence I have
A.handB.hboth have
```
#... |
Use include guards.
aheader.h:
```
#ifndef AHEADER_H
#define AHEADER_H
// ... rest of header here
#endif
```
bheader.h:
```
#ifndef BHEADER_H
#define BHEADER_H
// ... rest of header here
#endif
```
|
This question already has an answer here:memcpy vs assignment in C(1 answer)Closed10 years ago.
Suppose pp is a pointer to an array of structs of length n. [was dynamically allocated]
Suppose I want to create a copy of that array of structs and make a pointer to it, the following way:
```
struct someStruct* pp2 = ma... |
There is no definitive answer for all architectures. You need to do profiling to figure out what method is best.
However IMHO I would imagine thatmemcpywould be faster simply that somebody has taken the time for your particular architecture/platform and is able to use particular nuances to speed things up.
|
Is there a simple way to set the value of a variable to the concatenated values of other variables of mixed types?
For example, something that accomplishes the same thing as this...
```
int card=10;
char card_suit='c';
char card_picture[255];
FILE *x
x=fopen("streamy.txt", "w");
fprintf(x, "%d%c.bmp\n", card, card... |
I believe you're looking forsnprintf()and its relatives:
```
char card_picture[255];
snprintf(card_picture, sizeof(card_picture), "%d%c.bmp", card, card_suit);
```
|
Hi guys I'm currently using the code below and I'm pretty sure there's a better way to do it. What the code does is look if there's the delimiter (~~~~), puts everything before ~~~~ in cmd and everything after ~~~~ in param. If anyone could let me know how I should be doing this then it would be very appreciated! I'm ... |
You can simplify your code as follows:
```
char cmd[1024], *tempCharPointer, *param = "";
// Fill in cmd from somewhere...
...
char *delim = strstr(cmd, "~~~~");
if(delim)
{
param = delim+4;
*delim = '\0';
}
```
|
I have this struct:
```
struct sArray {
TCHAR *sName;
};
```
I want to now dynamically allocate memory for an array of sArray, and also dynamically allocate memory for sName. So I can use something like var[0].sName, var[1].sName...var[x].sName.
I'm looking for a simple solution - tons of articles here and on the w... |
Try this:
```
int len = 20; //number of elements (sArray's) you want in ar.
struct sArray *arr = malloc(length*sizeof(struct sArray));
int i;
int nameLength = 30; // max length of name
for (i = 0; i < length; ++i)
arr[i].sName = malloc(nameLength*sizeof(TCHAR));
```
and to free the memory:
```
for (i = 0; i < l... |
I have a 2 dimensional array and 8 concurrent threads writing to the array. If each thread reads/writes to a different array, will it result in a seg fault?
For example:
```
char **buffer;
//each thread has its own thread ID
void set(short ID, short elem, char var)
{
buffer[ID][elem] = var;
}
```
Would this be... |
If each thread writes to a different sub-array, this aspect of your code will be fine and you will not need locking.
|
I'm programming my TI-84 in C with z88dk. I need to call things like normalcdf and Ztest. I know they can be called from ti-BASIC, but how do I call them from C or inline assembly?
|
In TI-84 assembly, you use theBCALLorB_CALLinstruction to do a "system call" into the TI-84's ROM. This is usually used for simple I/O things (B_CALL PutSprints a string to the screen), but it could also be for more complicated mathematical routines (LD A,OPNormal; B_CALL BinOPExeccomputes thenormalcdf(function).
Goo... |
I want to copy string fromargv[0]but I don't know how to get the size ofargv[0].
How to do this?
```
int main(int argc, char* argv[])
{
char str[20];
if(argc>0)
memcpy(str, argv[0], sizeof(argv[0]));
}
```
|
Sinceargv[0]is a string, usestrlen.
```
#include <string.h>
size_t length = strlen (argv[0]) + 1;
memcpy (str, argv[0], length);
```
By the way, you could also usestrcpy, which is more suitable forstrings.
```
#include <string.h>
strcpy (str, argv[0]);
```
In every case, in order to make sure that your copy won... |
When you open a file withCreateFileyou can set its sharing mode (the third parameter).
Is there a way to set the sharing mode when using_open? Possibly by a call to_setmodeor something equivalent? I need to use theFILE_SHARE_DELETEmode.
|
_fsopen,_sopenand similar functions can take a share mode parameter however this does not supportFILE_SHARE_DELETE. If you want this share mode useCreateFile
|
How can I capture packet of applications, including Hotspot Shield and other free proxy applications?
|
If I understand your question, you're looking for a tool that allows you to capture network packets on your machine and examine them.
You can use tools likeWiresharkthat allows you do that.
|
I am working on application which should be running on any Windows NT machine. Today I was trying to deploy my application on new machine and suddenly get error thatmsvcp100.dllis missing. I've started digging into that problem and found solution. Only what I had to do is in project configurations changeRun time libra... |
You aren't supposed to deploy debug builds. Compile with Release settings (including release version of the run-time library) and you won't have that problem. (You can enable debug information on a release build... it's use of the debug libraries that causes problems)
|
Doing an OS programming assignment using semaphores and POSIX threads. Here's my code:
```
#include <pthread.h>
#include <semaphore.h>
sem_t mutex, to_b, to_a;
int main()
{
// Initialize semaphores
sem_init(&mutex, 0, 1);
sem_init(&to_b, 0, 0);
sem_init(&to_a 0, 0);
}
```
Compiling withgcc main.c -... |
There is a comma missing in
```
sem_init(&to_a 0, 0);
```
It should be
```
sem_init(&to_a, 0, 0);
```
|
I wrote a program in which I found the area of cylinder using a functionareawith a return-type and without parameters.answerwas returned tomainfunction. However, I am getting different output inmainand a different output inarea. The decimal places seem to be replaced by 0 in themainfunction. Why is it so?
|
Change the return type of area from int to float
|
I recently had an assignment where I had to dynamically allocate memory for a struct. I used this method:
```
myStruct *struct1 = malloc(sizeof *struct1);
```
This worked just fine. However, I don't understand how. I would think that thestruct1pointer is uninitialized at that point and should therefore have a size o... |
sizeofoperator in C doesn't evaluate the operand. It just looks at the type. For example:
```
#include <stdio.h>
int main(void)
{
int i = 0;
printf("%zu\n", sizeof i++);
printf("%d\n", i);
return 0;
}
```
If you run the above program, you will see thatiis still 0.
So, in your example,*struct1is n... |
I always add the _CRT_SECURE_NO_WARNINGS to all of my C/C++ projects in the Preprocessor Definition tab in the Project Properties. There is the drop-down for <edit> and <inherit from parent or project defaults>. How do I change the values of the project defaults. I would think it is an XML file hidden somewhere, or th... |
View -> Property Manager, then expand a project and build configuration to see the property sheets being used for that build configuration. Right-click on a property sheet and select Properties to modify the property sheet. I don't recommend modifying the built-in property sheets, however there is a .user property she... |
my server is sending a sample response header with body to a request:
```
static char* not_found_response_template =
"HTTP/1.1 404 Not Found\n"
"Content-type: text/html\n"
"\n"
"<html>\n"
" <body>\n"
" <h1>Not Found</h1>\n"
" <p>The requested URL was not found on this serv... |
HTTP requires that lines be terminated by CR+LF, so try\r\n.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
I am trying to understand more sock... |
You're really suggested to readBeej's guideto network programming to make sense of these functions. Manpages (-S2) will help too.
The source code of the function (if that's what you hope to find) won't help a lot. They call system calls to do their job, as they're mostly OS-abstraction layer. What you need is their d... |
I am wanting to fetch the current console size in rows and columns. Using theGetConsoleScreenBufferInfofunction I can get aCONSOLE_SCREEN_BUFFER_INFOstructure which has the following:
```
typedef struct _CONSOLE_SCREEN_BUFFER_INFO {
COORD dwSize;
COORD dwCursorPosition;
WORD wAttributes;
SMALL... |
The size of the window is in thesrWindowfield:
srWindowA SMALL_RECT structure that contains the console screen buffer coordinates of the upper-left and lower-right corners of the display window.
|
Could you please help me with an algorithm for selective repeat protocol file transferring good documentation?Is there any book for protocol programming just like Beej guide for Network Socket Programming?
|
You could try the TCP RFCs
I believethis oneis the one you want.
You could also pick up a textbook on networking:Computer Network: A Top Down Approachis a pretty good one (I've taken a few networking courses and that's been the best one thus far).
Also, google is your friend!
|
I have three files:
header.h
```
#ifndef _HEADER_
#define _HEADER_
int var = 0;
#endif
```
src1.cpp
```
#include "somefile.h"
extern int var;
int main(void) { // error: first defined here
var = 10;
return 0;
}
```
src2.cpp
```
#include "somefile.h"
extern int var;
int foo () { // error : multiple defi... |
put the declaration of
```
int var = 0;
```
in one of the cpp file and not in the header file
and put the
```
extern int var;
```
in the header file only
|
Recently I have come across a program which contained data types like
```
uint32_t, uint32, uint64 etc.
```
Can I run the program in Windows 7 (32 Bit) without making any changes?
I use Code::Blocks 10.05 with MingW.
If changes are required, which data types can replace them?
Also I would like to know which standa... |
These are from<stdint.h>, a C standard header introduced with C99, I think.
If you don't have C99 or a compatible header already in your system, which youreallyshould have andreallyshould investigate, you need to re-create the definitions yourself.
To do this you need to introduce a bunch oftypedefs:
```
typedef un... |
This question already has answers here:problems in floating point comparison [duplicate](2 answers)Floating point comparison [duplicate](5 answers)Closed10 years ago.
I worked out the following code and got a bizarre output. Can anyone explain how it works?
```
main()
{
float a=0.8;
float b=0.25;
if(a==0... |
This is because 0.25 is a power of two (i.e. 2^-2), while 0.8 is not. Only exact sums of powers of two can be represented exactly; all other numbers, including 0.8, are represented as an approximation, which has a different precision betweenfloatanddouble. The0.8ina==0.8is adouble, whileais afloat. Their representatio... |
If I have a condition like this:
```
if (X && Y) {}
```
Will the compiler checkYifXis false? Is it compiler dependent?
|
In C andmost other languagesshort-circuit evaluation is guaranteed. SoYis only evaluated ifXevaluates to true.
The same applies toX || Y- in this caseYis only evaluated ifXevaluates to false.
SeeMike's answerfor a reference to the C specification where this behavior is mentioned and guaranteed.
|
```
#include <stdio.h>
int main()
{
int i = 10;
return 0;
}
```
In the above program, where exactly the value 10 is stored ?
I understand the variable i is stored in the stack. stack is populated during run time. From "where exactly" 10 is coming from.
|
10 is a constant, so the compiler will use the number 10 directly in the executable part of your program as part of the CPU instructions.
Here's the assembly produced on my system withgcc:
```
movl $10, -4(%rbp)
```
(The4is because anintis 4 bytes long)
Note that all of these things are part of the implementati... |
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
theawill be1or0
1: Ifexecute != 0andcount >0
0: otherwise
Note:
count >0if and only ifpcnt[0]!=0orpcnt[1]!=0orpcnt[2]!=0orpcnt[3]!=0orpcnt[4]!=0
|
Multiple markers at this line
- previous definition of 'type' was here
- redefinition of parameter 'type'
int parseLine(char* line, int* day, float* amount,char* type, char* type);
That's the error I'm getting in a header C file in Eclipse
|
The error tells you that you definedchar* typetwice
|
When statically initializing a recursive mutex, what is the difference between
```
static pthread_mutex_t foo_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
```
and
```
static pthread_mutex_t foo_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
```
and why should I want the one instead of the other?
|
"_NP" is meant as a hint that the feature is nonportable. In order to keep the hint there, you are best off to use the "_NP" version.
Other than that I suspect there is no difference. Not 100% sure, though.
|
I'm implementing an alphabetic search based on telephone keypad, likePhone keypad1
When user types , say 2, I get {A, B, C} in the combination. When user types 23, I get {AD, AE, AF, BD, BE, BF, CD, CE, CF} in the combinations, and so on. If I keep typing and make combinations I get thousands of combinations which ma... |
You could build atrieof valid prefixes based on the dataset you're searching. Matching partial inputs against that should be pretty easy.
|
```
void mscanf(char *format, ...)
{
scanf(format);
}
int main()
{
int n1, n2;
mscanf("%d%d", &n1, &n2);
printf("%d,%d\n", n1, n2);
return 0;
}
```
what's wrong with this.?
How could I use scanf in a function just like this?
thanks.
|
Instead of yourscanfyou wantvscanf:
```
va_list args;
va_start(args, format);
vscanf(format, args);
va_end(args);
```
When you use functions with variable arguments list you sometimes stumble on the need topass those variable arguments. So in your example you know what you want to do, you want to "pass the '...' t... |
```
case MAP_KEY3:
case MAP_KEY4:
case MAP_KEY5:
case MAP_KEY6:
break;
default:
LampShow(LampID, 0);
LampShow(LampID, 2);
LampShow(LampID, 0);
break;
```
I want to make a MARCO of above code so that I can use it anywhere repeatedly. But how to do?
It is for C language.
If I do it like below:
```... |
```
#define EVIL_MACRO \
case MAP_KEY3: \
case MAP_KEY4: \
case MAP_KEY5: \
case MAP_KEY6: \
break; \
default: \
LampShow(LampID, 0); \
LampShow(LampID, 2); \
LampShow(LampID, 0); \
break;
```
|
I'm attempting to write a safe file input. I have a fixed buffer size of 128. I want to read the strings from the file, but before copying them I want to check they are less than or equal to128in length.
Can I do something like:
```
fscanf(fp, "%128s", myString)
```
I've seen that scanf used in the same way will li... |
Yes, you can do that but you're off by 1.
So if you have an array of 128 characters in length:
```
char myString[128] = {'\0'};
fscanf(fp, %127s", myString);
```
You mentioned that you've seen that syntax used inscanf(), well that's the same thing as:
```
fscanf(stdin, "%127s", myString); // just like scanf("%127s... |
I have a file opened withfopen. There is a way to reopen the same file (while it is opened) but have adifferentseek? (so i can use fread independently)
|
there is no problem if you keep reading only.
Be careful if you write in the file especially if you have 2 threads that access with read/write to the file at the same time
If your code looks like that
```
FILE *fp1, *fp2;
fp1 = fopen("file", "r");
fp2 = fopen("file", "r");
```
then you have 2 seeks in the same fi... |
It's pretty simple. Let's say I have:
```
char x = -1;
```
Then in memory, I have (most likely?)
```
11111111
(01234567)
```
So my question is, if I write&xis the address I get back the address of bit 0 or bit 7 and is this the most or least significant bit?
What about in the case of a 32bit integer?
|
the memory address are byte-addressed, not bit addressed. Which means you will - depending upon the type of architecture(big endian or little endian) you will get the most significantbyteor least significantbytenot specificbit
Thanks to WhozCraig, yes - since your variable is acharit is the address of thecharor the b... |
I need solve this transcendental equation in C:
x = 2.0 - 0.5sen(x)
I tried this:
```
double x, newx, delta;
x = 2.0 - 0.5;
newx = sin(x);
delta = fabs(newx * x);
printf("%f", delta);
```
This is correct?
Thanks!
|
Use a numeric method to solve your equation, likeNewton's methodor (a lot easier to use, and not too much slower in practice) thesecant method. For the last one,don'trewrite the expression for the next x, it is written that way so that rounding errors (a problem near the root) don't affect too much.
|
Is it possible to declare a 2D array like so:
```
char words[128][25];
```
And then only assign to it like so:
```
int i=0;
while(fscanf(fp,"%s" words[i++]) != EOF){
printf("Copied");
}
```
I've seen it in a snippet of code, didn't understand so tried it out and just get a crash from codeblocks when it attempt... |
That is a legal way of using arrays; the problem appears to be in your while:
```
while(fscanf(fp,"%s words[i++]) == EOF){
```
You just need a closing quote and comma after the"%s.
|
I am initializingINOTIFYby usinginotify_init()and I callreadwith no mask flags. When I want to use the watch descriptorwdI can see that it is returned with value -1. Reading the man page I can see that this value is set only when the even queue overflowed, BUT only if the call to read has the mas bit IN_Q_OVERFLOW set... |
Then you misread the manual,inotify_init(2)clearly says:
On success, these system calls return a new file descriptor. On error, -1 is returned, and errno is set to indicate the error.
So look in errono, to see what you are doing wrong.
|
In infinite loop, i am accepting new connections, but i need choice to stop that server, so i want use ctrl+c (SIGINT). When i press it, it calls my signal handler, but it doesn't interrupt accept call, so the check if interrupt is true isn't evaluated (when no client's connecting, so accept is blocking for long while... |
Your OS is usingSA_RESTARTsemantics by default when usingsignal(). You should be able to confirm this in the man page. Since you don't want this to happen, usesigaction()to set the handler and omit theSA_RESTARTflag.
|
I want to ask is that there is a function to read text file from bottom up in C ?
Exp: text content isabcdef--> we will getfedcba.
If there is no such function like that,I'm thinking about pass text content into an array,then reverse the array,is that ok ? Do you have better solution for this question :)
|
you can develop your own function that reads from bottom usingfseek()standard function:
```
char *my_read(FILE *fp)
{
int i, size;
char *buffer;
fseek(fp, 0, SEEK_END);
size = ftell(fp);
buffer = malloc((size+1) * sizeof(char));
for (i=0; i<size; i++)
{
fseek(fp, size-1-i, SEEK_... |
I'm trying to parse a file that another function has written with this fprintf:
```
fprintf(file, "DS;%s;%ld;%ld;%u\n", ds->name, ds->start, ds->period, ds->size)
```
I'm using this fscanf:
```
fscanf(file, "DS;%[^;$]s;%ld;%ld;%u", file_name, &file_start, &file_period, &file_size)
```
file_name is read with no pro... |
replace the string format"%[^;$]s"by this%[^;$]==> remove thesbecause[]replace thesso no need any more fors
|
Anybody knows, how to get real value of clock per sec?clock()fromtime.hreturns clocks from start of my process, so it need to be divided byCLOCKS_PER_SEC, but this constant has always value1000000.
Is there some POSIX standard for this?
|
That's how it specified in the C specification.
If you want to measure elapsed time, there are other (and better) functions, likegettimeofdayfor example.
|
I want to compile a.cfile to 32-bit executable usinggccoption-m32with libpcap
the machine is linux 64bit fedora 16
however, I get the following error
```
[root@fdf source]# gcc -m32 -o test_tcp test_tcp.c -lpcap
/usr/bin/ld: skipping incompatible /usr/lib64/libpcap.so when searching for -lpcap
/usr/bin/ld: cannot fi... |
You need the development package in addition to the runtime library. So do
yum install libpcap-devel.i686
|
I'm starting to learn how to program Windows drivers but can't seem to find anywhere that contains the definition of IN located in the argument declarations of functions. For example:
```
NTSTATUS DriverEntry( IN PDRIVER_OBJECT DriverObject,
IN PUNICODE_STRING RegistryPath)
```
Could someone p... |
These are called SAL (Source Annotation Language) annotations and there isMSDN documentationon how to use them to benefit from great static analysis.
The actual syntax may differ from one SAL version to another (e.g. IN and _In_). There's backwards compatibility, but I recommend using the latest syntax consistently.
|
There is some mistake in power function of my code it returns correct answer for small values but gives wrong answer for large values.
```
#include<stdio.h>
long long MOD= 1000000007;
long long power(long long i,long long j)
{
if(j==0)
return 1;
long long d;
d=power(i,j/(long l... |
Your arithmetic overflowed the values representable in along longin your C implementation.
Also, you are working on a challenge problem or homework which has been discussed numerous times on Stack Overflow, as you can see by searching for “1000000007”.
|
Im trying to implementExternal Sorting in C.
I have to read N integers (fixed depending on main memory) from a file initially so that I can apply quicksort on them and then continue with the merging process.
I can think of these 2 ways:
read N integers one by one from the file and put them in an array then sort the... |
Don't try to be more clever than your OS, it probably supports some clever memory management functions, which will make your life easier, and your code faster.
Assuming you are using a POSIX compliant operating system, then you can usemmap(2).
Map your file into memory with mmapSort itSync it
This way the OS will h... |
```
int main()
{
int err1, err2;
struct rlimit rlim;
err = getrlimit(RLIMIT_NOFILE, &rlim);
printf("max_fds: %d\n", rlim.rlim_max); // 4096
err1 = dup2(1, 1023); // OK
err2 = dup2(2, 4090); // error: EBADF
return 0;
}
```
Like the codes above, I use getrlimit to get the max# of open f... |
getrlimit()returns a structurerlimitthat contains two values:
thecurrentlimit, calledrlim_cur, which is the value that the kernel enforces for the corresponding resource.themaximumlimit, calledrlim_max, which is the ceiling value that an unpriviliged user can setrlim_curto.
tl;dr, userlim_cur!
```
printf("max_fds: ... |
I have a C function witch looks like:
```
int foo(int a, long long b);
```
I'm trying to call it from arm assembly, but I don't know how to deal with the second parameter(long long).
|
TheARM EABI/AAPCSspecifies that 64bit types should be passed in 2 registers which are next to each other and the first register must be even numbered. In little endian mode the high part resides in the higher numbered register, while the low part is put in the lowered numbered one. In big endian mode it's vice versa.
... |
There is some mistake in power function of my code it returns correct answer for small values but gives wrong answer for large values.
```
#include<stdio.h>
long long MOD= 1000000007;
long long power(long long i,long long j)
{
if(j==0)
return 1;
long long d;
d=power(i,j/(long l... |
Your arithmetic overflowed the values representable in along longin your C implementation.
Also, you are working on a challenge problem or homework which has been discussed numerous times on Stack Overflow, as you can see by searching for “1000000007”.
|
Im trying to implementExternal Sorting in C.
I have to read N integers (fixed depending on main memory) from a file initially so that I can apply quicksort on them and then continue with the merging process.
I can think of these 2 ways:
read N integers one by one from the file and put them in an array then sort the... |
Don't try to be more clever than your OS, it probably supports some clever memory management functions, which will make your life easier, and your code faster.
Assuming you are using a POSIX compliant operating system, then you can usemmap(2).
Map your file into memory with mmapSort itSync it
This way the OS will h... |
```
int main()
{
int err1, err2;
struct rlimit rlim;
err = getrlimit(RLIMIT_NOFILE, &rlim);
printf("max_fds: %d\n", rlim.rlim_max); // 4096
err1 = dup2(1, 1023); // OK
err2 = dup2(2, 4090); // error: EBADF
return 0;
}
```
Like the codes above, I use getrlimit to get the max# of open f... |
getrlimit()returns a structurerlimitthat contains two values:
thecurrentlimit, calledrlim_cur, which is the value that the kernel enforces for the corresponding resource.themaximumlimit, calledrlim_max, which is the ceiling value that an unpriviliged user can setrlim_curto.
tl;dr, userlim_cur!
```
printf("max_fds: ... |
I have a C function witch looks like:
```
int foo(int a, long long b);
```
I'm trying to call it from arm assembly, but I don't know how to deal with the second parameter(long long).
|
TheARM EABI/AAPCSspecifies that 64bit types should be passed in 2 registers which are next to each other and the first register must be even numbered. In little endian mode the high part resides in the higher numbered register, while the low part is put in the lowered numbered one. In big endian mode it's vice versa.
... |
Can you help me to find the main (only) thread ID of a given by ID process, please ?
Task context:
A running process has (at the moment) no windows but a(some) thread(s).
Wanted:
Posting ofWM_QUITat the main thread only.
Not-wanted:
Using ofTerminateProcessor postingWM_QUITat the non-primary threads.
|
A much simpler and surer way to get the thread id of the main thread is to let the main thread records its own thread id using::GetCurrentThreadId()into a shared global variable, perhaps in your WinMain or somewhere at the very beginning of your 'main thread':
```
MainThreadId_G = ::GetCurrentThreadId();
```
then in... |
In my application, written in C, under Windows-XP:
how can I check if a file is already open by another application?
One option is to rename the file, and to check if it was renamed.
Another option is to open the file for appending.
But these options are very time-consuming.
Is there any other, less time-consuming so... |
No function exists in the Windows API that will check if a function is open in another application. If it did exist it would be subject to a race condition.
Suppose that you checked first whether or not a file was already opened and the answer came back that it was not currently open. Then you move on to open it, but... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.