question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I get an addres of string from assembler into C, and I need to get content of this address.
How to do it? Google gives C++ examples with reinterpret_cast, but it not working in C (I suppose).
I will appreciate if you will note needed libs too, tenx
```
#include <stdio.h>
#include <stdlib.h>
unsigned long const1(vo... |
If you've already got the address and you know it's a null terminated string, then all you need to do is treat it like a string.
```
printf("%s", (char*)alleged_string_address);
```
|
What's the most efficient/safest way to check if a string in C is made up only of spaces? Do I need to write a function myself to check or is there one in string.h that I can use?
|
Well, writing your own is trivial:
```
int IsSpaces( char * s ) {
while ( * s ) {
if ( ! isspace( * s ) ) {
return 0;
}
s++;
}
return 1;
}
```
Anything you use from the standard library is not likely to be much more efficient.
|
hi there i can compare people birthday in format YYYY-MM-DD with string (strcmp) functions. but i need compare todays date with person's birthday to display if his/her birthday is in 7 days or not_?. i searched "time.h" library but couldn't managed it. i appreciated if you can help.
|
I would usedifftimeon thetime_tvalues and compare against the number of seconds in a week...
|
Does anyone know of a free (non-GPL), decently performing compression library that supports packet oriented compression in C/C++?
With packet oriented, I mean the kind of featureQuickLZ(GPL) has, where multiple packets of a stream can be compressed and decompressed individually while a history is being maintained acr... |
zlib's maindeflate()function takes aflushparameter, which allows various different flushing modes. If you pass Z_SYNC_FLUSH at the end of each packet, that should produce the desired effect.
The details are explained in thezLib manual.
bzip2 has flushing functionality as well, which might let you do this kind of thi... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
I want to adapt my old C codebases,... |
Find all code that usesinet_aton,inet_ntoa,gethostbyname,gethostbyaddr,htonl,htons,ntohl,ntohs, and any directsockaddr_inmanipulation and replace it with simple calls togetaddrinfoorgetnameinfo. This will make your code much simpler and more maintainable and IPv6 will automatically work with no additional effort.
|
I am looking a set of#ifdef's to check availability of__restrictkeyword for GCC and Visual Studio. I assume that it needs to check compiler version, but I don't know for which versions it was introduced. Anyone that can help me out?
UPDATE: This must (and only needs to) work when compiling as C89! So I cannot rely on... |
How I fixed it:
```
#if defined(__GNUC__) && ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
# define SKP_restrict __restrict
#elif defined(_MSC_VER) && _MSC_VER >= 1400
# define SKP_restrict __restrict
#else
# define SKP_restrict
#endif
```
|
```
#include < iostream >
#define MY_CHK_DEF(flag) \
#ifdef (flag) \
std::cout<<#flag<<std::endl; \
#else \
std::cout<<#flag<<" ,flag not define"<<std::endl; \
#endif
int main()
{
MY_CHK_DEF(FLAG_1);
MY_CHK_DEF(FLAG_2);
MY_CHK_DEF(FLAG_3);
...
}
```
complier report:
main.cpp:3:... |
You can't do it. #if, #else, and #endif must be the first tokens on the logical line. Your definition is just one logical line, so it doesn't work,
|
I'm curious about few things about text algorithms.
For example we have binary word : 1011101110001101
And how to search for specific fixed subsequences in this word ?
For example how to find longest fixed subsequence(lets call it LFS) in word which has same amount of 1's and 0's ?
And another, how to find LFS with... |
You can make aTrieout of the input.
That will help you find LFS strings.
You can change the creation algorithm to count 1s and 0s, and then you'll easily find those numbers on the substring nodes.
Look atSuffix Treeas well..
Creation = O(n)For the search, you'll probably do something like BFS which also be like O(... |
When I use__attribute__ ((weak))like inthis postI get warnings from gcc about redeclaring the symbol, while all I do is adding an attribute. Can the attribute be attached differently? The warnings I get look like this:
```
threads.c:53: warning: redundant redeclaration of ‘pthread_once’
/usr/include/pthread.h:478: no... |
Yes - GCC allows you to use#pragma weakto declare symbols as weak, so you can do this instead:
```
#include <pthread.h>
#pragma weak pthread_create
#pragma weak pthread_mutex_init
#pragma weak pthread_mutex_lock
#pragma weak pthread_mutex_unlock
#pragma weak pthread_mutex_destroy
/* ... code ... */
```
(Documente... |
I am compiling a program for source, and it is not finding some dynamic libraries that are compiled with it. Here is the output when I run the executable. (It compiles fine)
```
dyld: Library not loaded: libipeqtcanvas.so.7.0.14
Referenced from: /Users/zrbecker/testipe/bin/./ipe
Reason: image not found
Trace/BPT ... |
You can setLD_LIBRARY_PATH(or actually,DYLD_LIBRARY_PATH, since you're on OS X) at runtime to include the library directory.
export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:/path/to/lib"
|
Isint puts(const char*);re-entrant? Can I safely put it into a signal handler?
|
Hereis a table with all functions considered safe for signal handling:
"The following table defines a set of
functions that shall be either
reentrant or non-interruptible by
signals and shall be
async-signal-safe."
putsdoes not seem to be in that list, however perthis, it is deemed reentrant, but not async-s... |
I'm trying to call into a C function that takes the following struct as a parameter:
```
typedef struct CSTRUCT
{
unsigned long* p1;
unsigned long* p2;
unsigned long* p3;
unsigned long* p4;
} CSTRUCT;
```
I need to call the function from C# and need to know the pinvoke C# equivalent for this C struct... |
unsigned long* p1in C is simply a pointer which you would typically declare asIntPtrin C#. That's the easy part of the process. The hard part is how to assign to the pointer. Is the pointer to memory owned by the C code? Or is it memory owned by the C# code? And who writes to that memory, the C code or the C# code... |
I am using a while loop to detect the presence of a ">" symbol in an array. The loop conditional never evaluates to true. When I show the contents of the array, the ">" symbol is there by itself though. In my code, this isn't the first call to strtok. This is also only a snippet of the total code. The string to be bro... |
strtokreturns achar *so I guess you're trying to compare strings.
You can't compare strings like that in C, usestrcmp. What you are doing now is comparing addresses, definitely not what you want.
|
Unsure how to tell if an overflow is possible. I am given this sample code:
```
char x;
float f, g;
// some values get assigned to x and f here...
g = f + x;
```
Can someone please explain?
|
Afloat, at its highest limits (binary exponent of 127), does not have sufficient precision (23 bits) to show a difference of the largest possiblechar(127, 7 bits), and so overflow is not possible since addition will have no effect (a precision of 127-7=120 would be required).
|
Im just trying to share an integer between two processes, but the memory segment is initialized in program 1 and is used in program 4. Here is the initialization in program 1:
```
shmid = shmget(key, sizeof(int*), 0666 | IPC_CREAT);
int *data = (int *)shmat(shmid, (void*)0,0);
```
Here I get a warning of "cast to po... |
Pretty sure you're missing the header that definesshmat()and thus the compiler is guessing thatshmatreturns an int (not a pointer).
|
In each of the following statements, what are the tokens?
a. x = y +++ 3;x, =, y, ++, +, 3, ; 7 tokensb. a+=c*=(d+-2)>>5&3;a, +=, c, *=, (, d, +, -, 2, ), >>, 5, &, 3, ; 15 tokens
For each, state whether it is a syntactically correct expression.a. x+++yx, ++, +, y. Yes.b. x+++++yx, ++, ++, +, y. No.
Just wondering ... |
Yes, your proposed answers are correct. Parentheses are tokens - in the C grammer, they're one of a class of tokens calledpunctuators.
|
What exactly does the below statement do?
```
const char *string
*string - '0'
```
Thanks!
|
It subtracts the value of the character'0'from the character pointed to bystring, turning it into a numerical value. So for example the character'9'will be turned into the integer9.
|
I would like to do some benchmarking on a few simple functions in C.
```
// Record start time
// Do a bunch of work
for (int i = 0; i < SOME_BIG_NUMBER; i++)
mySimpleFunction();
// Record stop time
```
In my release build configuration the compiler is smart enough to optimize this away.
Is there a canonic... |
Use the result:
```
int accum = 0;
// Record start time
// Do a bunch of work
for (int i = 0; i < SOME_BIG_NUMBER; i++)
accum += mySimpleFunction();
// Record stop time
printf("%d", accum);
```
|
I have a sample problem withw=1,y=7,z=0,x = ~(w && y) | y;and the solution isx = -1, but I can't figure out why?
Here is my thought process:(w && y) = (1 && 7) = 1~11 in bits is0000 0001~1 in bits is1111 1110
Not sure what to do from here.
|
The last step is a bitwise OR so you get:
```
1111 1110 | 0000 0111 = 1111 1111
```
which is -1.
|
Is there a way to find the parameters passes to the kernel (/proc/cmdline) at boot time without reading any files in proc? I might have a process that needs to read the boot parameters before /proc is mounted.
|
It seems the kernel passes anything on the boot line as a arg to init- unless there is a ' = ' or a ' . '
Passing Linux boot opts to Init
|
I'm trying to compare two character and see which one is lexicographic longer and sorting by it problem is I'm not sure how to compare single character I tried doing it with strcmp like
```
struct example
{
char code;
}
if (strcmp(i->code, j->code) < 0)
return 1;
```
warning: passing argument 1 of âstrcmpâ make... |
charis an integer type.
You comparecharobjects using the relational and equality operators (<,==, etc.).
|
I've been having trouble with fputs lately: when printing some strings in a text file with fputs, it happens I get other characters than A-Z, a-z, 0-9 in (chars that aren't part of the string). I made absolutely sure the strings all end with the null character. Unfortunately I can't give you more information, since I ... |
fputsis not inherently dangerous. Of course without example code its hard to say what was causing the problem you were seeing.
|
What is an efficient way to calculate the maximum of 2 floats inside a for loop in C without using a logic statement which might stall the pipeline such asa > b ? a : b?
I am working with huge 3D arrays and have tons of loop iterations.
|
Check what your compiler outputs, it's probably "optimal" already. For instance,
```
float foo(float a, float b)
{
return (a>b?a:b);
}
```
Compiled with GCC 4.5,-O3, generates this assembly on x86_64:
```
Disassembly of section .text:
0000000000000000 <foo>:
0: f3 0f 5f c1 maxss %xmm1,%xmm0
... |
```
main()
{
char *x="girl";
int n,i;
n=strlen(x);
*x=x[n];
for(i=0;i<n;i++)
{
printf("%s \n",x);
x++;
}
}
```
What is the output?Please explain the output.......................o/p is :
```
irl
rl
l
```
|
The output is undefined behaviour. You modified a string literal.
|
I am trying to create a method that finds and replaces a string within a string but I seem to have some error at compile time with it. Could I get some help into figuring out what is going on?
```
void replaceString(char *find, char *replace)
{
int len_string,i;
char temp[30];
len_string=strlen(find);
... |
stricmpis Windows-specific. If you're not on Windows,strcasecmp.
|
Is there a way to use preprocessor keywords inside of a macro? If there is some sort of escape character or something, I am not aware of it.
For example, I want to make a macro that expands to this:
```
#ifdef DEBUG
printf("FOO%s","BAR");
#else
log("FOO%s","BAR");
#endif
```
from this:
```
PRINT("FOO%s","B... |
You can't do that directly, no, but you can define thePRINTmacro differently depending on whetherDEBUGis defined:
```
#ifdef DEBUG
#define PRINT(...) printf(__VA_ARGS__)
#else
#define PRINT(...) log(__VA_ARGS__)
#endif
```
|
How do you connect a GtkTreeVew and a GtkListStore?
My TreeView shows the ListStore's data fine, but won't update the ListStore when the user changes a value in one of the cellrenderer widgets. The widgets behave normally but when they lose focus the value returns to normal.
Would I have to write signal handlers for... |
Apparently the only way to do this is to catch the edited signal and handle it manually. What a shame.
|
I'm looking to make a custom filesystem for a project I'm working on. Currently I am looking at writing it in Python combined with fusepy, but it got me wondering how a compiled non-userspace filesystem is made in Linux. Are there specific libraries that you need to work with or functions you need to implement for the... |
Yup you'd be programming to the kernel interfaces, specificallythe VFS layerat a minimum.EditBetter link[1]
'Full' documentation is in the kernel tree:http://www.mjmwired.net/kernel/Documentation/filesystems/vfs.txt. Of course, the fuse kernel module is programmed to exactly the same interface
This, however, is not ... |
I'm writing a fairly simple program with LEX, that after parsing a few files, parses input from a user.
Now, with the files, everything works like a charm. However, when it comes to user input from stdin, LEX rules won't run until an EOF (via ctrl+D) character is sent. When I do that, LEX parses all I wrote and then ... |
Solved! This did the trick:
```
%option always-interactive
```
I'm leaving this here for future reference, in case... well, who knows.
|
I trying to use a library (http://code.google.com/p/qxmpp/) but I can't find the name of the library to link it to. I want to understand how can you find out the name of the library to use in the linking parameters.
|
Looks like that is a source archive only -- no binaries included. Have you built the library from it? Where did the build process put it?/usr/libor/usr/local/libwould be usual suspects, but read the build and install documentation in the package.
|
Where i can find documentation about registers which assembly must preserve when a C function is called?
|
What you want is your system's C Application Binary Interface. Google for "C ABI" and your architecture, and you'll find it. For example,hereis one for sparc andhereis the relevant bit for AVRs.
|
I was going through The C programming Language by K&R. Here in a statement to print a double variable it is written
```
printf("\t%g\n", sum += atof(line));
```
where sum is declared as double. Can anybody please help me out when to use %g in case of double or in case of float and whats the difference between %g and... |
They are both examples of floating point input/output.
%g and %G are simplifiers of the scientific notation floats %e and %E.
%g will take a number that could be represented as %f (a simple float or double) or %e (scientific notation) and return it as the shorter of the two.
The output of your print statement will ... |
I've recently encountered a very rarely reproducible bug. If I cast a pointer that isn't nil to BOOL for some reason I get NO!!!11 I know that BOOL is typedef of signed char. Can that be a problem?
|
If the pointer is of the form0xNNNNNN00or (on 64-bit)0xNNNNNNNNNNNNNN00, whereNis any hex digit, then a cast toBOOL(anunsigned char) will leave you with0since it will truncate all the non-zero bits.
To properly convert a pointer toBOOL, use the inequality operator:
BOOL isNotNull = (myPointer != NULL);
|
I am doing a project in C and in that I need to process a lot of data . Is there a way to stop the program automatically after 30 minutes and then resume whenever I run the program again?
|
There is noautomaticway to do this. If you're on a Unix system though, you can pressCtrl+Zwhile your program is running to send it a STOP signal. It will wait until you continue again by sending it a CONT signal (the easiest way is with thefgshell command). A stopped process is still resident in memory, but is not run... |
I have to do some int -> byte conversion and switch to big endian for some MIDI data I'm writing. Right now, I'm doing it like:
```
int tempo = 500000;
char* a = (char*)&tempo;
//reverse it
inverse(a, 3);
[myMutableData appendBytes:a length:3];
```
and the inverse function:
```
void inverse(char inver_a[],int j)... |
Use theCore Foundation byte swapping functions.
```
int32_t unswapped = 0x12345678;
int32_t swapped = CFSwapInt32HostToBig(unswapped);
char* a = (char*) &swapped;
[myMutableData appendBytes:a length:sizeof(int32_t)];
```
|
Are there existing algorithm visualization tool for C programs? like visualizing an execution of a C program through animated execution stack.
|
I recommenddddfor fancy GUI debugging visualizations. It visualizes all the data structures and makes pretty graphs and gives you access to your regular debugger.
|
I open a file in program A. Its file descriptor is 3. Using fork followed by an execve I execute another program B, where I immediately open another file. This files descriptor is 4. If A and B was not sharing the file descriptor table then the file descriptor of file opened in B should have been 3. I need to create c... |
The childdoesn'tshare the same FD table, you simply forgot to close them in the child or mark them close-on-exec.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
To reach thestate of the artofdimen... |
FastICAis a very good package for doing this sort of thing, and it's available in C++, R, Python, and MATLAB. I have used the matlab version of this package; it's simple to use and produces good output.
|
As in: How do you recover the memory, and delete the array to such an extent you can initialize it again later in the program? Like so:
```
char * array[][2] = {
{"bla","bla","bla"},
{"blabity","blabity","bla"}
}
// Delete array
sizeof(array) == NULL;
char * array[][2] = {
{"bla","bla","bla"},
{"blabity","blabity","b... |
You can't. An array defined using brackets (outside the scope of a function1) is compiled directly into your program, and therefore cannot be deallocated. You can, however, reinitialize it simply by writing the initial contents to it again. If you want to be able to create and destroy an array at will, you need to sto... |
I am trying to create a method that finds and replaces a string within a string but I seem to have some error at compile time with it. Could I get some help into figuring out what is going on?
```
void replaceString(char *find, char *replace)
{
int len_string,i;
char temp[30];
len_string=strlen(find);
... |
stricmpis Windows-specific. If you're not on Windows,strcasecmp.
|
Is there a way to use preprocessor keywords inside of a macro? If there is some sort of escape character or something, I am not aware of it.
For example, I want to make a macro that expands to this:
```
#ifdef DEBUG
printf("FOO%s","BAR");
#else
log("FOO%s","BAR");
#endif
```
from this:
```
PRINT("FOO%s","B... |
You can't do that directly, no, but you can define thePRINTmacro differently depending on whetherDEBUGis defined:
```
#ifdef DEBUG
#define PRINT(...) printf(__VA_ARGS__)
#else
#define PRINT(...) log(__VA_ARGS__)
#endif
```
|
How do you connect a GtkTreeVew and a GtkListStore?
My TreeView shows the ListStore's data fine, but won't update the ListStore when the user changes a value in one of the cellrenderer widgets. The widgets behave normally but when they lose focus the value returns to normal.
Would I have to write signal handlers for... |
Apparently the only way to do this is to catch the edited signal and handle it manually. What a shame.
|
I'm looking to make a custom filesystem for a project I'm working on. Currently I am looking at writing it in Python combined with fusepy, but it got me wondering how a compiled non-userspace filesystem is made in Linux. Are there specific libraries that you need to work with or functions you need to implement for the... |
Yup you'd be programming to the kernel interfaces, specificallythe VFS layerat a minimum.EditBetter link[1]
'Full' documentation is in the kernel tree:http://www.mjmwired.net/kernel/Documentation/filesystems/vfs.txt. Of course, the fuse kernel module is programmed to exactly the same interface
This, however, is not ... |
I'm writing a fairly simple program with LEX, that after parsing a few files, parses input from a user.
Now, with the files, everything works like a charm. However, when it comes to user input from stdin, LEX rules won't run until an EOF (via ctrl+D) character is sent. When I do that, LEX parses all I wrote and then ... |
Solved! This did the trick:
```
%option always-interactive
```
I'm leaving this here for future reference, in case... well, who knows.
|
I trying to use a library (http://code.google.com/p/qxmpp/) but I can't find the name of the library to link it to. I want to understand how can you find out the name of the library to use in the linking parameters.
|
Looks like that is a source archive only -- no binaries included. Have you built the library from it? Where did the build process put it?/usr/libor/usr/local/libwould be usual suspects, but read the build and install documentation in the package.
|
Where i can find documentation about registers which assembly must preserve when a C function is called?
|
What you want is your system's C Application Binary Interface. Google for "C ABI" and your architecture, and you'll find it. For example,hereis one for sparc andhereis the relevant bit for AVRs.
|
I was going through The C programming Language by K&R. Here in a statement to print a double variable it is written
```
printf("\t%g\n", sum += atof(line));
```
where sum is declared as double. Can anybody please help me out when to use %g in case of double or in case of float and whats the difference between %g and... |
They are both examples of floating point input/output.
%g and %G are simplifiers of the scientific notation floats %e and %E.
%g will take a number that could be represented as %f (a simple float or double) or %e (scientific notation) and return it as the shorter of the two.
The output of your print statement will ... |
I've recently encountered a very rarely reproducible bug. If I cast a pointer that isn't nil to BOOL for some reason I get NO!!!11 I know that BOOL is typedef of signed char. Can that be a problem?
|
If the pointer is of the form0xNNNNNN00or (on 64-bit)0xNNNNNNNNNNNNNN00, whereNis any hex digit, then a cast toBOOL(anunsigned char) will leave you with0since it will truncate all the non-zero bits.
To properly convert a pointer toBOOL, use the inequality operator:
BOOL isNotNull = (myPointer != NULL);
|
I am doing a project in C and in that I need to process a lot of data . Is there a way to stop the program automatically after 30 minutes and then resume whenever I run the program again?
|
There is noautomaticway to do this. If you're on a Unix system though, you can pressCtrl+Zwhile your program is running to send it a STOP signal. It will wait until you continue again by sending it a CONT signal (the easiest way is with thefgshell command). A stopped process is still resident in memory, but is not run... |
I have to do some int -> byte conversion and switch to big endian for some MIDI data I'm writing. Right now, I'm doing it like:
```
int tempo = 500000;
char* a = (char*)&tempo;
//reverse it
inverse(a, 3);
[myMutableData appendBytes:a length:3];
```
and the inverse function:
```
void inverse(char inver_a[],int j)... |
Use theCore Foundation byte swapping functions.
```
int32_t unswapped = 0x12345678;
int32_t swapped = CFSwapInt32HostToBig(unswapped);
char* a = (char*) &swapped;
[myMutableData appendBytes:a length:sizeof(int32_t)];
```
|
Are there existing algorithm visualization tool for C programs? like visualizing an execution of a C program through animated execution stack.
|
I recommenddddfor fancy GUI debugging visualizations. It visualizes all the data structures and makes pretty graphs and gives you access to your regular debugger.
|
I open a file in program A. Its file descriptor is 3. Using fork followed by an execve I execute another program B, where I immediately open another file. This files descriptor is 4. If A and B was not sharing the file descriptor table then the file descriptor of file opened in B should have been 3. I need to create c... |
The childdoesn'tshare the same FD table, you simply forgot to close them in the child or mark them close-on-exec.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
To reach thestate of the artofdimen... |
FastICAis a very good package for doing this sort of thing, and it's available in C++, R, Python, and MATLAB. I have used the matlab version of this package; it's simple to use and produces good output.
|
As in: How do you recover the memory, and delete the array to such an extent you can initialize it again later in the program? Like so:
```
char * array[][2] = {
{"bla","bla","bla"},
{"blabity","blabity","bla"}
}
// Delete array
sizeof(array) == NULL;
char * array[][2] = {
{"bla","bla","bla"},
{"blabity","blabity","b... |
You can't. An array defined using brackets (outside the scope of a function1) is compiled directly into your program, and therefore cannot be deallocated. You can, however, reinitialize it simply by writing the initial contents to it again. If you want to be able to create and destroy an array at will, you need to sto... |
A client requested that the MTU limit should be 1492.
Is there a way to do it in the source code (program in C)?
Is there any other way to do it in general? (ifconfig?)
Why does somebody needs to modify MTU to a certain limit? What is the benefit? And the most
important: By changing the MTU is there any risk to bre... |
Programmaticaly way using C:
```
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
struct ifreq ifr;
strcpy(ifr.ifr_name, "eth0");
if(!ioctl(sock, SIOCGIFMTU, &ifr)) {
ifr.ifr_mtu // Contains current mtu value
}
ifr.ifr_mtu = ... // Change value if it needed
if(!ioctl(sock, SIOCSIFMTU, &ifr)) {
// Mtu changed ... |
I'm trying to implement in C some graph algorithms, using an adjacency matrix as support data structure.
I need to implement a weighted graph, with weigths represented by a real number.
Given that 0 and negative numbers would be a correct weight for an edge, how can I represent the absence of an edge between two node... |
You could use instead of a number (double) a structure like this:
```
struct weight
{
double weight;
bool edge_exists;
};
```
and create an adjacency matrix ofweight's. So ifedge_exists is false there is no reason to check theweight, otherwiseweightwill be meaningful.
I would use the above if every(?)doubleco... |
Hi can't read the french accent (like 'é') in a text file,
this is the piece of code I use to open and read the file...
```
FILE* file = fopen( [MyFileName UTF8String], "r, ccs=UTF-8");
if (file != 0)
{
while(fgets(buffer, 1024, file) != NULL)
{
NSString* string = [[NSString alloc] initWithCStri... |
The fgets function in c is ASCII only, you need to use the fgetws. This is the wide version of fgets for use with multibyte encodings.
|
In a C program, I have a file path in a string (specifically, this is theexename stored inargv[0]). I would like to extract the file name and discard the directory path using MS Visual Studio 2005. Any built in function for that?
|
For reference, here's the code I implemented, supposedly Win/Unix compatible:
```
char *pfile;
pfile = argv[0] + strlen(argv[0]);
for (; pfile > argv[0]; pfile--)
{
if ((*pfile == '\\') || (*pfile == '/'))
{
pfile++;
break;
}
}
```
|
I want to append two strings. I used the following command:
```
new_str = strcat(str1, str2);
```
This command changes the value ofstr1. I wantnew_strto be the concatanation ofstr1andstr2and at the same timestr1is not to be changed.
|
You need to allocate new space as well. Consider this code fragment:
```
char * new_str ;
if((new_str = malloc(strlen(str1)+strlen(str2)+1)) != NULL){
new_str[0] = '\0'; // ensures the memory is an empty string
strcat(new_str,str1);
strcat(new_str,str2);
} else {
fprintf(STDERR,"malloc failed!\n");... |
I have 2 applications, one written in C and the other in Java, that suppose to run on the same machine. What is the best way to implement an IPC between them?
best meaning portability, minimal user awareness (firewall popups...), etc.
|
I would use Sockets over loop back to start with. This allows you to send text or binary data and cleanly handle when one process starts or dies. The latency is about 20-50 micro-seconds depending on what you are doing with the data and how much you send.
Sockets are platform independent and can be use in pure Java.... |
As I understand correctly, besides the fact that Objective-C language is a strict superset of a "clean" C, added OOP paradigm is simulated by a set of functions partially described inObjective-C Runtime Reference.
Therefore, I'm expecting a possibility to somehow compile Objective-C code in an intermediate C/C++ file... |
You could use the clang rewriter to convert to C++. Not aware of a way to go to C though.
The rewriter is available via the "-rewrite-objc" command line option.
|
Why is garbage collection rarely spoken about in languages such as Pascal and C, whereas it is very important in SML and Java?
|
Pascal and C don't traditionally use garbage collections. They used manual memory management instead (malloc/freefor C andnew/disposein Pascal).
Garbage collection can beaddedin most languages that don't have them, but often with considerable expenses. An example of a garbage collector for C/C++ is theBoehm GC.
Java... |
I have to send a short string from ANSI C application to Java application through a socket - already done. Because its important data I have to encrypt it using password like "abc123". How should I do it in the simpliest way?
|
By "socket" I assume you mean a TCP/IP connection. In that case you should consider using Secure Sockets Layer (SSL). SSL pretty much solves most of the security problems associated with sending data across the wire. The only thing you need to work out is how to distribute keys to each end of the pipe.
I strongly rec... |
I'm new in c. I want to create array, and after it delete it, and then put another array into it. How can I do it?
|
If you are looking for a dynamic array in C they are fairly simple.
1) Declare a pointer to track the memory,2) Allocate the memory,3) Use the memory,4) Free the memory.
```
int *ary; //declare the array pointer
int size = 20; //lets make it a size of 20 (20 slots)
//allocate the memory for the array
ary = (int*)ca... |
I need to use the function _nextafterf on Visual C++ 32 bit to compute the distance in ULP of some results compare to reference functions.
C99 provides nextafterf and nextafter for float and double but these functions are not supported by Visual C++. However, Visual C++ 2010 supports _nextafterf and nextafter from b... |
There is a templatized equivalentnextafterin Boost.Math, seeFinding the Next Representable Value in a Specific Direction (nextafter).
The C99 functions must use suffixes f
and l to distinguish float and long
double versions. C++ uses the template
mechanism instead.
|
I am new to C and I have this code:
```
f = fopen( argv[1], "rb" );
fseek( f, 64, SEEK_SET );
fpos_t pos;
fgetpos (f, &pos);
printf("%x", pos);
```
However, this returns 40, even though it's supposed to be returning 64. What am i doing wrong?
|
You are outputting 64 in hex format,"%x". Since 64=0x40, the mystery is solved!
|
What exactly is the purpose of using malloc hooks? And I've read it's used in memory-profiling, etc. but never really understood how.
|
Well, if you can hook into the behaviour of allocation functions, then you can track memory allocations for profiling and debugging.
The GCC documentation on malloc hooks hasa nice little exampledemonstrating adding debug output every time the allocation functions are invoked.
I'm not really sure what else to tell y... |
Is there any way to check if an object file(.o file) is PIC-enabled?
|
Not sure how portable this is, but for x86 and x86_64, ELF format, you can usereadelf -rand look at the relocation types.
For 32bit PIC code, you should have a R_386_GOTPC relocation section:
```
Relocation section '.rel.text' at offset 0x38c contains 3 entries:
Offset Info Type Sym.Value Sym. Na... |
My ipad application has a custom look. It uses text labels extensively for displaying partly colored/shadowed/bold texts. Larger pieces of text may contain numbered lists and embedded Images. There could be couple rich text regions on a single page.
I am not sure that UIWebView is the right tool for displaying string... |
I would recommend usingTTStyledLabelfrom theThree20library. It provides the desired functionally and would save you the time of writing your own.
|
The below fails to compile:
```
typedef int arr[10];
int main(void) {
return sizeof arr;
}
sizeof.c:3: error: expected expression before ‘arr’
```
but if I change it to
```
sizeof(arr);
```
everything is fine. Why?
|
According to 6.5.3, there are two forms forsizeofas the following:
```
sizeof unary-expression
sizeof ( type-name )
```
Sincearrin your code is atype-name, it has to be parenthesized.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:what's the mechanism of sizeof() in C/C++?
Hi,
I'm a TA for a university, and recently, I showed my undergraduate students the following C code from a C puzzle I found:
```
int i = 5;
int j = sizeof(i++);
printf("%d\n%d\n", i, j);
```
I... |
The expression in a sizeof is not evaluated - only its type is used. In this case, the type is int, the result of what i++ would produce if it were evaluated. This behavior is necessary, as sizeof is actually a compile-time operation (so its result can be used for things like sizing arrays), not a run-time one.
|
I want to design a timer in Linux, but due to some system constraints and design requirements i cannot use the POSIX timer APIs.
Can somebody kindly let me know, what are the other timer design mechanisms available in Linux apart from the POSIX timers? (timer_create, timer_settime etc to avoid)
Thanks in advance.
E... |
Check out myanswer. One of the timers I find useful istimerfd_create()API provided in Linux system call. This blends well when your application is structured on an event loop.
|
Suppose, i know the process of my parent id and would like to
```
kill(my_parent_id, SIGTERM)
```
As a parent process, how can i catch this signal?
|
Register to catch the signal:
```
void termination_handler(int sig)
{
/* do something */
}
struct sigaction handler;
handler.sa_handler = termination_handler;
sigemptyset (&handler.sa_mask);
handler.sa_flags = SA_RESTART;
sigaction(SIGTERM, &handler, NULL);
```
Here is a goodexample page.
You could use the ol... |
We're running a Linux server with Microsoft SQL Server for the database. Are there any good (preferably open source) c libraries that we could use other than FreeTDS?
Thank you
|
Not really. Sybase has some client libraries, but they only work for older versions of MS SQL Server (since it is a derivative of Sybase SQL Server).
|
What is the purpose of this block in stdint.h (from newlib)?
```
#if defined(__GNUC__) && \
( (__GNUC__ >= 4) || \
( (__GNUC__ >= 3) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ > 2) ) )
/* gcc > 3.2 implicitly defines the values we are interested */
#define __STDINT_EXP(x) __##x##__
```
This macro is used la... |
##is the cpp (C Preprocessor) operator to concatenate tokens, ie.
```
#if __STDIN_EXP(LONG_MAX) > 0x7fffffff
```
evaluates to
```
#if __LONG_MAX__ > 0x7fffffff
```
in the first step.
|
Suppose I define the following:
```
unsigned char temp[2][13];
```
What is the default values will be assign to thischar[]? Is it like{'', '', '', ... , ''}?
In my program (The calculator), I haveoperand[2][13](where first operand isoperand[0]and second operand isoperand[1]) and I have Operation andResult[15]and th... |
memset(operand, 0, 2 * 13);memset(Result, 0, 15);
|
I am writing a multithreaded application and would like to pass around pointers to a struct.
Do the structs in the struct need to be malloced or if the outer struct is malloced will it prevent the internal structs from being deleted or lost when passing around the pointer?
Struct I am asking about is
```
struct thr... |
If the struct contains child structs, then it is generally all one block of memory. And so there would be no separate allocation.
If the struct instead contains pointers to structs, then my previous comment would not apply. In this case, it kind of depends on what you are doing.
Had you considered posting a tiny bit... |
Can anyone recommend a good library I could use on Linux to watermark videos? I want to overlay a watermark at several different positions in my videos, fade them in randomly and with different colors and opacity.
|
Have you triedffmpeg? That's a very good tool for video related stuff. Also for watermarking you can try thislink.
|
For some odd reason I was copying an example in another language of which does not use types, and forgot to add one in to a function definition parameter, and it worked.
```
#include <stdio.h>
char toChar(n) {
//sizeof n is 4 on my 32 bit system
const char *alpha = "0123456789ABCDEF";
return alpha[n];
}
int m... |
K&R-style function declaration:
```
void foo(n)
int n;
{
}
```
If type isn't specified, it defaults to int. This is valid in C89, not C99
|
I am wondering if there is an equivalent to C's fputc in PHP?
I am trying to do the following C code in PHP:
```
fputc(0x10, fp);
```
more information on fputc:http://en.wikipedia.org/wiki/C_file_input/output#Writing_to_a_stream_using_fputc
Thanks
|
You can write the character code directly to the file:
```
fputs($fp, "\x10");
// or
fputs($fp, chr(16));
// or
fputs($fp, chr(hexdec(10));
```
|
in my code I work with Ethernet MAC addresses and need to compare for a 00:00:00:00:00:00 address; the easiest solution I came up with is this:
```
#define ETH_ADDR_LEN 6
unsigned char mac[ETH_ADDR_LEN] = { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6 }; /* example */
const unsigned char empty[ETH_ADDR_LEN] = { 0, };
if (memcmp(m... |
There is nothing wrong with your code. Keep it as it is. The "empty" array contains 6 zeroes so it will work just fine.
|
Let's say I've got that:
```
char *p = NULL;
```
I'm sure this one would be a problem as I'd be dereferencing aNULLpointer:
```
*p = 16;
```
On the other hand, I think this one would be OK for I'd be getting the address of *p which is notNULLitself:
```
char **pp = &p;
```
Am I right in both cases?
|
Yes you are. Although the value of p is NULL, it still has a valid address, so you may pass its reference.
|
The pthread functions take a void * argument. How can a plain struct, not a pointer be sent in?
I want to send in a non pointer struct to one pthread function.
Also I want to send a pointer to the void * function, how is this done? can any pointer be sent in to the void * function?
|
Not possible; you have to send a pointer. However, avoid *can point to anything. If your struct variable is calledfoo, you can simply pass it as(void *) &foo, and inside the function, you can cast it back into e.g. astruct Foowithstruct Foo * fooPtr = (struct Foo *) param;orstruct Foo foo = *((struct Foo *) param);.
... |
I am trying to make a prog which can record voice and store it in digital audio format on LINUX using ALSA. (currently using Ubuntu).
While looking for some help on net, I found this code fromhere
```
#include "formats.h"
...
...
WaveChunkHeader wch, ch = {WAV_FMT,16};
WaveHeader h;
WaveFmtBody ... |
it should be in the alsa-utils package, subdirectory aplay:
http://alsa-utils.sourcearchive.com/documentation/1.0.17/formats_8h-source.html
|
I'm having a problem with using the automatic formatting in Eclipse CDT. For the most part it works great but it seems to insist on putting the semicolons after macro calls on a separate line.
Is this a bug or did I mischeck a combination of formatting settings which lead to this?
|
The problem has been fixed in later versions of Eclipse CDT. Just try to download later version of Eclipse.
|
I have created an 'External Build Project' in Xcode 4 using a makefile. The project builds perfectly, except the only way I know how to get it to run is in Terminal.
Is there a way I can run the program in Xcode 4 or is Terminal it ?
|
Yes, you can!
Product -> Edit scheme
Select "Run" from the left panel, select "Info" from top and specify "Executable" drop list
Select next pane "Arguments" and add "Arguments Passed On Launch" (to "Executable" you select before)
|
Suppose I have:
```
Operand[2][4] = {{"1", "2", "3", "4"},{"5", "6", "7", "8"}};
```
and I have some bit variables called Operand1_sign and Operand2_sign (0: positive and 1: negative) suppose they are:
```
Operand1_sign = 0;
Operand2_sign = 1;
```
How can I convert this into 2 integers and apply some operation on ... |
Instead of answering, I'll give you a clue: the number1234can also be expressed as1 * 1000 + 2*100 + 3*10 + 4*1- this is the key to parsing numbers :)
|
I hope that this makes sense.... is there a way to get xCode to use the makefile system for building C programs??
|
Yes - set up an "external build system" project.
|
WCHAR wszName;
In the debugger displays multiple "squares" and each addressed 0xcdcd
```
printf("Description: %ws\n", pIfRow->wszName); //prints nothing
```
Is there a reason it can not get the name from XP?(All other info inMIB_IFTABLEis correct)
Thanks
|
0xcdcdcdcd indicates that wszName was never initialized. It is the default value of heap-allocated memory in the Debug build. Review the code that copies a string into wszName, it is not working. Presumably the call to GetIfTable() failed or you're iterating the table wrong.
|
I need to control C-State configuration. Specifically, I'd probably like to execute the following asm code:
```
__asm
{
rdmsr
and eax, 0x00
or eax, 0x01
wrmsr
}
```
Currently, I got this exception onrdmsrline:
```
Unhandled exception at 0x00e3139e in MessWithCStates.exe: 0xC0000096: Privileged instr... |
Chances are, you are running this code on an x86 processor within Ring 3. You do not have the privileges to execute this command. Period. This is a hardware limitation. The only way to execute that instruction is to go into Ring 0 and chances are, your OS won't let you do that. You will need to write a kernel-mode dri... |
In C, how to do you call a function from just having its name as a string? I have this:
```
int main(int argc, const char *argv[])
{
char* events[] = {
"test",
"test2"
};
int i = 0;
for (; i < 2; ++i){
char* event = events[i];
// call function with name of "event"
... |
You can do it, but there's not much built-in to help out.
```
typedef struct {
char *event_name;
void (*handler)();
} event_handler;
```
then search through an array (or whatever) ofevent_handlers, and when you find the right name, call the associated function.
|
Does it even matter?Const before or const after?I'm guessing that whether I putconstbefore or afterCGFloatit makes the value ofCGFloatconstant, but what about the pointer? Is this right for Objective-C:
```
// Example.h
extern CGFloat const kPasscodeInputBoxWidth;
// Example.m
CGFloat const kPasscodeInputBoxWidth... |
It can go either before or after. In the case of a pointer, what matters is whether theconstends up before or after the asterisk:
```
const int *a; // pointer to const int -- can't change what a points at
int const *a; // same
int *const a; // const pointer to int -- can't change the pointer itself.
... |
I saw somewhere assert used with a message in the following way:
```
assert(("message", condition));
```
This seems to work great, except that gcc throws the following warning:
```
warning: left-hand operand of comma expression has no effect
```
How can I stop the warning?
|
Use-Wno-unused-valueto stop the warning; (the option-Wallincludes-Wunused-value).
I think even better is to use another method, like
```
assert(condition && "message");
```
|
In C or C++ if I want to modify the filesystem permissions of a file I can us a standard library function (chmod), which is very similar to the utility that one can execute from the UNIX prompt.
Is there an equivalently simple way to set the selinux context for a file? If so, what libraries do I need to link to and w... |
```
#include <selinux/selinux.h>
typedef char *security_context_t;
int setfilecon(const char *path, security_context_t con);
```
is probably the function you are looking for. You have to link against libselinux.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:Computational complexity of Fibonacci Sequence
Hi,
I found out a inductive proof yesterday for the time complexity of a recursive Fibonacci program.The proof first claimed that the complexity is exponential(and later goes on to prove it by... |
As Daniel says,ris greater than 1 sor^nis greater thanr^(n-1)which is greater thanr^(n-2)etc...
So you have indeed:f(n) >= r^n >= r^(n-1) >= r^(n-2)
|
is it possible in java to have a C like syntax for this:
```
int counter = 10;
while(counter){
System.out.println(counter--);
}
```
In C it is working very well to count until the counter is 0... do i really have to write
```
int counter = 10;
while(counter!=0... |
No, java requires abooleanin awhilecondition.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
% operator isn;t working in objecti... |
Modulas operator only works for integers..Check whether your operands are floats..If they are floats or doubles, you can usefmodfinstead..
|
In C, I can use the following form inside a method.
```
void foo() {
struct {
int val;
int color;
string desc;
} ItemMap[] = {
{ 1, 2, "test"},
{ 2, 3, "test"},
}
// process tasks according to ItemMap.
}
```
If I want to do the same thing under C#, how to achieve it ?
|
You could use anonymous types for that in C#:
```
var ItemMap = new[] { new { val = 1, color = 2, desc = "test" },
new { val = 2, color = 3 , desc = "test" } };
string description = ItemMap[0].desc;
```
This would however create a one-dimensional array of ananonymous classfor you not a struct... |
Here is what I have to find the kth smallest value in a binary search tree:
```
struct treeNode
{
int data;
struct treeNode *left, *right:
};
int rank(stuct treeNode* ptr, int k)
{
if(node == NULL)
return root;
while(ptr->left != NULL) {
ptr = ptr->left;
return rank(ptr->left)
}
}
```... |
A BST is a sorted binary tree, an in-order traversal (left subtree, current node, right subtree) will give sorted node values. To find the kth smallest node, just do an in-order traversal with a counter. The counter starts from 0, whenever a node is traversed, increase it by one, when it reaches k, the node is the kth... |
I have several equations that will return the binary value for each of the three bits in my number.
I am programing this in C which is a new language for me.
So let's say my equations returnY0 = 1,Y1 = 0andY2 = 1(101); I want to store that value as5.
Is this possible in C if these values are returned by different e... |
No such luck. You have to multiply (or shift, which is the same)
```
unsigned Y0 = 1, Y1 = 0, Y2 = 1, val;
val = (Y0 * 4) + (Y1 * 2) + (Y2 * 1); /* parens */
val = (Y0 << 2) + (Y1 << 1) + (Y2 << 0); /* redundant */
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.