question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
```
int bar[10]; /* bar is array 10 of int, which means bar is a pointer to array 10 of int */
int (*bar)[10]; /* bar is a pointer to array 10 of int */
```
According to me they both are same, am I wrong? Please tell me.
Edit: int *bar[10] is completely different.
Thanks
Raja
|
They are completely different. The first one is an array. The second one is a pointer to an array.
The comment you have after the firstbardeclaration is absolutely incorrect. The firstbaris an array of 10ints. Period. It is not a pointer (i.e. your "which means" part makes no sense at all).
It can be expressed this ... |
I have a number of.cand.hfiles with some parts of the code disabled by putting the code block in pre-processor directives e.g.
```
#ifdef FOOBAR
// some code that can be compiled if needed by defining FOOBAR in pre-processor.
#endif
```
No I need to defineFOOBARsuch that its defined for every file that is compiled b... |
Add the compiler option-DFOOBARto the make variableCFLAGS
|
When I compile this little program instead of displaying "num1:7,num2: 2",
it displays "num1:-1218690218,num2:-1217453276". I think I'm not specifying what the program should display so its just giving me the int range instead.
I'm sorry.
```
#include <stdio.h>
main() {
int num1 = 7, num2 = 2;
... |
You've put the closing parenthesisbeforenum1andnum2, so they're not being passed toprintf. You need to change this:
```
printf("num1:%d , num2:%d\n"), num1, num2;
```
to this:
```
printf("num1:%d , num2:%d\n", num1, num2);
```
Yes, the parenthesis is the only change, but it's crucial.
|
I want tosend(socketfd, ...)and I'm using theselect()function. Should this file descriptor be in thewritefds, or in thereadfds?
|
readfdsare for sockets you want to read from,writefdsfor those you want to write to. Sowritefdsin your case.
|
I am using C and writing a client-server program, and I would like to get an unused port number to run my server process. My server code is like this:
```
getaddrinfo()
socket()
bind()
listen
while(1)
accept()
```
I need to provide the unused port addr to the bind() call. But I do not want to pass the port number ... |
Just bind() your socket setting sin_port to 0 in sockaddr_in. System will automatically select unused port. You can retrieve it by calling getsockname().
But I don't have any idea how to pass it to client, except printing it and using as command-line parameter for client program.
|
I have a following array and a printf() stament,
```
char array[1024] = "My Message: 0x7ffff6be9600";
printf("%.14s", strstr(array, " 0x") + 1);
```
The output of above printf() is 0x7ffff6be9600,
can we store it into a unsigned long variable?
|
Look atsscanf
|
I'm using PC Lint for the first time. I was "linting" my code, when PC Lint warns me about mywhile(TRUE).
This is what it says:
716: while(1) ... -- A construct of the form while(1) ... was found.Whereas this represents a constant in a context expecting a Boolean,
it may reflect a programming policy whereby infin... |
The text says that althoughwhile(TRUE)(which gets preprocessed intowhile(1)) is a perfectly valid infinite loop, the more conventional form of writing an infinite loop is
```
for(;;)
{
...
}
```
because it doesn't use any values at all and therefore is less error-prone.
|
I've split some code into two files, it was working before. In one file I have a function which has an out value parameter which is a pointer to a pointer.
I'm filling this parameter with a call to a getter and dereferencing it:
```
foo(&bar());
```
however I get an error saying ''&' requires an l-value'. I underst... |
Well, you need an lvalue, i.e. something that can be assigned to. You can't assign to the return value of a function.
You need to do something like this:
```
temp = bar();
foo(&temp);
```
|
MSDN says that afterCryptVerifySignature()you cannot reuseHCRYPTHASHobject to try hashing more data, instead it says you need to recreate it withCryptDestroyHash()andCryptCreateHash().Reusing really fails.
Anyone is familiar with a hack that can save these calls, or it is really impossible?
|
I imagine theHCRYPTHASHdata structure is more flexible than just being used to call withCryptVerifySignature(). It's designed to operate on a (possibly discontinuous) stream of data (viaCryptHashData()), which means it stores some state within it on the hash's current values. Therefore, once you've used it on a stre... |
I want to keep some applications to run with a 4 GB address space within a 64 bit OS running on a 64 bit processor (x86 xeon, 8 core). I know there is an option to compile with -m32 option, but at this moment the computer I'm working with, doesn't have the required support for compiling with -m32, so I can't use it, n... |
The ulimit/setrlimit mechanism, accessible in bash via ulimit, can do this with minor drawbacks.
```
ulimit -v 4000000
```
should limit the memory available to the current process group to 4 GB.
However, it limits the totalsizeof your address space mappings, and does not limit your mappings' offset
- you still may ... |
see i have written one program for big endian now i dont have big endian machine but i want to check whether my program will works correctly or not on big endian so how can i check that on my little endian pc.?
Is there any online virtual big-endian compiler ?
note : i have googled about this but did not get anythin... |
qemucan virtualize all sorts of architectures, amongst then big endian ones.
|
Is there a LPTSTR equivalent of _strnicmp which takes in 2 LPTSTR strings, and number of TCHARs to compare until?
using the c winapi btw
|
It is_tcsncicmp, seethe documentation.
|
The same code ran in TURBO C.
```
struct details
{
char name[20];
int year;
float price;
}my_str;
details book1[10];
```
This error is produced. How can this be fixed?
```
ram.c: In function ‘main’:
ram.c:11:1: error: ‘details’ undeclared (first use in this function)
ram.c:11:1: note:... |
There are two ways to fix this:
Change second line to this:
```
struct details book1[10];
```
Or you can change the declaration to:
```
typedef struct{
char name[20];
int year;
float price;
} details;
```
C is slightly different from C++, so you can't declare structs quite the same way.
|
suppose I have a string "2011-08-21 21:48:45 +1200",and another one with the same format,I want to compare these 2 strings to find out which one is the early one or later one,is there a easy way to convert a string to time format rather than compare them by characters?
Thanks
|
usegetdateorstrptime().
|
Suppose i have a stringconst char *temp = "i am new to C".
Now i have a float variablea=1.0000;
How can i send the value of "a" insideconst char *tempalong with the existing string.
Thanks in advance.
|
```
const char temp[] = "I am new to C";
float a = 1.0;
char buffer[256];
sprintf(buffer, "%s %f", temp, a);
```
|
I am really frustrated about strncpy function. I did something like this:
```
char *md5S; //which has been assign with values, its length is 44
char final[32];
strncpy(final,md5S,32);
```
but somehow the length ofchar final[]became more than 32 after.What should I do here?
|
You forgot to leave room for the null character
```
char final[33];
strncpy(final,md5S,32);
final[32] = '\0';
```
|
Right now I am able to retrieve the network status using the following code..
```
popen("netstat -i | grep '^e[a-z][a-z]*0[ \t]' | head -n1","r")
sscanf(line,"%32s %d %*s %*s %d %d %d %d",
name, &mtu,
&in_packets, &in_errors,
&out_packets, &out_errors);
```
I want to ca... |
How to calculate packets/second
Get the number of packets right now.Waitnseconds.Get the new number of packets.
Now subtract the first number from the second number and divide bynand you have your packets/second over a given interval.
|
I've been reading through the original ping program code (http://www.ping127001.com/pingpage/ping.text) out of interest, just to see how it was done.
I get most of it, but there is one conditional that I don't understand:
```
if (datalen >= sizeof(struct timeval)) /* can we time 'em? */
timing = 1;
```
Whereda... |
That's because you need to ensure the packets are big enough to store timing data if you want to actually store timing data in them. In other words, timing works by placing atimevalstructureintothe payload area.
If, for example, you specified a length of 3 for the ICMP payload area when the size of thetimevalstructur... |
As in title. I tried reading the BFD's ELF's code, but it's rather not a light reading. I also tried to get something from the documentation, but I would need an example to see how it works. Could anyone point me some easier example for me, to know how to define an executable format?
Edit: Looks like I didn't formula... |
You did look herehttp://sourceware.org/binutils/docs-2.21/bfd/index.htmland herehttp://sourceware.org/binutils/binutils-porting-guide.txt?
Also studying the MMO implementation of a BFD backend as mentioned herehttp://sourceware.org/binutils/docs-2.21/bfd/mmo.html#mmo(source:http://sourceware.org/cgi-bin/cvsweb.cgi/sr... |
I have a function that creates a binary sha1, but I need a result as a 40-byte string, (+1 for null-t).
Is there a better way of converting it to string, than this?
```
unsigned char hash_binary[20] = "\xFF\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01";
char hash_string[41];
int i;
for(i = 0;i < 20; i++)
sprintf( has... |
You can populate the target string directly:
```
static const char alphabet[] = "0123456789ABCDEF";
for (int i = 0; i != 20; ++i)
{
hash_string[2*i] = alphabet[hash_binary[i] / 16];
hash_string[2*i + 1] = alphabet[hash_binary[i] % 16];
}
hash_string[40] = '\0';
```
|
I am trying to learn C. The reading I've been doing explains pointers as such:
```
/* declare */
int *i;
/* assign */
i = &something;
/* or assign like this */
*i = 5;
```
Which I understand to meani= the address of the thing stored insomething
Or
Put 5, or an internal representation of 5, into the address that ... |
Well, yes, in your example setting an int pointer to 5 is a mismatch of types, but this is C, so there's nothing stopping you. This will probably cause faults. Some real hackery could be expecting some relevant data at the absolute address of 5, but you should never do that.
The English equivalents:
```
i = &somethi... |
This question might sound fool, because I know there are bunch of frameworks that does it for you. What I want is actually get in touch with low level C API deeply and able to write a program that sits on computer and intercepts packets between local machine and outer spaces. I tried to figure it out by looking at ope... |
You have to use raw socket. Here's anexample.
At least for what concern Linux and Unix like operating systems. I don't know about Windows.
|
I have been working on a college project using OpenCV. I made a simple program which detects faces, by passing frames captured by a webcam in a function which detects faces.
On detection it draws black boxes on the faces when detected. However my project does not end here, i would like to be able to clip out those fa... |
For C++ version you can checkthis tutorialfrom OpenCV documentation.
In the functiondetectAndDisplayyou can see the line
```
Mat faceROI = frame_gray( faces[i] );
```
wherefaceROIis clipped face and you can save it to file withimwritefunction:
```
imwrite("face.jpg", faceROI);
```
|
Is there a common way or good public domain code for converting binary (i.e. byte array or memory block) to hexadecimal string? I have a several applications that handle encryption keys and checksums and I need to use this function a lot. I written my own "quick and dirty" solution for this but it only works with bina... |
Something like this?
```
void print_hex(const char * buffer, size_t size)
{
for (size_t i = 0; i < size; i++)
printf("%02x", buffer[i]);
}
```
|
I have some legacy code that needs certain gcc flags passed in. Can I add pre-processor checks for these flags?
For example, let's say I need-fno-strict-aliasing, can I do something like this:
```
#ifndef _FNO_STRICT_ALIASING
#error -fno-strict-aliasing is required!
#endif
```
|
You can use
```
#pragma GCC optimize "no-strict-aliasing"
```
to compile the file with that flag (overriding what was specified on the command line).
You can also use
```
__attribute__((optimize("no-strict-aliasing")))
```
to apply the flag to a single function within a source file...
|
I almost finishing a clean NSLog with this code:
```
#define NSLog(FORMAT, ...) printf("%s\n", [[NSString stringWithFormat:FORMAT, __VA_ARGS__] UTF8String]);
```
This work fine if I do this:
```
NSLog(@"Show %@ message", @"this");
```
But, will fail if I user it
```
NSLog(@"One argument");
```
because__VA_ARGS__... |
Use this code (notice the##part):
```
#define NSLog(FORMAT, ...) fprintf(stderr, "%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
```
|
I just executed a program that mallocs 13 MB in a 12 MB machine (QEMU Emulated!) . Not just that, i even browsed through the memory and filled junk in it...
```
void
large_mem(void)
{
#define LONGMEM 13631488
long long *ptr = (long long *)malloc(LONGMEM);
long long i;
if(!ptr) {
printf("%s(): array a... |
It's calledvirtual memorywhich is allocated for your program. It's notrealmemory which you call RAM.
There is a max limit for virtual memory as well, but it's higher than RAM. It's implemented (and defined) by your operating system.
|
I was wondering if anyone could tell me if there is a way to dynamically allocate a buffer when reading an input from stdin usingread(...)For example:
n = read(0, buffer, sizeof ?);How do I ensure that the number of bytes read fromstdin(here 0) is the same as inbuffer?
|
You can't. You do areadinto a fixed-size buffer, e.g.:
```
char buf[BUF_SIZE];
int num_read = read(0, buf, BUF_SIZE);
```
and then figure out if there's any more data available (usually by checking whethernum_readis equal toBUF_SIZE, but in some cases, maybe you need to interpret the data itself). If there is, the... |
I'm trying to convert 64bit integer string to integer, but I don't know which one to use.
|
Usestrtoullif you have it or_strtoui64()with visual studio.
```
unsigned long long strtoull(const char *restrict str,
char **restrict endptr, int base);
/* I am sure MS had a good reason not to name it "strtoull" or
* "_strtoull" at least.
*/
unsigned __int64 _strtoui64(
const char *nptr,
char **endp... |
What I've written is:
```
typedef enum _MyStatus
{
MY_STATUS_OK = 0,
MY_STATUS_GENERAL_ERROR = -1,
} MyStatus;
typedef MyStatus (*MyCallback)(MySettings *settings);
typedef struct _MySettings
{
MyCallback callback;
} MySettings
```
However, it wouldn't compile as when defining MyCallback it doesn't kn... |
How about putting this line at the top:
```
typedef struct _MySettings MySettings;
```
ThisC FAQ: How can I define a pair of mutually referential structures?might be of use.
|
I tried two ways:
```
void func(const char *path, const char *arg0, ...){
va_list args;
va_start(args, arg0);
execl(path, arg0, args, NULL);
va_end(args);
}
func("/bin/ls", "ls");
```
And:
```
void func(const char *path, const char *arg0, ...){
va_list args;
va_start(... |
Since you don't know how many arguments you'll be receiving, you'll need/want to useexecvinstead ofexecl. You'll need to walk through the arguments, retrieve a pointer to the beginning of each string, and put them into an array. You'll then pass the address of that array toexecv.
|
Problem: if you do
```
if ( ptr = memchr( str1, '4', sizeof(str1) ) )
{
// do stuff using ptr
}
```
then you'll enter and do "stuff" every time.
But if you just do
```
if ( memchr( str1, '4', sizeof(str1) ) )
{
// would do stuff but don't have ptr!
}
```
then you'll enter but you won't have the pointer to ... |
The assignment operator returns the value being assigned, which (along with right associativity) is whya=b=c;works. So your first example will work just fine.
|
I was reading the C-FAQ question no: 20.8 which basically deals with bit arrays:
http://c-faq.com/misc/bitsets.html
One of the macros defined looks something like:
```
#define BITNSLOTS(nb) ((nb + CHAR_BIT - 1) / CHAR_BIT)
```
Is this macro meant to calculate the num of elements(or slots) in the char array (each s... |
Yes, it calculates how manychars are needed to hold the bits. The addition stuff is to make it round up.
|
Hi guys I have an ANSI C university course.
I am looking for a compiler that will easily create
makefiles and .o files and binaries that would work on both windows and ubuntu.
all code i write must be multiplatform.
(Im a C#/C++ programmer, didn't touch C for over 10 years)
no need for any external library support ... |
I think gcc is your best option. On Windows the best port is probablyMinGW.
You edited your question to request an IDE too. TryCode::Blocks.
|
I havechar * source, and I want extract from it subsrting, that I know is beginning from symbols "abc", and ends where source ends. WithstrstrI can get the poiner, but not the position, and without position I don't know the length of the substring. How can I get the index of the substring in pure C?
|
Use pointer subtraction.
```
char *str = "sdfadabcGGGGGGGGG";
char *result = strstr(str, "abc");
int position = result - str;
int substringLength = strlen(str) - position;
```
|
"The wait() system call suspends execution of the current process until one of its children terminates" . Waitpid also is similar.
My Question is whether calling wait() from one thread will cause all other threads (in the same process) also to go to sleep ? Do the behavior is same for detached threads also?
|
This is just a bug in the manual.waitsuspends the calling thread, not the process. There is absolutely no way to suspend the whole process short of sending itSIGSTOPor manually suspending each thread one at a time.
|
In multicore systems, such as 2, 4, 8 cores, we typically use mutexes and semaphores to access shared memory. However, I can foresee that these methods would induce a high overhead for future systems with many cores. Are there any alternative methods that would be better for future many core systems for accessing shar... |
Transactional memoryis one such method.
|
When I use % operator on float values I get error stating that "invalid operands to binary % (have ‘float’ and ‘double’)".I want to enter the integers value only but the numbers are very large(not in the range of int type)so to avoid the inconvenience I use float.Is there any way to use % operator on such large intege... |
You can use thefmodfunction from the standard math library. Its prototype is in the standard header<math.h>.
|
After accepting data from a socket, can I view the header for the data? I want to know what IP address the packet was sent to as I am listening on multiple interfaces.
|
You can usegetsocknameto fetch the local IP address of the socket.
```
int getsockname(int socket, struct sockaddr *restrict address,
socklen_t *restrict address_len);
```
Here is an example:
```
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
memset(&addr, 0, sizeof(addr));
getsockname(s, &addr, &le... |
I have a computer on my network that had multiple IP addresses and uses multiple ports. Is there any way to open a socket that receives data on all those ip addresses and all those ports, and then have the data received contain the ip address from the packet header, and the port it received it on?
Rephrase:
How can I... |
You cannot bind to multiple ports using just one socket. The TCP/IP networking stack is based on the idea that one port == one socket.
|
I have the following code:
```
unsigned char* originaldata = (unsigned char*)malloc(50);
strcpy((char*)originalData,"12345 7");
unsigned char* replacingData = (unsigned char*)malloc(9);
strcpr((char*)replacingData,"11111111");
memset(replacingData,6,6);
```
Then, I want to replace the data from position 6 ti... |
```
memcpy(originalData+6, replacingData, strlen(originalData)-6)
```
Although, it should be noted that this makes the assumption thatoriginalDatais always greater than 6 characters long and thatreplacingDatais longer than 6 characters shorter thanoriginalData.
|
The baudrate is normally set to one of the specified values, like 9600, 56k and so on.
Is it possible to select another value, like 123456 Baud? Its an numerical parameter, so why not?
|
The clock of the communication module is usually derived from the system clock.
this system clock can be devided by specific numbers , like 2,4,8..
that's why you can reach only to specific baudrates.
Because you are talking on asynchronous protocol , clock is not transmitted on lines.
all of the above , cause the i... |
Does hitting a switch statement in C (assuming that it uses a jump table) empty the pipeline of an x86 processor? I'm thinking that it might because it would need the result of the table lookup to know what instruction to execute next. Can it forward that result back early enough that the pipeline doesn't get totally ... |
A jump table does not necessarily empty the pipeline. Indirect branches are predicted on modern processors, and the branch predictors do a better job than you might expect. Obviously, a correctly-predicted indirect branch does not cause a stall.
Not branching at all is preferable, but often impossible (or introduce... |
HI I have following three strings,
```
char* string1, string2, string3;
printf("First string = %s", string1);
printf("Second string = %s", string2);
printf("Third string = %s", string3);
```
Output of above code is,
```
First string = My Content is : %s, My value is : %d
Second string = Open source OS
Thirf string ... |
try:
```
printf(string1, string2, atoi(string3));
```
|
How to change the entry point of a C program compiled with gcc ?Just like in the following code
```
#include<stdio.h>
int entry() //entry is the entry point instead of main
{
return 0;
}
```
|
It's a linker setting:
```
-Wl,-eentry
```
the-Wl,...thing passes arguments to the linker, and the linker takes a-eargument to set the entry function
|
I need a tool which helps me to find memory leaks in a c program in a similar way valgrind does. It should figures out when a program overwrites memory it should not (e.g. by miscalculating an array index). I learned that there is the leaks utility along with the graphical instruments app.
However I think it can just... |
Valgrind 3.7.0 (released 5thNovember 2011) supports Lion.http://valgrind.org
|
I am making a C program on windows using visual studio 2010.
I am passing a wchar_t array to a function.
```
//in main
wchar_t bla[1024] = L"COM6";
mymethod(bla);
static void mymethod(wchar_t *bla) {
//do stuff
}
```
I used the debugger to watch bla, sizeof(bla) and noticed that in main, bla is of typewchar_t... |
in main you are calculating the size of the array:
```
sizeof(bla); // 1024 * sizeof(unsigned short) = 2048
```
in your function, if you use sizeof, you are calculating the size in bytes of a pointer:
```
sizeof(bla); //means sizeof (wchar_t *) = 4
```
|
By"human-readable serialisation format"I meanYAML,JSON,INIor like. Please note,XMLis too verbose and too inconvenient for my purposes, so let's leave it alone as the last resort.
The format should store the data as"named key -- value"pairs and allow for nesting and arrays. Absence of arrays is not critical, though. A... |
I foundJanssona while back and it might fit your requirements.
|
Does libjpeg allows/have routines to scale the output image?
I have an image which needs to be resized when saving to and loading from, Providing width1, height1 on input and getting width2, height2 on output, and I really cant use anything outside.
|
Yes, libjpeg does support image scaling, but with some limitations.
Libjpeg version 8c and higher supportsM/8 scalingwhere M is an integer between 1 and 16. The more commonly used libjpeg version 6b supports M of 1, 2, 4, and 8 only (i.e. power-of-2 downscaling).
Supply the scaling numerator and denominator to the d... |
looking at the linux kernel source, I found this:
```
static struct tty_operations serial_ops = {
.open = tiny_open,
.close = tiny_close,
.write = tiny_write,
.write_room = tiny_write_room,
.set_termios = tiny_set_termios,
};
```
I've never seen such a notation in C.
Why is there a dot before the variable ... |
This is aDesignated Initializer, which is syntax added for C99.
Relevant excerpt:
In a structure initializer, specify the name of a field to initialize
with ‘.fieldname =’ before the element value. For example, given the
following structure,
```
struct point { int x, y; };
```
the following initialization
```
stru... |
I'm using CreateThread() for my 4 threads.I would like to run all my threads simultaneously, but wait for all 4 to finish before continuing with the main thread.I used an int and increased it at the start of the thread, then decreased it at the end, then in my main thread I used a while loop to hold while the number i... |
UseWaitForMultipleObjectswith thebWaitAllflag set, on all of your thread handles. The function will return once all threads exit.
|
Part of my application (preferably a daemon) required to log the list of process names that have got core dumped. It would be great, if someone points which mechanism that I can use?
|
If the processes are truly dumping core, you could use the following trick:
Set/proc/sys/kernel/core_patternto|/absolute/path/to/some/program %p %e
This will cause the system to execute your program (with the faulting process' pid and executable name), and pipe the core dump into its standard input. You may then log... |
Simple question; what is the function or library that i need to use to write a very simple program (in C) (linux, ubuntu) to find out whether a user exists on the system ?
In bash i'd do :
```
'ls -la /home | grep $user | wc -l'
```
I think it's posix for C (or python) ? Can anyone help me to get started ?
An exam... |
getpwnamis used for all accesses to the passwd database. If it returns NULL, the user doesn't exist.
|
what is the difference between the below declarations?
```
char *argv[];
```
and
```
char *(argv[]);
```
I think it is same according to spiral rule.
|
As written, the parentheses make no difference.
The so-called spiral rule falls out of this simple fact of C grammar: postfix operators such as()and[]have higher precedence than unary operators like*, so expressions like*f()and*a[]are parsed as*(f())and*(a[]).
So given a relatively complex expression like
```
*(*(*... |
The following code has me confused
```
int a=2,b=5,c;
c=a+++b;
printf("%d,%d,%d",a,b,c);
```
I expected the output to be 3,5,8, mainly because a++ means 2 +1 which equals 3, and 3 + 5 equals 8, so I expected 3,5,8. It turns out that the result is 3,5,7. Can someone explain why this is the case?
|
It's parsed asc = a++ + b, anda++means post-increment, i.e. increment after taking the value ofato computea + b == 2 + 5.
Please,neverwrite code like this.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:What is the signature of printf?
I know that there will be an argument list for every function.
if we pass the arguments more than no.of variables mentioned in the argument list then
it gives an error.but my question is
Printf() function ... |
printf is a "variadic" function. This means that the argument list is declared with...on the end, and in the implementation of printf theva_list,va_start,va_argetc macros are used to extract the arguments from the variable length list.
|
Let us say I have only one file in my project called test.c; the code below does not compile if I do not define "TRUE". I just want to understand the behavior. Please throw some light on this aspect.
```
#ifdef TRUE
static int a;
extern int a;
#else
extern int a;
static int a;
#endif
int main (void)
{
a =10;
pri... |
WhenTRUEis not defined, the first declaration (extern) saysahas external linkage (ISO/IEC 9899:1999, 6.2.2, paragraph 4, no prior declaration). The second declaration (static) statesahas internal linkage (paragraph 3). An identifier cannot have both internal and external linkage (paragraph 7).
In theTRUEdefined case,... |
``I have a requirement that the function call will have different names but all of them should refer to the same definition while executing.
For example,
i have a function calls like
```
UINT8 vsignal;UINT8 vsignal1;void Read_Message1_Signal1(&vSignal);void Read_Message2_Signal2(&vSignal1);
```
but this should be li... |
Is there some reason you can't just write your own wrapper?
```
void Read_Message1_Signal1(&vSignal)
{
Read_Message_Signal(vSignal);
}
void Read_Message2_Signal2(&vSignal)
{
Read_Message_Signal(vSignal);
}
```
You can autogenerate these with a macro if there are a lot of them.
|
I'm a noob at C/C++ So excuse the simplicity of the question, but here goes
```
unsigned char i;
for (i=0; i<1000; ++i)
if ((i%4) == 0)
printf("hello\n");
```
how many times will the code print "hello". I say 63, but alas its not one of the options. Can someone provide an answer, but more importantly an explan... |
Note: I am assuming 8 bit char types.
You will overflow when you perform++iforiequal to 255. At that point the language standard decrees thatibecomes 0, a phenomenon commonly known as wraparound.
So, you have an infinite loop, sincei<1000for all values ofi.
|
I havechar * source, and I want extract from it subsrting, that I know is beginning from symbols "abc", and ends where source ends. WithstrstrI can get the poiner, but not the position, and without position I don't know the length of the substring. How can I get the index of the substring in pure C?
|
Use pointer subtraction.
```
char *str = "sdfadabcGGGGGGGGG";
char *result = strstr(str, "abc");
int position = result - str;
int substringLength = strlen(str) - position;
```
|
"The wait() system call suspends execution of the current process until one of its children terminates" . Waitpid also is similar.
My Question is whether calling wait() from one thread will cause all other threads (in the same process) also to go to sleep ? Do the behavior is same for detached threads also?
|
This is just a bug in the manual.waitsuspends the calling thread, not the process. There is absolutely no way to suspend the whole process short of sending itSIGSTOPor manually suspending each thread one at a time.
|
In multicore systems, such as 2, 4, 8 cores, we typically use mutexes and semaphores to access shared memory. However, I can foresee that these methods would induce a high overhead for future systems with many cores. Are there any alternative methods that would be better for future many core systems for accessing shar... |
Transactional memoryis one such method.
|
When I use % operator on float values I get error stating that "invalid operands to binary % (have ‘float’ and ‘double’)".I want to enter the integers value only but the numbers are very large(not in the range of int type)so to avoid the inconvenience I use float.Is there any way to use % operator on such large intege... |
You can use thefmodfunction from the standard math library. Its prototype is in the standard header<math.h>.
|
After accepting data from a socket, can I view the header for the data? I want to know what IP address the packet was sent to as I am listening on multiple interfaces.
|
You can usegetsocknameto fetch the local IP address of the socket.
```
int getsockname(int socket, struct sockaddr *restrict address,
socklen_t *restrict address_len);
```
Here is an example:
```
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
memset(&addr, 0, sizeof(addr));
getsockname(s, &addr, &le... |
I have a computer on my network that had multiple IP addresses and uses multiple ports. Is there any way to open a socket that receives data on all those ip addresses and all those ports, and then have the data received contain the ip address from the packet header, and the port it received it on?
Rephrase:
How can I... |
You cannot bind to multiple ports using just one socket. The TCP/IP networking stack is based on the idea that one port == one socket.
|
I have the following code:
```
unsigned char* originaldata = (unsigned char*)malloc(50);
strcpy((char*)originalData,"12345 7");
unsigned char* replacingData = (unsigned char*)malloc(9);
strcpr((char*)replacingData,"11111111");
memset(replacingData,6,6);
```
Then, I want to replace the data from position 6 ti... |
```
memcpy(originalData+6, replacingData, strlen(originalData)-6)
```
Although, it should be noted that this makes the assumption thatoriginalDatais always greater than 6 characters long and thatreplacingDatais longer than 6 characters shorter thanoriginalData.
|
The baudrate is normally set to one of the specified values, like 9600, 56k and so on.
Is it possible to select another value, like 123456 Baud? Its an numerical parameter, so why not?
|
The clock of the communication module is usually derived from the system clock.
this system clock can be devided by specific numbers , like 2,4,8..
that's why you can reach only to specific baudrates.
Because you are talking on asynchronous protocol , clock is not transmitted on lines.
all of the above , cause the i... |
Does hitting a switch statement in C (assuming that it uses a jump table) empty the pipeline of an x86 processor? I'm thinking that it might because it would need the result of the table lookup to know what instruction to execute next. Can it forward that result back early enough that the pipeline doesn't get totally ... |
A jump table does not necessarily empty the pipeline. Indirect branches are predicted on modern processors, and the branch predictors do a better job than you might expect. Obviously, a correctly-predicted indirect branch does not cause a stall.
Not branching at all is preferable, but often impossible (or introduce... |
HI I have following three strings,
```
char* string1, string2, string3;
printf("First string = %s", string1);
printf("Second string = %s", string2);
printf("Third string = %s", string3);
```
Output of above code is,
```
First string = My Content is : %s, My value is : %d
Second string = Open source OS
Thirf string ... |
try:
```
printf(string1, string2, atoi(string3));
```
|
How to change the entry point of a C program compiled with gcc ?Just like in the following code
```
#include<stdio.h>
int entry() //entry is the entry point instead of main
{
return 0;
}
```
|
It's a linker setting:
```
-Wl,-eentry
```
the-Wl,...thing passes arguments to the linker, and the linker takes a-eargument to set the entry function
|
I need a tool which helps me to find memory leaks in a c program in a similar way valgrind does. It should figures out when a program overwrites memory it should not (e.g. by miscalculating an array index). I learned that there is the leaks utility along with the graphical instruments app.
However I think it can just... |
Valgrind 3.7.0 (released 5thNovember 2011) supports Lion.http://valgrind.org
|
Is it considered bad coding to put a break in the default part of a switch statement? A book I was reading said that it was optional but the teacher counted off for using it.
|
Best practice is to always use abreakunless you mean for control to flow into another case, even at the end of the switch.
|
I have two libraries, to simplify:
libA.lib, libB.lib
libA has function:
```
void read(num,*val){
*val=Globalval[num];
...
}
```
libB:
```
void write(num,val){
Globalval[num]=val;
...
}
```
that is the gist of what I want to achieve. The two libs are included in my main project files and the functions are called ... |
In one of the files, probably the write one (libB), put something like this:
```
int Globalval[SIZE];
```
In its header file, which should be included by libA, put this:
```
extern int Globalval[];
```
If your example really is what you're doing though, keep both functions in the same file, and call them from wher... |
I read about some algorithms that can be used to find a string pattren in long text as fast as possible. I am looking for usingaho-corasickalgorithm in executable files, What functions orwin apican be useful to make a binary ready to start searching?.
|
Here's one free C++ implementation for Windows:link(look for "Aho-Corasick source code" towards the bottom of the page).
|
Is anyone at hand with the YUY2 packed format scale routine in C/C++, without intermediary conversions to another color space? I cannot use any libraries like IPP, because its an embedded linux system...
Ideally such function should have this declaration:
bool YUY2_scale( uint8_t *in_buf, int in_width, int in_height... |
You can uselibswscalefrom the FFmpeg/libav/mplayer projects. It's the best there is.
|
Unfortunately I'm neither able to write C-code nor to implement available (and proven) libraries like the common libxml and libxslt used by PHP. I wonder if it is so hart to implement them in node.js? As far as I know C libraries could (easily) be implemented for a usage in node.js.
I'm looking forward to see somethi... |
If you take a look at thenode_xslt source code. You can see it's already interacting with libxslt.
So either use that module, or draw inspiration from it and improve it.
For future reference I used thenpm search registryand searched for "xslt"
|
I am looking for minimalistic alternative for std::map<long, int>, which would go into Windows kernel driver, so it should be quite fast.. it is expected to hold a relatively small (~200 in working set) amount of keys and a large amount of inserts.
Looking for solution that can cut key search cost.
|
Already done for you.
See the RtlXxxGenericTable and RtlXxxGenericTableAvl calls.
RtlInitializeElementGenericTableRtlDeleteElementGenericTableRtlEnumerateGenericTableRtlEnumerateGenericTableWithoutSplayingRtlGetElementGenericTableRtlInsertElementGenericTableRtlLookupElementGenericTableRtlNumberGenericTableElementsRt... |
When we want to use a function sayvoid foo(void)inFile1.cin myMain.c[ where my main function is ] - why do i not need to write:
extern int main(void);
InFile1.c?
AssumingFile1.candMain.care in a Single TU.
|
You never need to writeexternwith function declarations. Functions have external linkage by default. There's a strange unexplainable habit observed in some older code: to addexternto all external function declarations. (This is probably what led to your question aboutmain.) In reality, it is completely unnecessary, se... |
I am started to learn Lua few days ago and faced next problem. How can I run the whole lua script form C program, for example, I have a lua script and read it like a text file in my C program so how can I run this script from C side?
|
By usingluaL_dofile. even no need to read the text file in separately.
InProgramming in Lua, they do it using luaL_loadfile (to allow for some more flexibility)
|
I have a C file which contains lots of code comments, how I can I extract the comments? Just want the comments, not the c code. Is there any tools i can use to do this. e.g Doxygen? or need i to build a parser by myself? if needed, which language is better?
Thanks in advance.
thank you all!!
i start to look into per... |
Following one-liner displays all commented lines (or lines that contain comments) in main.c file:
```
cat main.c | awk '/\/\// {print $0}; /\/\*/ {blk=1}; {if(blk) print $0}; /\*\// {blk=0}'
```
|
I want to convert wstring to UTF-8 Encoding, but I want to use built-in functions of Linux.
Is there any built-in function that convertwstringorwchar_t*to UTF-8 in Linuxwith simple invokation?
Example:
```
wstring str = L"file_name.txt";
wstring mode = "a";
fopen([FUNCTION](str), [FUNCTION](mode)); // Simple invoke... |
If/when your compiler supports enough of C++11, you could usewstring_convert
```
#include <iostream>
#include <codecvt>
#include <locale>
int main()
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8_conv;
std::wstring str = L"file_name.txt";
std::cout << utf8_conv.to_bytes(str) << '\n';
}
```
teste... |
I'm trying to do some preprocessing in assembly using the imagecraft compiler avr. So far my best guess looks like this:
```
#define TEST 1
#if TEST == 1
ldi R20, 0xFF
#else
ldi R20, 0xF1
#endif
```
However doing this gives the compiler error:
```
absolute expression expected
```
How do I resolve this or is there ... |
Create an answer like this:
After some digging I've found the correct solution. Appearently iccavr reserves the .define derective to declare alias' to registers, so above if actually resolved to
```
.if R1 == 1
```
which generated the error message. The solution is to declare a symbolic constant instead of a define... |
Of course, I don't actually need it to highlight anything, I'll take care of that, however, it would be great if there would be a library that can parse text and can in an abstract manner tell me which words should I highlight and how should I treat them (as functions, vars, etc). I think (not sure) Clang would be an ... |
Yes libclang is the way to go.
Watchthis video(captured at 2010 LLVM Developers' Meeting) for more info, which presents the libclang API and should give you a really good overview of how to use the API.
You may probably be interested inthe others videos heretoo.
|
In the scenario of debugging a remote target running a custom RTOS, what would be necessary to add thread support to GDB?
In my case I have access to the RTOS sources and debug info for all its scheduler's symbols, so theoretically the information is accessible.
Would this imply recompiling GDB? Adding hooks to thre... |
You need to add thread support (and in particular, support forHandqXfer:threads:readpackets) for your gdb RTOS stub. Documentationhereandhere.
|
Is it considered bad coding to put a break in the default part of a switch statement? A book I was reading said that it was optional but the teacher counted off for using it.
|
Best practice is to always use abreakunless you mean for control to flow into another case, even at the end of the switch.
|
I have two libraries, to simplify:
libA.lib, libB.lib
libA has function:
```
void read(num,*val){
*val=Globalval[num];
...
}
```
libB:
```
void write(num,val){
Globalval[num]=val;
...
}
```
that is the gist of what I want to achieve. The two libs are included in my main project files and the functions are called ... |
In one of the files, probably the write one (libB), put something like this:
```
int Globalval[SIZE];
```
In its header file, which should be included by libA, put this:
```
extern int Globalval[];
```
If your example really is what you're doing though, keep both functions in the same file, and call them from wher... |
I read about some algorithms that can be used to find a string pattren in long text as fast as possible. I am looking for usingaho-corasickalgorithm in executable files, What functions orwin apican be useful to make a binary ready to start searching?.
|
Here's one free C++ implementation for Windows:link(look for "Aho-Corasick source code" towards the bottom of the page).
|
Is anyone at hand with the YUY2 packed format scale routine in C/C++, without intermediary conversions to another color space? I cannot use any libraries like IPP, because its an embedded linux system...
Ideally such function should have this declaration:
bool YUY2_scale( uint8_t *in_buf, int in_width, int in_height... |
You can uselibswscalefrom the FFmpeg/libav/mplayer projects. It's the best there is.
|
Unfortunately I'm neither able to write C-code nor to implement available (and proven) libraries like the common libxml and libxslt used by PHP. I wonder if it is so hart to implement them in node.js? As far as I know C libraries could (easily) be implemented for a usage in node.js.
I'm looking forward to see somethi... |
If you take a look at thenode_xslt source code. You can see it's already interacting with libxslt.
So either use that module, or draw inspiration from it and improve it.
For future reference I used thenpm search registryand searched for "xslt"
|
I am looking for minimalistic alternative for std::map<long, int>, which would go into Windows kernel driver, so it should be quite fast.. it is expected to hold a relatively small (~200 in working set) amount of keys and a large amount of inserts.
Looking for solution that can cut key search cost.
|
Already done for you.
See the RtlXxxGenericTable and RtlXxxGenericTableAvl calls.
RtlInitializeElementGenericTableRtlDeleteElementGenericTableRtlEnumerateGenericTableRtlEnumerateGenericTableWithoutSplayingRtlGetElementGenericTableRtlInsertElementGenericTableRtlLookupElementGenericTableRtlNumberGenericTableElementsRt... |
When we want to use a function sayvoid foo(void)inFile1.cin myMain.c[ where my main function is ] - why do i not need to write:
extern int main(void);
InFile1.c?
AssumingFile1.candMain.care in a Single TU.
|
You never need to writeexternwith function declarations. Functions have external linkage by default. There's a strange unexplainable habit observed in some older code: to addexternto all external function declarations. (This is probably what led to your question aboutmain.) In reality, it is completely unnecessary, se... |
I am started to learn Lua few days ago and faced next problem. How can I run the whole lua script form C program, for example, I have a lua script and read it like a text file in my C program so how can I run this script from C side?
|
By usingluaL_dofile. even no need to read the text file in separately.
InProgramming in Lua, they do it using luaL_loadfile (to allow for some more flexibility)
|
I have a C file which contains lots of code comments, how I can I extract the comments? Just want the comments, not the c code. Is there any tools i can use to do this. e.g Doxygen? or need i to build a parser by myself? if needed, which language is better?
Thanks in advance.
thank you all!!
i start to look into per... |
Following one-liner displays all commented lines (or lines that contain comments) in main.c file:
```
cat main.c | awk '/\/\// {print $0}; /\/\*/ {blk=1}; {if(blk) print $0}; /\*\// {blk=0}'
```
|
I want to convert wstring to UTF-8 Encoding, but I want to use built-in functions of Linux.
Is there any built-in function that convertwstringorwchar_t*to UTF-8 in Linuxwith simple invokation?
Example:
```
wstring str = L"file_name.txt";
wstring mode = "a";
fopen([FUNCTION](str), [FUNCTION](mode)); // Simple invoke... |
If/when your compiler supports enough of C++11, you could usewstring_convert
```
#include <iostream>
#include <codecvt>
#include <locale>
int main()
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8_conv;
std::wstring str = L"file_name.txt";
std::cout << utf8_conv.to_bytes(str) << '\n';
}
```
teste... |
I'm trying to do some preprocessing in assembly using the imagecraft compiler avr. So far my best guess looks like this:
```
#define TEST 1
#if TEST == 1
ldi R20, 0xFF
#else
ldi R20, 0xF1
#endif
```
However doing this gives the compiler error:
```
absolute expression expected
```
How do I resolve this or is there ... |
Create an answer like this:
After some digging I've found the correct solution. Appearently iccavr reserves the .define derective to declare alias' to registers, so above if actually resolved to
```
.if R1 == 1
```
which generated the error message. The solution is to declare a symbolic constant instead of a define... |
When we want to use a function sayvoid foo(void)inFile1.cin myMain.c[ where my main function is ] - why do i not need to write:
extern int main(void);
InFile1.c?
AssumingFile1.candMain.care in a Single TU.
|
You never need to writeexternwith function declarations. Functions have external linkage by default. There's a strange unexplainable habit observed in some older code: to addexternto all external function declarations. (This is probably what led to your question aboutmain.) In reality, it is completely unnecessary, se... |
I am started to learn Lua few days ago and faced next problem. How can I run the whole lua script form C program, for example, I have a lua script and read it like a text file in my C program so how can I run this script from C side?
|
By usingluaL_dofile. even no need to read the text file in separately.
InProgramming in Lua, they do it using luaL_loadfile (to allow for some more flexibility)
|
I have a C file which contains lots of code comments, how I can I extract the comments? Just want the comments, not the c code. Is there any tools i can use to do this. e.g Doxygen? or need i to build a parser by myself? if needed, which language is better?
Thanks in advance.
thank you all!!
i start to look into per... |
Following one-liner displays all commented lines (or lines that contain comments) in main.c file:
```
cat main.c | awk '/\/\// {print $0}; /\/\*/ {blk=1}; {if(blk) print $0}; /\*\// {blk=0}'
```
|
I want to convert wstring to UTF-8 Encoding, but I want to use built-in functions of Linux.
Is there any built-in function that convertwstringorwchar_t*to UTF-8 in Linuxwith simple invokation?
Example:
```
wstring str = L"file_name.txt";
wstring mode = "a";
fopen([FUNCTION](str), [FUNCTION](mode)); // Simple invoke... |
If/when your compiler supports enough of C++11, you could usewstring_convert
```
#include <iostream>
#include <codecvt>
#include <locale>
int main()
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8_conv;
std::wstring str = L"file_name.txt";
std::cout << utf8_conv.to_bytes(str) << '\n';
}
```
teste... |
I'm trying to do some preprocessing in assembly using the imagecraft compiler avr. So far my best guess looks like this:
```
#define TEST 1
#if TEST == 1
ldi R20, 0xFF
#else
ldi R20, 0xF1
#endif
```
However doing this gives the compiler error:
```
absolute expression expected
```
How do I resolve this or is there ... |
Create an answer like this:
After some digging I've found the correct solution. Appearently iccavr reserves the .define derective to declare alias' to registers, so above if actually resolved to
```
.if R1 == 1
```
which generated the error message. The solution is to declare a symbolic constant instead of a define... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.