question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
So I have the number 12 how do I printout it out in the format
```
0x0000000C // where there is always the 0x in the beginning and always 8 digits after to
// represent the number
fprintf(outputFile, "%x", 12);
```
is giving me:
```
cc
```
But I want:
```
0x0000000C
```
|
need to prefix 0x and then Capital X to get the Capital C and 08 says prefix with 0s to make up to 8 characters
```
fprintf(outputFile, "0x%08X", 12);
```
|
I am usingstructwithunsigned intbit-fields perfectly, but suddenly, after duplicating one of them, the compiler is losing its mind (it would seem). Here's my code:
```
typedef struct myStruct {
unsigned int myVar:1;
} myStruct; // my compiler requires TWO declarations of the name for typedef
myStruct myNewStruct... |
You can declare the variable as a global outside of function scope, but you can't have a separate line of code to set its value. Setting the value on a separate line is executable code rather than initialization, and is not permitted there.
If you want to initialize it at the point of declaration, try:
```
myStruct ... |
Need to figure out a code that counts all the repeating symbols in a string. As you can see below, so far so good.
And here starts the tricky part, at the end of the code I want to output symbols in an order they were typed which had for example 2 occurences in a string, and I got problems figuring that out.
```
int... |
Just iterate through the source string again and for each character look into yourcountsarray.
If you don't want to print the same statistics for every occurence of repeating character, you can reset the correspondingcountsvalue to zero just after you print the statistics, and have an additional check before printing... |
In C, suppose var1 is a variable in foo1() and foo2() wants to access var1, however, foo1() doesn't call foo2(), so we can't pass it by parameter. At the same time, only foo1() and foo2() will access it, so I wouldn't like to declare it as global variable. It will be similar with the "friend semantics" in c++, is ther... |
you pass the variable to both functions.... in general functions shouldn't hold state.
quickly you find passing variables is not so nice and becomes fragile, so instead, you pass structs.... then functions start working on the state of structs.
```
typedef struct
{
int var1;
} blah_t;
void foo1(blah_t* b)
{
... |
I am trying to implement regular expression in C, I have the following code to find all the string which contains '*' in it,
```
regex_t regex;
regcomp(®ex, "^[A-Za-z0-9\*]+$", 0);
if (!regexec(®ex, args[j], 0, NULL, 0)) {
printf("string found");
}
```
Is this the right way to do it? My code is not matchi... |
In C++, the character\needs to be escaped. So if you want to escape an regex*, you need to do\\*. That should fix the problem. Whenever you use the backslash in a string, you need to escape it like that. If you ever need to find it in a string with the regex, you'll need to search for it with\\\\.
|
I am using sendfile to send and receive files between the client and server, sending the file is fine, but when receiving the file, it returns -1, and the errno is 29 illegal seek, I am not sure what is wrong.
```
int fd = open(filename, O_WRONLY | O_CREAT);
off_t offset = 0;
int ret = sendfile(fd, sockfd, &offset, f... |
The man page forsendfile()says:
Thein_fdargument must correspond to a file which supports mmap(2)-like operations (i.e., it cannot be a socket).
Thein_fdis the second argument, the one you namedsockfd. That suggests your problem is that the input file descriptor is not valid for use withsendfile().
|
So I have the number 12 how do I printout it out in the format
```
0x0000000C // where there is always the 0x in the beginning and always 8 digits after to
// represent the number
fprintf(outputFile, "%x", 12);
```
is giving me:
```
cc
```
But I want:
```
0x0000000C
```
|
need to prefix 0x and then Capital X to get the Capital C and 08 says prefix with 0s to make up to 8 characters
```
fprintf(outputFile, "0x%08X", 12);
```
|
I am usingstructwithunsigned intbit-fields perfectly, but suddenly, after duplicating one of them, the compiler is losing its mind (it would seem). Here's my code:
```
typedef struct myStruct {
unsigned int myVar:1;
} myStruct; // my compiler requires TWO declarations of the name for typedef
myStruct myNewStruct... |
You can declare the variable as a global outside of function scope, but you can't have a separate line of code to set its value. Setting the value on a separate line is executable code rather than initialization, and is not permitted there.
If you want to initialize it at the point of declaration, try:
```
myStruct ... |
Need to figure out a code that counts all the repeating symbols in a string. As you can see below, so far so good.
And here starts the tricky part, at the end of the code I want to output symbols in an order they were typed which had for example 2 occurences in a string, and I got problems figuring that out.
```
int... |
Just iterate through the source string again and for each character look into yourcountsarray.
If you don't want to print the same statistics for every occurence of repeating character, you can reset the correspondingcountsvalue to zero just after you print the statistics, and have an additional check before printing... |
In C, suppose var1 is a variable in foo1() and foo2() wants to access var1, however, foo1() doesn't call foo2(), so we can't pass it by parameter. At the same time, only foo1() and foo2() will access it, so I wouldn't like to declare it as global variable. It will be similar with the "friend semantics" in c++, is ther... |
you pass the variable to both functions.... in general functions shouldn't hold state.
quickly you find passing variables is not so nice and becomes fragile, so instead, you pass structs.... then functions start working on the state of structs.
```
typedef struct
{
int var1;
} blah_t;
void foo1(blah_t* b)
{
... |
To sort an array of strings in ascending order, I use:
```
int cmp(const void *p, const void *q) {
char* const *pp = p;
char* const *qq = q;
return strcmp(*pp, *qq);
}
```
This will be then implemented into a qsort like so:
```
qsort(a, sizeof(a)(sizeof(a[0]), sizeof(a[0]), cmp);
```
How do you sort... |
One quick and easy way to do this is to multiply the result ofstrcmp()by -1 before returning it.
```
int cmp(const void *p, const void *q) {
char* const *pp = p;
char* const *qq = q;
return -strcmp(*pp, *qq);
}
```
|
Thedeviationfunction throws me the following error:"Array subscript is not an integer". If you can help me locate the cause of error I'll appreciate it.
```
float average(float data[], int n) {
float total = 0;
float *p = data;
while (p < (data + n)) {
total = total + *p;
p++;
}
... |
pis a pointer to a float. That's why you're getting the error.
```
float *p, total;
...
total += (datos[p]-prom)*(datos[p+1]-prom);
```
You can only useintsas array indices in C.
|
I am running a C++ project which is getting crashed often.
My environment : UBUNTU
IDE : Netbeans C++
I need to take a stack trace and send it to some one for reference to analyse the cause of crash. How to do it in Netbenas IDE?
|
When you get the error, Netbeans asks you about what to do with the signal received, you canDiscard and Pause.Then at theOutputview (usually located below your code, or to the right), you can see aCall Stacktab.
There you can see your stack trace. Now, to take that stack trace in a text file, simply, click on an entr... |
How can i give the continue statement to force the next iteration of the outer loop to take place?
```
for(i=0;i<strlen(name1);i++) // Outer Loop
{
for(j=0;j<strlen(name2);j++) //inner Loop
{
if(name1[i]==name2[j])
{
name1[i]='*';
continue; //... |
```
for(i=0;i<strlen(name1);i++) // Outer Loop
{
for(j=0;j<strlen(name2);j++) //inner Loop
{
if(name1[i]==name2[j])
{
name1[i]='*';
break; // <-- break out of loop
}
}
}
```
|
```
typedef struct structA
{
char C;
double D;
int I;
} structA_t;
```
Size of this structA_t structure:
sizeof(char) + 7 byte padding + sizeof(double) + sizeof(int) = 1 + 7 +
8 + 4 = 20 bytes
But this is wrong , the correct is
24
. Why?
|
There is most likely 4 byte padding after the lastìnt.
Ifsizeof(double) == 8then likelyalignof(double) == 8also on your platform.
Consider this situation:
```
structA_t array[2];
```
If size would be only 20, thenarray[1].Dwould be misaligned (address would be divisible by 4, not 8 which is required alignment).
|
I have a bit of C code, which goes exactly like this:
```
short int fun16(void){
short int a = 2;
short int b = 2;
return a+b;
}
```
When I try to compile it with GCC, I get the warning:
```
warning: conversion to 'short int' from 'int' may alter its value [-Wconversion]
return a+b;
^
```
T... |
When you do arithmetic computations, the operands are subject to "the usual arithmetic conversions" (a superset of the "integer promotions" quoted inAcme's answer—he beat me to this but I'll go ahead and post anyway :-) ). These widenshort intto plainint, so:
```
a + b
```
computes the same result as:
```
((int) a... |
I server report need to display the clients ip address in the report which is processed by the server,that is i need to display from which client the report is being sent. How do i do this? Can anybody help me out?
|
use this :
```
char clntName[INET6_ADDRSTRLEN];
char portName[6];
if (getnameinfo(&client_address,
sizeof client_address,
clntName,
sizeof(clntName),
NULL,
0,
NI_NUMERICHOST|NI_NUMERICSERV|NI_NUMERICSCOPE) == 0) {
pr... |
I have this simplegetNode()function over here. Now, suppose the user calls for a node at an index that is greater than the length of the linked list itself. How can I handle such an error and return something?
```
NODE* getNode(NODE* start, int index)
{
int i;
for(i = 0; i < index; i++)
{
start = ... |
Usually you returnNULL. Some libraries have function declarations like:NODE *getNode(NODE *start, int index, int *status);that sets a status code if there was an error.
You could do something like:
```
NODE *getNode(NODE *start, int index, int *status)
{
// status of 1 means node not found
*status = 1;
/... |
While running the code below I see, that"x,y"pattern occurs. This pattern is beeing printed here:printf("%s", start);. Butif (strncmp(cp, VAL, strlen(VAL) == 0 ))is not stepped in. I wouold expect, it should be stepped in.
What is wrong?
```
me@host ~ $ ./test|grep x,y
<P k="x,y" v="160.59" z="100"/>
```
This is ... |
Maybe you meant
```
if (strncmp(cp, VAL, strlen(VAL)) == 0)
```
instead that
```
if (strncmp(cp, VAL, strlen(VAL) == 0 ))
```
which basically checks0characters, returns0, so the condition is alwaysfalse.
|
In Windows' C API, how can you get a list of network interface names? (Equivalent togetifaddrs()in Linux)
TheWSAIoctl(sock, SIO_GET_INTERFACE_LIST_EX, ...)function seems to only return IP addresses, plus a little metadata.
|
GetAdaptersAddresses()does this.
UseGetIpAddrTable()if you are interested in IPv4 addresses only.
|
This question already has answers here:C Language, scanf issue with char's [duplicate](3 answers)Closed9 years ago.
I have learnt a few languages in the past and I thought it would be a good I idea to learn C.
I am having a little trouble with scanf...
here is the code:
```
#include <stdio.h>
#include <string.h>
... |
do the following:
```
printf("Is your name %s? [y/n]", name); scanf("%c", &yn);
```
What the new scanf does is says "expect a char" and put it in the address of yn
|
Is it possible to write C code so that when it is compiled with
```
gcc -o foo foo.c
```
it in fact compiles foo.c with -O2?
I am using gcc 4.4.6.
|
recent gcc knows a#pragma GCC optimizepragma (http://gcc.gnu.org/onlinedocs/gcc/Function-Specific-Option-Pragmas.html)
|
I am trying to read in a matrix file where the first 2 lines display the number of rows then columns in the array. After that each line contains 1 double as an entry into that matrix (in row traversal format). I can read in most of the data fine, but I obtain a bus error when I try to obtain the second to last row (8t... |
Although your array indexes will only go from0..row1-1and0..col1-1, the array dimensions must berow1andcol1:
```
double input[row1][col1];
```
|
I have this simplegetNode()function over here. Now, suppose the user calls for a node at an index that is greater than the length of the linked list itself. How can I handle such an error and return something?
```
NODE* getNode(NODE* start, int index)
{
int i;
for(i = 0; i < index; i++)
{
start = ... |
Usually you returnNULL. Some libraries have function declarations like:NODE *getNode(NODE *start, int index, int *status);that sets a status code if there was an error.
You could do something like:
```
NODE *getNode(NODE *start, int index, int *status)
{
// status of 1 means node not found
*status = 1;
/... |
While running the code below I see, that"x,y"pattern occurs. This pattern is beeing printed here:printf("%s", start);. Butif (strncmp(cp, VAL, strlen(VAL) == 0 ))is not stepped in. I wouold expect, it should be stepped in.
What is wrong?
```
me@host ~ $ ./test|grep x,y
<P k="x,y" v="160.59" z="100"/>
```
This is ... |
Maybe you meant
```
if (strncmp(cp, VAL, strlen(VAL)) == 0)
```
instead that
```
if (strncmp(cp, VAL, strlen(VAL) == 0 ))
```
which basically checks0characters, returns0, so the condition is alwaysfalse.
|
In Windows' C API, how can you get a list of network interface names? (Equivalent togetifaddrs()in Linux)
TheWSAIoctl(sock, SIO_GET_INTERFACE_LIST_EX, ...)function seems to only return IP addresses, plus a little metadata.
|
GetAdaptersAddresses()does this.
UseGetIpAddrTable()if you are interested in IPv4 addresses only.
|
This question already has answers here:C Language, scanf issue with char's [duplicate](3 answers)Closed9 years ago.
I have learnt a few languages in the past and I thought it would be a good I idea to learn C.
I am having a little trouble with scanf...
here is the code:
```
#include <stdio.h>
#include <string.h>
... |
do the following:
```
printf("Is your name %s? [y/n]", name); scanf("%c", &yn);
```
What the new scanf does is says "expect a char" and put it in the address of yn
|
Is it possible to write C code so that when it is compiled with
```
gcc -o foo foo.c
```
it in fact compiles foo.c with -O2?
I am using gcc 4.4.6.
|
recent gcc knows a#pragma GCC optimizepragma (http://gcc.gnu.org/onlinedocs/gcc/Function-Specific-Option-Pragmas.html)
|
I am trying to read in a matrix file where the first 2 lines display the number of rows then columns in the array. After that each line contains 1 double as an entry into that matrix (in row traversal format). I can read in most of the data fine, but I obtain a bus error when I try to obtain the second to last row (8t... |
Although your array indexes will only go from0..row1-1and0..col1-1, the array dimensions must berow1andcol1:
```
double input[row1][col1];
```
|
Current Implementation of my process,
If there is a logic error in the process, it will dumb the core and quit by deliberately accessing invalid memory area. (sending SIGSEGV signal)
```
char* pzCoreMsg = "Logic Error";
char* zTmp = NULL;
strcpy(zTmp, pzCoreMsg);
```
Other Possible Implementations
1) Callingrais... |
Instead of relying on undefined behavior, just callabort(). It will raise SIGABRT and dump core by default.abort()will also unblock SIGABRT, and if the signal is ignored (or if the signal handler returns), it will restore the default disposition and raise it again. There's really no need to do anything further.
|
I have a function like :
```
char * s;
{
char * i = s, * t;
for(t = s;*t != NULL;t++)
if (*t == '/') i = t+1;
return i;
}
```
The warning I get is comparison between pointer and integer. How can U resolve it?
|
Stop treatingNULLas a character, it's supposed to be a pointer-type constant.
Your loop header should be:
```
for(t = s; *t != '\0'; ++t)
```
This is the "overly explicit" way of writing it, some C programmers aiming for maximum terseness will just say:
```
for(t = s; *t; ++t)
```
Since a comparison to'\0'is the ... |
I'm trying to print out a memory address backwards like in a little endian machine, but for some reason my program is outputting both char arrays in my program.
```
char address[8];
char result[16];
scanf("%s", address);
int x = 1;
for(x; x<5; x++)
{
int y = 4*x;
int z = 8 - 2*x;
result[y-4] = '\\';
result[y-3] = 'x'... |
You forget to terminate the string. In fact, your array is to small for the terminator, you need it to be 17 characters, then doresult[16] = '\0';.
Oh, and you have an out-of-bound error in your code as well, as if you enter 8 characters for the input thenscanfwill write 9 characters to the 8-character array.
|
I am having trouble dynamically declaring a 2D array (one dimension of known size, the other not known until a file is read and the number of lines stored in the integer ·lines·).
```
int NColDataType = 16;
char *DataType[NColDataType];
DataType = (char *)malloc(sizeof(char)*lines);
```
When this is compiled, I rece... |
The variableDataTypeis an array of pointer, and you try to assign a pointer to it. I think you mean to do e.g.
```
DataType[0] = malloc(lines);
```
Ordo you wantDataTypeto be a pointer to an array, like
```
char (*DataType)[NColDataType];
DataType = malloc(sizeof(DataType[0]) * lines);
```
|
In pg 44, C programming language by K&R, at the bottom it said:
For example, suppose that int is 16 bits and long is 32 bits. Then -1L < 1U, because 1U, which is an int, is promoted to a signed long. But -1L > 1UL, because -1L is promoted to unsigned long and thus appears to be a large positive number.
I really don'... |
In C, the same basic bits0xffffhas two different values.
If you treat the 16-bit number as "signed" then0xffffis -1, if it is "unsigned" then0xffffis 65535.
When you compare a signed value with an unsigned value, the bits in the signed value get treated as "unsigned" and if the value was negative, the new value is p... |
I have aserver.cI can connect to it if I know the port that I assign to the server; lets say 6000. I go to FireFox and type127.0.0.1:6000and I can connect perfectly.
How do I build my server that a client will type 127.0.0.1 on a browser and then the server will assign the port or notify the user on the browser to ty... |
You need a port to connect. HTTP connects to port 80 by default and that's why you can get away by typing 127.0.0.1 into your browser.
|
Which file configures caching on Windows Embedded Compact 7.0?
(For example, on VxWorks I can modify OS caching settings in SysLib.c)
How do I turn memory caching off?
|
What do you mean with "turning caching off"?
If you just need to disable caching for specific memory blocks you allocate then you can use the PAGE_NOCACHE flag of VirtualAlloc (or implement a custom heap on top of pages allocates in this way if you need small blocks).
If you need to disable cache for the whole system ... |
```
typedef struct A
{
short B;
short C;
} New_Type;
struct Move_Information
{
New_Type Position [25];
};
```
I am a newbie in C, and I don't really understand the meaning of "array in struct".
Could any wizard explain how to use it ? Thanks.
|
Suppose you had a plain old c type in a struct:
```
struct Other_Information
{
int x[25];
};
```
You could then make one of these structs and access the data member as follows:
```
Other_Information info;
info.x[0] = 42;//set the first item
```
Similarly, for Move_Information you can index into the array, then... |
When defining a function like this:
```
void myFunction(arguments){
// some instructions
}
```
what is the deference between usingchar[] nameandchar name[]as the function's argument. And why not use a pointer to char instead.
|
The 1stone (char[] name) won't compile as it's the wrong syntax.
Array subcripts in definitions for the parameters of a function's implementation go to the name of (mandatory) parameter.
The correct syntax is the 2nd:
```
char name[]
```
Example:
```
void p(char[]); /* prototype */
void p(char name[]) /* impleme... |
Can you openAF_INETsocket when only IPv6 addresses are available on system?
I'm trying to get the HWADDR for one system that may have only IPv6 addresses active (not dual stack).
Will I be able to open a socket usingAF_INET? I'm only interested in finding the MAC address
|
I fail to see the problem. You can callSIOCGIFHWADDRon both IPv4 and IPv6 sockets.
No matter if I useAF_INETorAF_INET6to create the socket, theioctl()call succeeds and gives me the HW addr of the device I ask for.
|
I have defined a function which has a pointer to char as its argument. When passing a constant string to this function's pointer, does the string reserves a dedicated space in memory or can any other object override it without using a pointer to access this specified space?
Defining my function
```
void myFunction(c... |
Really you should writevoid myFunction(const char *p){becuase, whatever you do,don't attempt to modify the string pointed at by p. To do so isundefined behaviour.
This is because the string"Some Text"will be copied into read-only memory on program compilation and the pointer to that will be passed top.
|
In a class project my teacher told us to make some code evaluations (C language) and to do so we need to disable the disk caching during the tests.
Currently I'm using Ubuntu 12.04, how can I do this?
Thanks.
|
You need root access to do this. You can runhdparm -W 0 /dev/sdacommand to disable write caching, where you have to replace/dev/sdawith device for your drive:
```
#include <stdlib.h>
...
system("hdparm -W 0 /dev/sda1");
```
You can also selectively disable write caching to individual partitions like this:hdparm -W 0... |
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed9 years ago.Improve this question
I am studying c language and in that there is exit handler. I am not getting exact... |
You should write one yourself and experiment with it. Your starting point will be something like:
```
void myExitFunction(void)
{
...
}
int main()
{
atexit(myExitFunction);
}
```
|
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 ... |
That's a definition of a macro, not a global variable. Try this:
```
int i;
int main()
{
i = 10;
return 0;
}
```
|
recv (sh , buff , 5000, 0 ).
Let assume, that my buff is mallocated for x bytes. How can I write the received bytes always from the beginning? I mean I wish to start with*buffand not withbuff+x.
|
recvstarts always writing the received data to the address given (*buff).
To make your code robust you should read in a loop until all data has arrived (this implies that subsequent calls should write tobuff+received bytes.
See alsoHandling partial return from recv() TCP in C
|
I know that bothraise(SIGABRT)andabort()methods will send a SIGABRT signal to itself. But there are some difference between those 2 functions. (e.g -abort()function unblocks the SIGABRT signal where asraise(SIGABRT)does not.)
What are the other differences betweenraise(SIGABRT)andabort()methods
|
The main difference it thatabort()even ends the process ifSIGABRTis ignored.
Verbatim fromman abort:
If theSIGABRTsignal is ignored, or caught by a handler that returns, theabort()function will still terminate the process. It does this by restoring the default disposition forSIGABRTand then raising the signal for ... |
Current Implementation of my process,
If there is a logic error in the process, it will dumb the core and quit by deliberately accessing invalid memory area. (sending SIGSEGV signal)
```
char* pzCoreMsg = "Logic Error";
char* zTmp = NULL;
strcpy(zTmp, pzCoreMsg);
```
Other Possible Implementations
1) Callingrais... |
Instead of relying on undefined behavior, just callabort(). It will raise SIGABRT and dump core by default.abort()will also unblock SIGABRT, and if the signal is ignored (or if the signal handler returns), it will restore the default disposition and raise it again. There's really no need to do anything further.
|
I have a function like :
```
char * s;
{
char * i = s, * t;
for(t = s;*t != NULL;t++)
if (*t == '/') i = t+1;
return i;
}
```
The warning I get is comparison between pointer and integer. How can U resolve it?
|
Stop treatingNULLas a character, it's supposed to be a pointer-type constant.
Your loop header should be:
```
for(t = s; *t != '\0'; ++t)
```
This is the "overly explicit" way of writing it, some C programmers aiming for maximum terseness will just say:
```
for(t = s; *t; ++t)
```
Since a comparison to'\0'is the ... |
I'm trying to print out a memory address backwards like in a little endian machine, but for some reason my program is outputting both char arrays in my program.
```
char address[8];
char result[16];
scanf("%s", address);
int x = 1;
for(x; x<5; x++)
{
int y = 4*x;
int z = 8 - 2*x;
result[y-4] = '\\';
result[y-3] = 'x'... |
You forget to terminate the string. In fact, your array is to small for the terminator, you need it to be 17 characters, then doresult[16] = '\0';.
Oh, and you have an out-of-bound error in your code as well, as if you enter 8 characters for the input thenscanfwill write 9 characters to the 8-character array.
|
I am having trouble dynamically declaring a 2D array (one dimension of known size, the other not known until a file is read and the number of lines stored in the integer ·lines·).
```
int NColDataType = 16;
char *DataType[NColDataType];
DataType = (char *)malloc(sizeof(char)*lines);
```
When this is compiled, I rece... |
The variableDataTypeis an array of pointer, and you try to assign a pointer to it. I think you mean to do e.g.
```
DataType[0] = malloc(lines);
```
Ordo you wantDataTypeto be a pointer to an array, like
```
char (*DataType)[NColDataType];
DataType = malloc(sizeof(DataType[0]) * lines);
```
|
In pg 44, C programming language by K&R, at the bottom it said:
For example, suppose that int is 16 bits and long is 32 bits. Then -1L < 1U, because 1U, which is an int, is promoted to a signed long. But -1L > 1UL, because -1L is promoted to unsigned long and thus appears to be a large positive number.
I really don'... |
In C, the same basic bits0xffffhas two different values.
If you treat the 16-bit number as "signed" then0xffffis -1, if it is "unsigned" then0xffffis 65535.
When you compare a signed value with an unsigned value, the bits in the signed value get treated as "unsigned" and if the value was negative, the new value is p... |
I have aserver.cI can connect to it if I know the port that I assign to the server; lets say 6000. I go to FireFox and type127.0.0.1:6000and I can connect perfectly.
How do I build my server that a client will type 127.0.0.1 on a browser and then the server will assign the port or notify the user on the browser to ty... |
You need a port to connect. HTTP connects to port 80 by default and that's why you can get away by typing 127.0.0.1 into your browser.
|
Which file configures caching on Windows Embedded Compact 7.0?
(For example, on VxWorks I can modify OS caching settings in SysLib.c)
How do I turn memory caching off?
|
What do you mean with "turning caching off"?
If you just need to disable caching for specific memory blocks you allocate then you can use the PAGE_NOCACHE flag of VirtualAlloc (or implement a custom heap on top of pages allocates in this way if you need small blocks).
If you need to disable cache for the whole system ... |
Inthis answersomebody writes
[..] most compilers won't optimize a + b + c + d to (a + b) + (c + d) (this is an optimization since the second expression can be pipelined better)
The original question was about how certain expressions involvingfloatvalue can or can not be re-ordered due to the imprecision of floating ... |
a+b and c+d can be calculated in parallel.
Like this:
```
x = a+b
y = c+d
return x+y // requires x and y
```
vs
```
x = a+b
y = x+c // requires x
return y+d // requires y (and thus x)
```
When calculatingyone has to wait for the result ofxto come in first, there is a data dependency between them. SeeInstruction-l... |
I'm having trouble replacing a whole word in a sentence.
For example:
Replace:
thetoahellotohihousetotree
Input:
Hello there, this is the house.
Output:
Hi there, this is a tree.
Is it possible to do it only with the<string.h>library, with no Regex etc.?
|
May be this can help youstr-replace-c
|
I have problem with understandingstrlenand/ormemcpy.
This is the snippet:
```
char * restP;
char * str;
//this returns a pointer
restP = strrstr (input_buffer, "pointer");
//this prints this pointer
printf("%p\n", restP);
str = malloc( 50000);
//this is wrong, restP is a pointer to a sring; i can print it with pr... |
Strlen counts characters until it reaches the NUL ('\0') character. Make sure your string contains this character, else strlen will count over the array bounds, case when the segmentation fault appears. C provides no checking for array bounds.
Also, check if the pointer you pass is valid (i.e. it is not null).
|
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 ... |
It stops because*sevaluates to 0.
That is, the last character copied was\0(the string terminator).
Evaluating to 0 is the way a boolean false is represented in C, so the loop exits when this happens.
|
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 ... |
char[]doesn't have to be NUL terminated. It's a convention used when you want to use char arrays as strings. You can use a char[] for your own purposes without any terminator.
|
This program complies fine but on running it stops in terminal and doest show any output i have to stop it manually by pressing "control + z".
I am expecting it to output size of string "hello , world"
```
include <stdio.h>
int strlenx(char *s);
int main(int argc, char *argv[])
{
printf("\n");
int a[10];
int ... |
In your strlenx function, you are never incrementing your pointers. Your for loop should be:
```
for(n =0; *s != '\0'; s++)
n++;
```
|
It seems the Linux high resolution timer starts counting within the scope of each thread - not globally in the application.
I tried using CLOCK_PROCESS_CPUTIME_ID but it gives me that thread behavior?
CLOCK_PROCESS_CPUTIME_ID (since Linux 2.6.12)
High-resolution per-process timer from the CPU.
CLOCK_TH... |
Please try withgetTimeofdaywhich should give time in the resolution ofmicroseconds(Reference:Linux Man Page)
You may also want to refer to this question:How to create a high resolution timer in Linux to measure program performance?
|
I have done a simpleCprogram that copies files fromftpusingcurllibrary.
I have done it onUbuntulinux machine and now I would like to distribute it toDebianandUbuntuPC's. I'm planning to copy output file to these machines. What other files need to be coppied to these PC'? Do I need to install curl using commandapt-get... |
If you are distributing your software as binary files, you do NOT need to require the-devpackages. Only the libraries in binary form are needed.
What does contain a-devpackage are header files needed by the compiler to build the object files and no more. Once you have a binary form for your executable, only the binar... |
I have the following code:
```
int main(void)
{
double r;
scanf("lf",&r);
printf("%lf\n",r);
}
```
Any value I enter returns a nonsense-number with about 40-50 digits. scanf works fine with chars, integers, strings etc., but with doubles I get this problem.
Can anybody help me?
|
You're missing the percent (%) symbol in the format string, it should be:
```
scanf("%lf", &r);
```
and then you should addchecking the return valuesince, as you just learned, I/O is brittle and can fail. Thus, it's wrong to depend onrcontaining a valid value unless you've verified that the scanning worked:
```
if(... |
My embedded system has one background program which generates some output message to console.
When it's not finished, the login program starts and prompt login string to same console as well.
My question is, when the login prompt string comes out, the output message generated by the background program is not aligned... |
Configure your terminal program to autolinefeed, so that it generates the\rinternally whenever it receives a\n.
|
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 ... |
It stops because*sevaluates to 0.
That is, the last character copied was\0(the string terminator).
Evaluating to 0 is the way a boolean false is represented in C, so the loop exits when this happens.
|
This question already has answers here:Why are C character literals ints instead of chars?(11 answers)Closed9 years ago.
```
void main()
{
printf("%d\n",sizeof('1'));
}
```
Output : 4
```
void main()
{
char a='1';
printf("%d\n",sizeof(a));
}
```
Output : 1
Can somebody say why it is different ?
|
In C, character literals are of typeint.
Note that this was changed in C++, in which character literals have the obvious typechar.
|
I wrote this simple code that given an input of 5 ints says if them are even or odd(I must use two arrays). But no matter what numbers I write, the output is always "5 odd.". Where am I wrong?
```
#include <stdio.h>
int main(){
int numbers[5];
int even_odd[5];
printf("%s\n", "Insert 5 numbers.");
int i;
for(i=0; ... |
for(i=0; i<=4; i++);{
theres a semicolon which shouldnt be there
for(i=0; i<=4; i++){
this way
|
The correct usage is:
```
COLORREF COLOR = RGB (255,255,255);
```
However, This
```
COLORREF COLOR = (255,255,255);
```
can be compiled without any warnings or errors.
Why? So strange? Thanks.
Reference:
COLORREFRGB()
|
The typeCOLORREFis a typedef for aDWORD. The line
```
COLORREF COLOR = (255,255,255);
```
is equivalent to
```
DWORD COLOR = 255;
```
and therefore compiles fine. It may not do what you want however.
The reason is thatexpr1, expr2yields the value ofexpr2in C, so255, 255, 255has a value of255. The brackets have no... |
When i am trying to compile (cabal install as well) in haskell i am getting this warning
```
/var/folders/hc/mp6156cx05v9l1x78qf4b_gh0000gn/T/11272.c:1:12:
warning: control reaches end of non-void function [-Wreturn-type]
int foo() {}
^
1 warning generated.
```
Every time i recompile the number (11272) i... |
Reinstalling haskell-platform solve the problem.
```
brew rm ghc
brew unlink haskell-platform
brew install haskell-platform
```
|
Is there a way find the size of the sparse files in the filesystem ext2?
|
Get thestat()of the file. The fieldst_sizegives the regular size in bytes, including holes. The fieldst_blocksshows the actually allocated blocks (in units of 512 byte blocks), sost_blocks * 512is the number of bytes it actually takes up on disk.
This works on any filesystem, not just ext2.
|
i have this for loop
for (i = 0, j = N-1; i < j; ++i , --j )
and i want to increment i with 4 not 1 and j decrement with 4 not 1.
Something like this, but i don't know the sintax:
```
for (i = 0, j = N-1; i < j; 4+=i , 4-=j )
```
Thanks
|
Try the other way around:i += 4. This is shorthand fori = i + 4. Now you have written4 += iwhich means4 = 4 + i- which does not make sense of course.
|
Is there a way to overload the comparators in C so that we can compare structs using>,=, and<
For example:
```
struct point {
int x, y;
}
struct point pt1 = make_point(2, 4);
struct point pt2 = make_point(2, 3);
```
we could have it compare on theyvalue (or some arbitrary member of the struct).
```
if (pt1 > ... |
No, you cannot overload operators in C. You cannot even overload ordinaryfunctionsin C.
|
IfTis a scalar type, andN = CHAR_BIT * sizeof(T), isuintN_tguaranteed to exist? If no, is it true in most cases, but with a few exceptional case types? (long double, and member function pointers come to mind. )
For reference:
intN_t,uintN_tN1548 §7.20.1.1 ¶3: "These types are optional. However, if an implementatio... |
The typesuintX_tare optional, so there is no guarantee that there will be any at all in your implementation.Other than that, there is no precise definition of whatscalarmeans to you.
|
a stupid question, but cant make it work
```
printf("Enter the string!\n");
char str[5],ch;
gets(str);
printf("%s\n" , str);
int i, c;
//int n = strlen(str);
for (i = 0; i <= strlen(str)-1; i++)
{
ch = str[(strlen(str)-1)-i];
printf("%c", ch);
}
```
this code should works but
I get an error "Stack around v... |
getsNULL-terminates the string, it stores. This is - adds one more char\0at the end of the string. So, this means thatstrmust be at least6, as you enter5char string.
For example,"01234"is 6 bytes:'0','1','2','3','4',\0.
|
```
#include <stdio.h>
int main(){
int valid = 0;
int length = 0;
int i = 0;
char custID[21];
do{
puts("\nPlease enter a customer ID:");
scanf("%s", custID);
length = strlen(custID);
if(length < 21){
for(i=0;i<=length;i++)
valid=1;
}
else{
valid = 0;
printf("\nN... |
Use this scanf format:
```
scanf("%[0123456789]", custID);
```
Using this the scanf accept only numbers in your entered string
Example:
If your entered "Str78in69g", custID variable will contain only 7869
|
In Linux both a binary executable file and a script can be marked "executable". I would like to determine in my gcc program whether the file is a script or a binary executable.
I read that there is an a.out.h file which allows to analyse the header of the file but I do not know how to use this in my code. Or if there... |
You can check so-called magic bytes. For elf 1st four bytes are supposed to be7f 45 4c 46in hex. You have to care for byte order though.
Opening file in binary mode and reading 1st four bytes should suffice.
E.g.
```
shell$ hexdump -n 10 ./ni6_ga
0000000 457f 464c 0101 0301 0000
```
|
Does anyone know of a way I can change the values of variables that are defined locally?
```
#include <stdio.h>
int change(int x, int y);
int main()
{
int x = 10;
int y = 20;
change(x,y);
printf("x:%d y:%d\n", x, y);
}
int change(int x, int y)
{
x = 20;
y = 30;
return(x);
return(y... |
Use pointers:
```
void change(int *x, int *y)
{
*x = 20;
*y = 30;
}
```
and call the function like:change(&x, &y);For readability you may want to use different names thanxandyfor thechangeparameters as they are not of the same type as thexandyvariables declared inmain.
|
I've been trying to convert an array[R,G,B,..]in Mat object with opencv. But is returning wrong data, someone knows why?
```
double data[12] = {0,0,255,0,0,255,0,0,255,0,0,255};
Mat src = Mat(2,2, CV_16UC3, data);
```
and returns:
```
M =
[0, 0, 0, 0, 0, 0;
0, 0, 0, 0, 57344, 16495]
```
EDIT:
Solved! use uch... |
i think, you wanted:
```
uchar data[12] = {0,0,255,0,0,255,0,0,255,0,0,255};
Mat src = Mat(2,2, CV_8UC3, data);
```
(all red, 2x2 rbg image)
|
So I have a structure, and one of its members is a string.
```
struct Output {
char *axis;
int value;
};
struct Output Jsoutput;
```
My question is, how do I store a string in axis?
```
char whichaxis[4][3] = {"LX","LY","RY","RX"};
// Store which axis and value of the joystick position in Jsoutput
Jsoutp... |
Just use strdup
```
Jsoutput.axis = strdup(whichaxis[jse.number]);
```
|
This question already has answers here:What does it mean when a numeric constant in C/C++ is prefixed with a 0?(7 answers)Closed7 years ago.
I am unable to understand output of below mentioned program-
```
#include <stdio.h>
int main()
{
int i, a[8]={000, 001, 010, 011, 100, 101, 110, 111};
for(i=0;i<8;i++)
{
... |
Any integer literal that starts with a0followed by other digits is octal, just like any integer literal starting with0xor0X, followed by digits, is hexadecimal. C++14 will add0bor0Bas a prefix for binary integer literals.
See more oninteger literals in C++ here.
|
This question already has answers here:Why are C character literals ints instead of chars?(11 answers)Closed9 years ago.
```
void main()
{
printf("%d\n",sizeof('1'));
}
```
Output : 4
```
void main()
{
char a='1';
printf("%d\n",sizeof(a));
}
```
Output : 1
Can somebody say why it is different ?
|
In C, character literals are of typeint.
Note that this was changed in C++, in which character literals have the obvious typechar.
|
I wrote this simple code that given an input of 5 ints says if them are even or odd(I must use two arrays). But no matter what numbers I write, the output is always "5 odd.". Where am I wrong?
```
#include <stdio.h>
int main(){
int numbers[5];
int even_odd[5];
printf("%s\n", "Insert 5 numbers.");
int i;
for(i=0; ... |
for(i=0; i<=4; i++);{
theres a semicolon which shouldnt be there
for(i=0; i<=4; i++){
this way
|
The correct usage is:
```
COLORREF COLOR = RGB (255,255,255);
```
However, This
```
COLORREF COLOR = (255,255,255);
```
can be compiled without any warnings or errors.
Why? So strange? Thanks.
Reference:
COLORREFRGB()
|
The typeCOLORREFis a typedef for aDWORD. The line
```
COLORREF COLOR = (255,255,255);
```
is equivalent to
```
DWORD COLOR = 255;
```
and therefore compiles fine. It may not do what you want however.
The reason is thatexpr1, expr2yields the value ofexpr2in C, so255, 255, 255has a value of255. The brackets have no... |
When i am trying to compile (cabal install as well) in haskell i am getting this warning
```
/var/folders/hc/mp6156cx05v9l1x78qf4b_gh0000gn/T/11272.c:1:12:
warning: control reaches end of non-void function [-Wreturn-type]
int foo() {}
^
1 warning generated.
```
Every time i recompile the number (11272) i... |
Reinstalling haskell-platform solve the problem.
```
brew rm ghc
brew unlink haskell-platform
brew install haskell-platform
```
|
Is there a way find the size of the sparse files in the filesystem ext2?
|
Get thestat()of the file. The fieldst_sizegives the regular size in bytes, including holes. The fieldst_blocksshows the actually allocated blocks (in units of 512 byte blocks), sost_blocks * 512is the number of bytes it actually takes up on disk.
This works on any filesystem, not just ext2.
|
i have this for loop
for (i = 0, j = N-1; i < j; ++i , --j )
and i want to increment i with 4 not 1 and j decrement with 4 not 1.
Something like this, but i don't know the sintax:
```
for (i = 0, j = N-1; i < j; 4+=i , 4-=j )
```
Thanks
|
Try the other way around:i += 4. This is shorthand fori = i + 4. Now you have written4 += iwhich means4 = 4 + i- which does not make sense of course.
|
I've known that
```
for (...; ...; ...)
printf ("Fulfill the limits.");
```
and
```
if (...)
printf ("Fulfill the limits.");
```
are C standard.
But
```
for (...; ...; ...)
if (...)
for (...; ...; ...)
if (...)
for (...; ...; ...)
printf ("Fulfill al... |
It is perfectly valid syntax. The syntax is not complicated, simply nested likex1 + (x2 + (x3 + ..).
That is,if/forisa statement andif/forcontainsa statement. This can be seen in therecursiveBNF grammar rules:
```
statement:
"if" "(" expression ")" statement |
"for" "(" expression? ";" expression? ";" expressi... |
When compiling like this:
```
void DisplayPos (void)
{
SetWindowPos (ConsoleWindow, HWND_TOPMOST, 0, 0, 600, 600, SWP_SHOWWINDOW);
}
int main (void)
{
HWND ConsoleWindow = GetConsoleWindow();
DisplayPos ();
}
```
GCC will report:
```
Line 3 | error: 'ConsoleWindow' undeclared (first use in this functio... |
Appreciate @cHao 's help. :-)
I answered my own question.
```
void DisplayPos (HWND ConsoleWindow)
{
SetWindowPos (ConsoleWindow, HWND_TOPMOST, 0, 0, 600, 600, SWP_SHOWWINDOW);
}
int main (void)
{
HWND ConsoleWindow = GetConsoleWindow();
DisplayPos (ConsoleWindow);
}
```
|
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... |
You can see some specific examples about how this is solved:
example1.example2.example3.
There are few more examples if you look in Google.
|
I'm using a switch statement that basically looks like this:
```
switch (command):
case '+':
int key;
scanf("%i", &key);
//do stuff
break;
case '-':
int key;
scanf("%i", &key);
//do stuff
break;
....
```
It appears I'm not allowed to redeclareint keyalong the case ladder, even though they br... |
It's not legal, and consequently it's not safe. But it's easy to fix. Just use blocks in your switch statement to limit the scope of your declarations:
```
switch (command):
case '+': {
int key;
scanf("%i", &key);
//do stuff
break;
}
case '-': {
int key;
scanf("%i", &key);
//do stuff
break;
}... |
I need to read binary data to buffer, but in the fstreams I have read function reading data intocharbuffer, so my question is:
How to transport/cast binary data intounsigned charbuffer and is it best solution in this case?
Example
```
char data[54];
unsigned char uData[54];
fstream file(someFilename,ios::in | i... |
Just read it into unsigned char data in the first place
```
unsigned char uData[54];
fstream file(someFilename,ios::in | ios::binary);
file.read((char*)uData, 54);
```
The cast is necessary but harmless.
|
```
if(serverSocket=socket(AF_UNIX,SOCK_STREAM,0) < 0) {
perror("Falhou a Ligacao ao socket");
exit(1);
}
bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sun_family = AF_UNIX;
strcpy(serv_addr.sun_path, UNIXSTR_PATH);
servlen = strlen(serv_addr.sun_path) + sizeof(serv_addr.sun_family);
if (bind(serv... |
This line is wrong. This will not assign serverSocket the return value.
```
if(serverSocket=socket(AF_UNIX,SOCK_STREAM,0) < 0)
```
Just change the parenthesis to
```
if ((serverSocket = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
{
perror("Falhou a Ligacao ao socket");
exit(1);
}
```
|
I'm trying something very simple; comparing a user inputted string to "hello" but strcmp does not want to work. I know I'm missing something obvious and I think it has to do with the way I declared my string. All help is greatly appreciated.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (vo... |
fgetswill leave the newline in the buffer and then null terminate while command will have no newline and just be null terminated.
|
I have following code in packet sniffer:
```
struct ip_header {
unsigned char ip_ver:4;
...
};
...
printf("Version: %i\n", (int)ip_hdr->ip_ver)
```
The output of ths is "Version: 5". I think version can onl be 4 or 6, right?
|
I got it it is just the Header length first 4 bits and version is second 4bits, so it should be
```
struct ip_header {
unsigned char ip_hl:4;
unsigned char ip_ver:4;
...
};
```
|
I am a newbie in C progrmming and I have looked at the following code:
```
struct iphdr *iph = (struct iphdr *)Buffer;
```
What does the expression mean?
here is the link to the codehttp://www.binarytides.com/packet-sniffer-code-c-linux/
|
It castsbufferto a pointer tostruct iphdrand then initializesiphto that pointer. This is used becausebufferis a pointer to a buffer of raw bytes, but in this function it is known that the bytes stored in the buffer follow the format of astruct iphdr. Hence thestruct iphdrcan be used to access the contents of the buffe... |
I'm new to c.
Is there any simple way to redirect all the console's output (printfs etc.) to a file using some general command line \ linkage parameter (without having to modify any of the original code)?
If so what is the procedure?
|
Use shell output redirection
your-command > outputfile.txt
The standard error will still be output to the console. If you don't want that, use:
your-command > outputfile.txt 2>&1
or
your-command &> outputfile.txt
You should also look into theteeutility, which can make it redirect to two places at once.
|
This function which I received from a third party contains the following code which does not compile in MS Visual Studio 10. I think there is a casting problem but do not know how to fix this.
```
void dump_ffmpeg_pad16(FILE *stream, uint32_t timestamp, void *data,
int data_size)
{
unsigned int... |
```
void *end = data + data_size;
```
Should be:
```
void *end = ((char *) data) + data_size;
```
Adding to avoid*is a GCC extension.
|
This is my code:
```
struct bacchetta {
bool in_uso;
};
int main()
{
key_t key;
if ((key = ftok(".", 'a')) == -1) {
perror("ftok");
exit(1);
}
int shmid;
if ((shmid = semget(key, sizeof(struct bacchetta)*5, 0600 | IPC_CREAT )) == -1) {
perror("Errore creazione dell'area di memoria per le ba... |
You need to callshmget, notsemget.
|
I have downloadedopenssh-6.4p1for Linux and I want to compile it usingclanginstead ofgcc. How can I tell the compilation engine to do this? Do I need to modifyconfigure?
|
You can try to use the option command like this:
```
option(USE_CLANG "build application with clang" ON) # OFF is the default
```
and then you can wrap the clang-compiler settings in the if() condition like this:
```
if(USE_CLANG)
SET (...)
//...
endif(USE_CLANG)
```
|
The header file is in the same folder as the other files, it's #include'ed and all, but some reason the other source files just can't find it. Same with compiler. Help?
|
May be you should try#include "funcs.h"instead of#include <funcs.h>
|
Iss1=s2valid statement? It give me error:
lvalue required
My code:
```
#include<stdio.h>
#include<conio.h>
void main()
{
char s[1]="integ";
char s[2]="systems";
s1=s2;
printf("%s", s1);
getch();
}
```
|
You haven't defined a variable calleds2. You have two variables,s1, ands. Also, you can't assign character arrays like that. Declare them as pointers if you need to change the array the variable points to after initialization, or else usestrcpy()to copy one string's contents into another (being careful about overflow ... |
This question already has answers here:Strange behaviour of macros C/C++(5 answers)Closed9 years ago.
Why do I get 27? Can't#definetake executable statement 5+2?
```
#include<stdio.h>
#include<conio.h>
#define x 5+2
void main()
{
int i;
i=x*x*x;
printf("%d",i):
getch();
}
```
Output:
27
I should g... |
First, this isnotan executable statement, it is anexpression. An no, it shouldn't be 343, because the expression is not parenthesized. Because of that, multiplication takes precedence over addition, so the expression being evaluated is
```
5+2*5+2*5+2
```
which is
```
5+(2*5)+(2*5)+2 = 27
```
This little example i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.