question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
Is it possible to usefprintfin such a way that write data to a compressed file?
For example:
```
fopen ("myfile.txt","w");
```
will write to a plain text file. So the file size grows very large.
|
You can usezlibto write data to a compressed stream.
```
gzFile fp;
fp = gzopen(NAME, "wb");
gzprintf(fp, "Hello, %s!\n", "world");
gzclose(fp);
```
Compile it like this:
```
gcc -Wall -Wextra -o zprog zprog.c -lz
```
Usezcatto print the contents of the file.
|
Hello I am parsing text and using strtok() to do so. I am not sure how to include a '\' in my delimiters as C sees anything after this char as code.
```
char delims[] = "\n !@#$%^&*)(_+-=][}{|:;'<>?,./""";
```
Thanks!
|
You'll need to use an escape sequence for this. Escape sequences always start with a '\', and have one or more characters that follow.
In your example, you're after '\\'.
See this article on MSDN for more information about escape sequences:http://msdn.microsoft.com/en-us/library/h21280bw%28v=vs.80%29.aspx
|
What is theCPU_STATE_MAXmacro and what is it used for? I couldn't find any descriptive/relevant google results or man pages.
I am on Mac OSX Snowleopard, if that makes any difference.
|
Seethis--it corresponds to the number of CPU states defined in themachine.hheader. These different states are then used to index different pieces of information about the CPU state, which can differ by CPU state--idle, 'nice', etc.
|
was wondering what would be the best data structure to store a telephone directory when it has to be accessed via both name and number?
|
There is a bimap:http://commons.apache.org/collections/apidocs/org/apache/commons/collections/BidiMap.html
|
What are the sources or clock of Linux time functions ?
Are all (time , gettimeofday ...) getting updated clock values from reading same hardware component? Or are they all just retrieving some current time value maintained by Kernel?
Any of these function will read directly from BIOS ?
|
It varies depending on a large number of factors including what hardware is available, whether time synchronization is in use, and a number of other factors. On typical modern hardware, the TSC or HPET is read and scaled according to factors maintained by the kernel's timekeeping system.
|
Is it possible to usefprintfin such a way that write data to a compressed file?
For example:
```
fopen ("myfile.txt","w");
```
will write to a plain text file. So the file size grows very large.
|
You can usezlibto write data to a compressed stream.
```
gzFile fp;
fp = gzopen(NAME, "wb");
gzprintf(fp, "Hello, %s!\n", "world");
gzclose(fp);
```
Compile it like this:
```
gcc -Wall -Wextra -o zprog zprog.c -lz
```
Usezcatto print the contents of the file.
|
Hello I am parsing text and using strtok() to do so. I am not sure how to include a '\' in my delimiters as C sees anything after this char as code.
```
char delims[] = "\n !@#$%^&*)(_+-=][}{|:;'<>?,./""";
```
Thanks!
|
You'll need to use an escape sequence for this. Escape sequences always start with a '\', and have one or more characters that follow.
In your example, you're after '\\'.
See this article on MSDN for more information about escape sequences:http://msdn.microsoft.com/en-us/library/h21280bw%28v=vs.80%29.aspx
|
What is theCPU_STATE_MAXmacro and what is it used for? I couldn't find any descriptive/relevant google results or man pages.
I am on Mac OSX Snowleopard, if that makes any difference.
|
Seethis--it corresponds to the number of CPU states defined in themachine.hheader. These different states are then used to index different pieces of information about the CPU state, which can differ by CPU state--idle, 'nice', etc.
|
I want use a typedef struct that isn't already defined, but it is later.
Is there anything like a struct prototype?
file container.h
```
// i would place a sort of struct prototype here
typedef struct
{
TheType * the_type;
} Container;
```
file thetype.h
```
typedef struct {......} TheType;
```
file main.c
```... |
Replace this line:
```
// i would place a sort of struct prototype here
```
with these lines:
```
struct TheType;
typedef struct TheType TheType;
```
Since you need the typeTheTypeto be defined before typeContaineris defined, you have to use forward declaration of typeTheType- and to do so you also need forward de... |
I'm writing a program in C, and I need to known the mime-type of a file.
I have yet searched with Google, and I found thatI must include the 'file' UNIX utility in my project.
The source code offileneedconfigureandmake. How I can include this in my project? Do I have to crop a part of the source code into a newfile.... |
Do you want to guess the MIME type based on the extension, or do something likefileand examine the headers?
To get functionality similar tofile, you don't need to includefilein your project. Instead, you'll want to use libmagic whichfileis based on. Unfortunately I'm not aware of a good source of documentation for th... |
Simple question (I think), in C, I was able to scan in an entire line using:
```
fgets(line, MAX, input);
printf("%s\n", line);
```
Where it would, for example, print "Please cut me in half", how do I only get "me in half", including white spaces.
|
You do not know where the middle is until you scan the whole line. But you can scan the entire line, and then print only the second half, like this:
```
printf("%s\n", line+strlen(line)/2);
```
This is how the above code works:strlendetermines the length of the entire string (21), then we divide it in half using int... |
I am in the middle of writing a program which has a function which runs another function:
```
int executePuzzle(int input) {
switch (input) {
case 1: puzzle1();break;
case 2: puzzle2();break;
default:break;
}
}
```
However it may be more efficient to simply have something like:
```
i... |
It sounds like a place where function pointers would be useful
```
typedef void (*puzzlePointer)();
puzzlePointer puzzles[] = { puzzle1, puzzle2, puzzle3 };
void executePuzzle(int input) {
if (input >= 0 && input < 2) {
puzzles[input]();
}
}
```
|
I want a user defined function which is equivalent to strlen() function in C. In the below program it does the same function as strlen() but it has a limit to it. How can I make it count any length of text.
```
#include <stdio.h>
#include <conio.h>
void main()
{
int len(char *);
char s[20];
int l;
pri... |
I think your "limit" is because you usegets()on a buffer of 20 bytes. You will experience issues due to a buffer overflow. Exactly what happens when you do that is not entirely predictable.
If you fix that, I think your function will work as you expect it to. (Read the other people's answers for insight on your lengt... |
I am specifically talking about physical RAM, I do not want virtual memory stats to be included. I am on Mac OSX Snow leopard but would prefer a solution that would work on ALL OS X platforms (i.e. Lion). I am using Objective-C but solutions in C would also obviously be valid.
|
It sounds like what you want to be able to report is the same stuff that the command line utility vm_stat displays? If so then it's probably easiest just tocheck out its source code, which is amongst the stuff Apple provide as open source.
The relevant code is at the bottom; it all falls back on a call tohost_statist... |
I am trying to compile the implementation of the RFC 3797 random selection algorithm by Donald Eastlake (code:http://kambing.ui.ac.id/minix/other/rfc3797/). However, I am getting a linker error:
```
rfc3797.c:(.text+0xe7f): undefined reference to `log'
```
I am trying to make it with the provided Makefile, which exp... |
I don't know what the reason is, but if you move-lmto the end, it will compile.
```
$ cc -o randomselection rfc3797.c MD5.c -lm
rfc3797.c: In function ‘getinteger’:
rfc3797.c:183:3: warning: format not a string literal and no format arguments [-Wformat-security]
```
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:In C, how is the main() method initially called?
I want to know, who calls the main function in C.What is actual use of the main function ( why main is special/necessary ) ?Can I write a c program with out main function ?
|
Themainfunction is called, in practice, by the C runtime.
You can write a program withoutmainbut itmusthave an entry point. Different operating systems allow you to specify different entry points for your program, but they all serve the same purpose asmain. On Windows, you can useWinMain. On Linux you can link wit... |
I'm writing a C program and running multiple queries with sqlite. I'm not usingsqlite3_exec()as you can't retrieve results without writing a callback function for it.
So I have source that looks something like this:
```
char * query = "CREATE TABLE 'items' (id int, icon int, name text); CREATE TABLE 'icons' (id int,... |
Found in the references, my bad:
These routines only compile the first statement in zSql, so *pzTail is left pointing to what remains uncompiled.
|
I have a struct with 2 initialiser functions which take different types of arguments:
```
struct myStruct;
typedef struct myStruct *myStruct;
INFNumber *myStructMake(long long arg);
INFNumber *myStructMake(char *arg);
```
I get aconflicting types for 'myStructMake'error on the second declaration. Is C not capable o... |
Is C not capable of having 2 identically named functions which take
different parameters
That's right, no overloading. You have to use different names or choose some other scheme (like passing additional arguments).
|
I was revising C and came across to alloca/free functions which is described as allocating storage on a stack like space. Is this same as the malloc/free ? or this is something different ? Thanks.
|
I think you meanallocawhich is used to allocate memory on the stack. And yes, this is different frommallocandfreewhich allocate on the heap.
Don't attempt to free memory allocated withallocabecause it is automatically freed when the function that callsallocareturns to its caller.
Usingallocaand/or C99 variable lengt... |
I am looking for information on the implementation of md5 algorithm using vectorization.
I am interested in the details of SSE* and the AVX instructions.Are there any ready-made library with support for vectorization?
|
You could try looking atJohn the Ripper, they used to have highly optimized implementations of various cryptographic algorithms used to hash passwords.
|
```
void swap(int &first, int &second){
int temp = first;
first = second;
second = temp;
}
```
```
int a=3,b=2;
swap(a,b);
```
The compiler complaints thatvoid swap(int &first, int &second)has a syntax error. Why? Doesn't C support references?
|
C doesn't support passing by reference; that's a C++ feature. You'll have to pass pointers instead.
```
void swap(int *first, int *second){
int temp = *first;
*first = *second;
*second = temp;
}
int a=3,b=2;
swap(&a,&b);
```
|
When I'm trying to use_delay_us(condition ? value_if_true : value_if_false)in my 1-Wire implementation, delay doesn't work and i get no answer from my device, but it works fine when i replace it with:
```
if(condition) _delay_us(value_if_true);
else _delay_us(value_if_false);
```
When i displaying inline if value on... |
Thedocumentationclearly says:
In order for these functions to work as intended, compiler optimizations must be enabled, andthe delay time must be an expression that is a known constant at compile-time.If these requirements are not met, the resulting delay will be much longer (and basically unpredictable), and applica... |
I am working in C. To store a set of words for searching through them, I am told to save them in a hash table, and that it will reduce the time complexity to a constant.
Can someone help me out with the hash function? Also, if I have around 25 keywords, can I just make a table of size 25 and map each keyword to an in... |
One option is to look for aperfect hash function, a hash function for which collisions don't exist. The Linux toolgperf(not gprof) can be used to automatically generate a perfect hash function from a set of strings. As others have pointed out this is unlikely to give you a huge performance boost unless lookup times ... |
I have a global variable, X. I then fork and modify X from the child. I want those changes to show up in the parent, but I don't want the parent to have to wait on the child.
How can I do this?
|
You need to put the variable in shared memory. There are many ways to create shared memory. I'd probably just usemmap, but you could also check outshmgetorshm_open.
|
One function tries to pass char array to another, but without success:
```
char * ret() {
char buf[32];
buf[0]='1'; // buf char array contains 1
buf[31]='\0';
printf(buf);
return buf;
}
int multiline() {
char temp[32];
strcpy(temp,ret()); // temp array doesn't contain 1 after this line
... |
you are returning a pointer to a local variablechar buf[32];. This array is allocated on the stack and only valid within the function but not outside of the function.
You get undefined behavior when you access this array.
To return an array like this you should allocate it on the heap, eg. withmalloc()
|
I read below line in one book about "buffered input"
Why have buffers? First, it is less time-consuming to transmit several
characters as a block than to send them one by one
Please explain what is meaning of this sentence?
|
Why have buffers? First, it is less time-consuming to transmit several
characters as a block than to send them one by one
Let's say I'm your boss. I really like waffles but the store is 20 minutes away, and you have to run through zombie-infested badlands. So from time to time I send you to buy ONE. Wouldn't it be ... |
Ire any solutions available to inject in process own C/C++ dll and start from entrypoint, i need hook process socket send functions and paste my own code there. Is it available on linux?
Thanks!
|
The typical way to do it is to set theLD_PRELOADenvironment variable before launching the program. See for exampletsocks. Note though that some programs will disable this due to security reasons (it can snoop a passwords etc), e.g. gnupg preventsLD_PRELOADfrom working.
If you want to inject into a running program it'... |
First one - is what NDEBUG somehow already defined by default, so asserts don't work until you #undef it.
Second one - they do they work, but i receive no logging in DDMS.
If there is some android specific one assert.h?
Or i just do something wrong?
|
If you want to compile your code with asserts then you can do it in three ways:
use NDK_DEBUG=1 argument in ndk-build commandlineadd android:debuggable="true" to < application > tag in AndroidManifest.xmladd APP_OPTIM := debug to your Application.mk file - this will also disable optimizations and will compile with de... |
I usinglibzipto work with zip files and everything goes fine, until i need to read file from zip
I need to read just a whole text files, so it will be great to achieve something like PHP "file_get_contents" function.To read file from zip there is a function"int
zip_fread(struct zip_file *file, void *buf, zip_uint64_t ... |
You can try usingzip_statto get file size.http://linux.die.net/man/3/zip_stat
|
I was revising C and came across to alloca/free functions which is described as allocating storage on a stack like space. Is this same as the malloc/free ? or this is something different ? Thanks.
|
I think you meanallocawhich is used to allocate memory on the stack. And yes, this is different frommallocandfreewhich allocate on the heap.
Don't attempt to free memory allocated withallocabecause it is automatically freed when the function that callsallocareturns to its caller.
Usingallocaand/or C99 variable lengt... |
I am looking for information on the implementation of md5 algorithm using vectorization.
I am interested in the details of SSE* and the AVX instructions.Are there any ready-made library with support for vectorization?
|
You could try looking atJohn the Ripper, they used to have highly optimized implementations of various cryptographic algorithms used to hash passwords.
|
```
void swap(int &first, int &second){
int temp = first;
first = second;
second = temp;
}
```
```
int a=3,b=2;
swap(a,b);
```
The compiler complaints thatvoid swap(int &first, int &second)has a syntax error. Why? Doesn't C support references?
|
C doesn't support passing by reference; that's a C++ feature. You'll have to pass pointers instead.
```
void swap(int *first, int *second){
int temp = *first;
*first = *second;
*second = temp;
}
int a=3,b=2;
swap(&a,&b);
```
|
When I'm trying to use_delay_us(condition ? value_if_true : value_if_false)in my 1-Wire implementation, delay doesn't work and i get no answer from my device, but it works fine when i replace it with:
```
if(condition) _delay_us(value_if_true);
else _delay_us(value_if_false);
```
When i displaying inline if value on... |
Thedocumentationclearly says:
In order for these functions to work as intended, compiler optimizations must be enabled, andthe delay time must be an expression that is a known constant at compile-time.If these requirements are not met, the resulting delay will be much longer (and basically unpredictable), and applica... |
I am working in C. To store a set of words for searching through them, I am told to save them in a hash table, and that it will reduce the time complexity to a constant.
Can someone help me out with the hash function? Also, if I have around 25 keywords, can I just make a table of size 25 and map each keyword to an in... |
One option is to look for aperfect hash function, a hash function for which collisions don't exist. The Linux toolgperf(not gprof) can be used to automatically generate a perfect hash function from a set of strings. As others have pointed out this is unlikely to give you a huge performance boost unless lookup times ... |
I have a global variable, X. I then fork and modify X from the child. I want those changes to show up in the parent, but I don't want the parent to have to wait on the child.
How can I do this?
|
You need to put the variable in shared memory. There are many ways to create shared memory. I'd probably just usemmap, but you could also check outshmgetorshm_open.
|
One function tries to pass char array to another, but without success:
```
char * ret() {
char buf[32];
buf[0]='1'; // buf char array contains 1
buf[31]='\0';
printf(buf);
return buf;
}
int multiline() {
char temp[32];
strcpy(temp,ret()); // temp array doesn't contain 1 after this line
... |
you are returning a pointer to a local variablechar buf[32];. This array is allocated on the stack and only valid within the function but not outside of the function.
You get undefined behavior when you access this array.
To return an array like this you should allocate it on the heap, eg. withmalloc()
|
I read below line in one book about "buffered input"
Why have buffers? First, it is less time-consuming to transmit several
characters as a block than to send them one by one
Please explain what is meaning of this sentence?
|
Why have buffers? First, it is less time-consuming to transmit several
characters as a block than to send them one by one
Let's say I'm your boss. I really like waffles but the store is 20 minutes away, and you have to run through zombie-infested badlands. So from time to time I send you to buy ONE. Wouldn't it be ... |
Ire any solutions available to inject in process own C/C++ dll and start from entrypoint, i need hook process socket send functions and paste my own code there. Is it available on linux?
Thanks!
|
The typical way to do it is to set theLD_PRELOADenvironment variable before launching the program. See for exampletsocks. Note though that some programs will disable this due to security reasons (it can snoop a passwords etc), e.g. gnupg preventsLD_PRELOADfrom working.
If you want to inject into a running program it'... |
First one - is what NDEBUG somehow already defined by default, so asserts don't work until you #undef it.
Second one - they do they work, but i receive no logging in DDMS.
If there is some android specific one assert.h?
Or i just do something wrong?
|
If you want to compile your code with asserts then you can do it in three ways:
use NDK_DEBUG=1 argument in ndk-build commandlineadd android:debuggable="true" to < application > tag in AndroidManifest.xmladd APP_OPTIM := debug to your Application.mk file - this will also disable optimizations and will compile with de... |
I usinglibzipto work with zip files and everything goes fine, until i need to read file from zip
I need to read just a whole text files, so it will be great to achieve something like PHP "file_get_contents" function.To read file from zip there is a function"int
zip_fread(struct zip_file *file, void *buf, zip_uint64_t ... |
You can try usingzip_statto get file size.http://linux.die.net/man/3/zip_stat
|
Can anyone help me as what is going wrong here?
Am not able to allocate memory using malloc...
```
bReadFile = ReadFile( hConsoleFile, &ReadFileBuffer, MaxCharToRead, &CharsRead, NULL );
```
|
You have&ReadFileBufferin the call toReadFile. You are supposed to passReadFilea pointer to the buffer, not a pointer to a pointer to the buffer.
From thedocumentation:
```
lpBuffer [out]
A pointer to the buffer that receives the data read from a file or device.
```
SinceReadFileBufferisa pointer to the buffer,... |
I can refer C struct with its name. Anyway it looks it doesn't have run-time identity. I mean, there's no symbol for the struct. It's been referred from header files. So I think I can put struct of same name with different fields over multiple .c files without name duplication.
Am I right? Or C struct has it's symbol... |
If you're asking if you can reuse a structure name to mean different structures in different translation units, the answer is yes. I wouldn't say it's agoodidea, though.
|
How can I split a string into an array of strings based on a dividing character? For instance, how could I split a sentence into an array of words, separated by the space character?
|
You should use eitherstrtokorstrtok_r, both of which are describedhere(with examples). I'd recommended to usestrtok_r, sincestrtokis thread-unsafe, and you may add threads to your application in the future.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Is it possible to modify a string of char in C?
```
char *s = "anusha";
```
Is this like a constant pointer? When i tried to change the character in location 3 by writings[3]='k', it gave me a segmentation fault. So i am assuming it is li... |
That is correct, you are not allowed to modify string literals.
However, it's legal to do this:
```
char s[] = "anusha";
s[3] = 'k'
```
The difference here being that it is stored as a local array that can be modified.
|
Alright, I'm attempting to remove these pesky ^M characters that pop up when I compile and run my program on Linux.
I've attempted running
```
dos2unix filename
```
on the file, and the ^M's remain. I've also made sure that anytime I am opening the file, I am opening with
```
ios::binary
```
Is there some way to ... |
A number of tools will do it with a regular expression. For example, perl can edit the file in place:
```
# perl -i -p -e 's/\r//g' FILENAME
```
|
Can't create array of coreGraphic gradient colors list
I have anifstatement for 2 types of gradients
```
CGFloat colors[8];
if (YES) {
colors = { //expected expression error
130/255.0f, 42/255.0f, 212/255.0f, 0.3,
50/255.0f, 4/255.0f, 92/255.0f, 0.3
};
}
else {... |
You cannot assign array like that. I suggest you to:
```
float col1[]={ 130/255.0f, 42/255.0f, 212/255.0f, 0.3,
50/255.0f, 4/255.0f, 92/255.0f, 0.3};
float col2[]={1.0, 1.0, 1.0, 1.0,
207/255.0f, 207/255.0f, 207/255.0f, 1.0};
float *colors;
if (YES) colors=col1;
else colors=col2;
```
|
I am currently learning C Programming ( my first programming language ).
I am a little bit confused with the operators precedence.
Arithmetic operators precedence are as follows.
*/%+-
This is what is given in my book at least.
What i am confused is about how do i go solving expressions when it comes to my theory ex... |
```
a + 4/6 * 6/2
= 10 + 4/6 * 6/2
= 10 + 0*6/2
= 10 + 0/2
= 10
```
Note that4/6evaluates to0as integer division is used.
|
How to open a filename given in Main's argv[] (say, D:\a.txt) by CreateFile API?
```
CreateFile( ReadBuffer, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL );
```
|
It looks to me that your problem is simply that you are trying to call a function like this
```
Connect(char *filename)
{
HANDLE hFile = CreateFile(filename, ...);
....
}
```
and don't know how to get hold of the first command-line argument. Do it like this:
```
int main(int argc, char *argv[])
{
if (ar... |
In order to enforceC89 code conformance, I would like Visual Studio 2005not to accept C++-style comments(// my comment), but only C-style comments (/* my comment */).
Is there any available configuration in Visual Studio 2005 for that purpose? Thanks.
|
Well, sorry for that self-answered question. Everything isthere.
Just in case the link becomes unavailable: you need toenable strict mode(/Za), and add either a pragma or a compiler option in order to activate warnings or errors on these comments:
for a warning#pragma warning(1:4001)or/w14001for an error#pragma warn... |
see
```
char str[] = "hello world";
printf("%s",str);
```
printf statement prints the all character in string before reaching'\0'
so what if i want to print just 4 1st character ofstronstdout?
|
You can just specify the field width in the printf format string:
```
#include <stdio.h>
int main(void)
{
const char *s = "Hello world !";
printf("%.4s\n", s);
return 0;
}
```
or, if you want to specify the field width at run-time:
```
#include <stdio.h>
int main(void)
{
const char *s = "Hello wo... |
I have to rewrite code that references a 2-dimensional array using pointers instead of array operators.
How would I rewrite this:
```
...
else
array[i][j] = 'x';
...
```
So, I'm going to be setting the array to 'x' at that index. How would I do this with a pointer?
|
Assumingarrayischar array[x][y]then
```
*(*(array + i) + j) = 'x';
```
I mean, it's ugly and I probably wouldn't do that, but it will work.
```
*(array + i)
```
returns anotherchar[]at indexi. So, you then offset again into that usingj. You can (should) break that up into a few lines so that it is easy to scan.
|
How to open a filename given in Main's argv[] (say, D:\a.txt) by CreateFile API?
```
CreateFile( ReadBuffer, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL );
```
|
It looks to me that your problem is simply that you are trying to call a function like this
```
Connect(char *filename)
{
HANDLE hFile = CreateFile(filename, ...);
....
}
```
and don't know how to get hold of the first command-line argument. Do it like this:
```
int main(int argc, char *argv[])
{
if (ar... |
In order to enforceC89 code conformance, I would like Visual Studio 2005not to accept C++-style comments(// my comment), but only C-style comments (/* my comment */).
Is there any available configuration in Visual Studio 2005 for that purpose? Thanks.
|
Well, sorry for that self-answered question. Everything isthere.
Just in case the link becomes unavailable: you need toenable strict mode(/Za), and add either a pragma or a compiler option in order to activate warnings or errors on these comments:
for a warning#pragma warning(1:4001)or/w14001for an error#pragma warn... |
see
```
char str[] = "hello world";
printf("%s",str);
```
printf statement prints the all character in string before reaching'\0'
so what if i want to print just 4 1st character ofstronstdout?
|
You can just specify the field width in the printf format string:
```
#include <stdio.h>
int main(void)
{
const char *s = "Hello world !";
printf("%.4s\n", s);
return 0;
}
```
or, if you want to specify the field width at run-time:
```
#include <stdio.h>
int main(void)
{
const char *s = "Hello wo... |
I have to rewrite code that references a 2-dimensional array using pointers instead of array operators.
How would I rewrite this:
```
...
else
array[i][j] = 'x';
...
```
So, I'm going to be setting the array to 'x' at that index. How would I do this with a pointer?
|
Assumingarrayischar array[x][y]then
```
*(*(array + i) + j) = 'x';
```
I mean, it's ugly and I probably wouldn't do that, but it will work.
```
*(array + i)
```
returns anotherchar[]at indexi. So, you then offset again into that usingj. You can (should) break that up into a few lines so that it is easy to scan.
|
Think of a pointer-datatype, for instance to a floating-pointer number.
```
typedef float* flPtrt;
```
How would I allocate an array of 3 elements in the local scope? I guess usingmallocandfreewithing the same scope produces overhead, but what's the alternative?
```
void foo() {
flPtrt ptr = malloc(sizeof(float... |
If3is known at compile time and is small enough, you can declare a local array and use it as a pointer
```
void foo() {
float array[3];
flPtrt ptr = array;
}
```
If the size is bigger or variable, you have to use dynamic memory as in your example.
|
I'd like emacs to treat "#ifdef" exactly like "{" and "#endif" like "}" in relation to indentation. Like so:
```
#ifdef __linux__
#include <sys/socket.h>
#endif
int func(void)
{
int foo = 0;
#ifdef DO_STUFF
foo = do_stuff();
#endif
return foo;
}
```
instead of:
```
#ifdef __linux__
#i... |
You can use this el file for emacs :http://www.emacswiki.org/emacs/ppindent.el
You can find many info about emacs indentation here :http://www.emacswiki.org/emacs/IndentingC
|
I have the following in C:
```
long long int a;
long long int b;
long long int c;
long long int d=a*b/c;
```
However, I want 'd' to be double. Is there a way I can multiply, divide long long int and get a double as an answer keeping up to 3 decimals as precision?
Thanks
|
Cast (at least) one of thelong long ints todouble
```
double d = a * (double)b / c;
```
|
what is the best way to compare int arrays b and c with a:
```
int a[] = {0,1,0,0,1};
int b[] = {0,1,0,0,1};
int c[] = {1,1,0,0,1};
```
b and c are just examples, assume they can be any combination of 0s and 1s.
I am trying to detect arrays identical to a. I have googled this for a while and have not found a satisf... |
Use the standardmemcmpfunction from<string.h>.
```
memcmp(a, b, sizeof(a)) == 0
```
wheneveraandbare equal.
|
I am designing a C API which among other things has to provide a way to set some double-valued options. To identify the options I use the following enum:
```
typedef enum
{
OptionA,
OptionB,
...
} Option;
```
Is it a good idea to useOptionas a parameter type in a public API function:
```
int set_option(... |
By using anenumyou are effectively helping the user of your function to know what valid values are available.
Of course the drawback is that whenever a new option is added you will need to modify the header and thus the user may need to recompile his code whereas if it is aninthe may not have to do that.
|
I am writing a code in which I need to parse a string to a "long long int"
I used to use atoi when changing from string to int, I dont think it still work. What Can I use now?
--Thanks
|
Usestrtoll()(man page):
```
#include <stdlib.h>
long long int n = strtoll(s, NULL, 0);
```
(This is only available in C99 and C11, not in C89.) The third argument is the number base for the conversion, and0means "automatic", i.e. decimal, octal or hexadecimal are selected depending on the usual conventions (10,010,... |
I can't seem to figure out what I'm doing wrong.
```
int main(int argc, char **argv) {
int height = 4, width = 6;
int **map;
map = (int **)(malloc(height * sizeof(int*)));
for(i = 0; i < height; i++) {
map[i] = (int *)(malloc(width * sizeof(int)));
}
fill_map(&map, height, width);
}
void fill_map(int... |
Don't send &map to the function, change the prototype to receive (int **map) or, use (*map)[i][k]. This is because indirection operator * has lower precedence than [] operator.
|
I have aGtkTreeViewhooked into aGtkListStore, but theGtkCellRendererTextthat's all on it's own in a column, a column which is set to expand.
However the renderer is occupying a max width of 3 characters, just enough for the ellipsis...
While, and after editing the text:
|
Did you create your window with GtkBuilder? It might bethis bugrearing its ugly head again...
|
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.Closed11 years ago.
can somebody give a simple CGI prim... |
I prefer C/C++ if there is a way to replace PHP work with these
In that case, you will findG-WANC and C++ (compiled) scripts very helpful!
Instead of having to stop the server to recompile a C module (like with Nginx or Apache), G-WAN lets you "edit & play" your C/C++ source code in real-time.
|
What is a simple way to see if my low-pass filter is working? I'm in the process of designing a low-pass filter and would like to run tests on it in a relatively straight forward manner.
Presently I open up aWAVfile and stick all the samples in a array of ints. I then run the array through the low-pass filter to crea... |
You can use a broadband signal such as white noise to measure the frequency response:
generate white noise input signalpass white noise signal through filtertake FFT of output from filtercompute log magnitude of FFTplot log magnitude
Rather than coding this all up you can just dump the output from the filter to a te... |
Let's say I have this function, which is part of some gui toolkit:
```
typedef struct _My_Struct My_Struct;
/* struct ... */
void paint_handler( void* data )
{
if ( IS_MY_STRUCT(data) ) /* <-- can I do something like this? */
{
My_Struct* str = (My_Struct*) data;
}
}
/* in main() */
My_Struct s;
sign... |
Yourvoidpointer looses all its type information, so by that alone, you cannot check if it can be cast safely. It's up to the programmer to know if avoid*can be cast safely to a type.
|
How can I get the process name in C? The same name, which is in/proc/$pid/status. I do not want to parse that file. Is there any programmatic way of doing this?
|
If you're on using a glibc, then:
```
#define _GNU_SOURCE
#include <errno.h>
extern char *program_invocation_name;
extern char *program_invocation_short_name;
```
See program_invocation_name(3)
Under most Unices,__prognameis also defined by the libc.
The sole portable way is to useargv[0]
|
Let say I have a multi-dimensional array like
```
int a[10][10]
int b[10][10]
void arrayCopy(int* a, int* b, int size){
memcpy(b, a, size);
}
int main(){
a[0][0] = 13;
a[0][1] = 17;
"and so on..."
arraycopy(&a[0][0], &b[0][0], 10);
}
```
This code is not working I am unable to copy all the values ... |
Yoursizeargument is wrong for a few reasons. First of all, there are 10 * 10 == 100 elements, plus you're passing it tomemcpy()which takes its size inbytesand yourintis probably more like 4 bytes. Further, it's not really necessary to write such a function. This ought to suffice:
```
memcpy(b, a, sizeof(a));
```
|
We have some devices (Like IP cameras) on network. I am writing APIs in C to find these cameras. These cameras support multicast DNS query. I have the format for query, but I do not have the general response format. so that I could write API that can parse MDNS query responses. Can someone have MDNS parser, preferably... |
mDNS responses are formatted as per standard DNS responses, described inRFC1035.
See also the Multicast DNSRFC6762, in particular sections 16, 17, 18 and 19, which cover some differences with Unicast DNS (eg. longer messages are allowed, a wider character set is allowed).
|
I'm currently working on gcov and I need to pointers to study gcov. Perl scripts are being used to automate testing and I need to use gcov for test coverage. Apart from the gcov documentation what are the other things I should be aware of ? How do I proceed ?
|
Devel::Coverhas gcov support.
```
cd project_root
perl Makefile.PL
cover -test -gcov
$BROWSER cover_db/coverage.html
cover -delete
```
|
I need some assistance understanding how variables of a typedef work with structs
```
/*This is the Struct, with a new type Program*/
typedef struct prog{
char move[MAXNUMTOKENS][MAXTOKENSIZE];
int cm;
}Program;
Program prog; // new variable of type Program that has an array and an int
```
My question is... |
Think of a struct as a template for a new object.
The lineProgram progis creating a new structure object based on the template defined at the top.
Soprog.cm=0;means that yes you are initializing that specific objects cm field to zero.
The typedef is there simply so you dont have to writestruct prog 'variableName'wh... |
I have a library in C-language. is it possible to use it in C sharp.
http://zbar.sourceforge.net/is the link of library i want to use
|
C Libraries compiled for Windows can be called from C# usingPlatform Invoke.
FromMSDN, the syntax of making a C function call is as follows:
```
[DllImport("Kernel32.dll", SetLastError=true)]
static extern Boolean Beep(UInt32 frequency, UInt32 duration);
```
The above calls the function Beep in Kernel32.dll, passin... |
I can't seem to figure out what I'm doing wrong.
```
int main(int argc, char **argv) {
int height = 4, width = 6;
int **map;
map = (int **)(malloc(height * sizeof(int*)));
for(i = 0; i < height; i++) {
map[i] = (int *)(malloc(width * sizeof(int)));
}
fill_map(&map, height, width);
}
void fill_map(int... |
Don't send &map to the function, change the prototype to receive (int **map) or, use (*map)[i][k]. This is because indirection operator * has lower precedence than [] operator.
|
I have aGtkTreeViewhooked into aGtkListStore, but theGtkCellRendererTextthat's all on it's own in a column, a column which is set to expand.
However the renderer is occupying a max width of 3 characters, just enough for the ellipsis...
While, and after editing the text:
|
Did you create your window with GtkBuilder? It might bethis bugrearing its ugly head again...
|
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.Closed11 years ago.
can somebody give a simple CGI prim... |
I prefer C/C++ if there is a way to replace PHP work with these
In that case, you will findG-WANC and C++ (compiled) scripts very helpful!
Instead of having to stop the server to recompile a C module (like with Nginx or Apache), G-WAN lets you "edit & play" your C/C++ source code in real-time.
|
What is a simple way to see if my low-pass filter is working? I'm in the process of designing a low-pass filter and would like to run tests on it in a relatively straight forward manner.
Presently I open up aWAVfile and stick all the samples in a array of ints. I then run the array through the low-pass filter to crea... |
You can use a broadband signal such as white noise to measure the frequency response:
generate white noise input signalpass white noise signal through filtertake FFT of output from filtercompute log magnitude of FFTplot log magnitude
Rather than coding this all up you can just dump the output from the filter to a te... |
Let's say I have this function, which is part of some gui toolkit:
```
typedef struct _My_Struct My_Struct;
/* struct ... */
void paint_handler( void* data )
{
if ( IS_MY_STRUCT(data) ) /* <-- can I do something like this? */
{
My_Struct* str = (My_Struct*) data;
}
}
/* in main() */
My_Struct s;
sign... |
Yourvoidpointer looses all its type information, so by that alone, you cannot check if it can be cast safely. It's up to the programmer to know if avoid*can be cast safely to a type.
|
How can I get the process name in C? The same name, which is in/proc/$pid/status. I do not want to parse that file. Is there any programmatic way of doing this?
|
If you're on using a glibc, then:
```
#define _GNU_SOURCE
#include <errno.h>
extern char *program_invocation_name;
extern char *program_invocation_short_name;
```
See program_invocation_name(3)
Under most Unices,__prognameis also defined by the libc.
The sole portable way is to useargv[0]
|
Let say I have a multi-dimensional array like
```
int a[10][10]
int b[10][10]
void arrayCopy(int* a, int* b, int size){
memcpy(b, a, size);
}
int main(){
a[0][0] = 13;
a[0][1] = 17;
"and so on..."
arraycopy(&a[0][0], &b[0][0], 10);
}
```
This code is not working I am unable to copy all the values ... |
Yoursizeargument is wrong for a few reasons. First of all, there are 10 * 10 == 100 elements, plus you're passing it tomemcpy()which takes its size inbytesand yourintis probably more like 4 bytes. Further, it's not really necessary to write such a function. This ought to suffice:
```
memcpy(b, a, sizeof(a));
```
|
We have some devices (Like IP cameras) on network. I am writing APIs in C to find these cameras. These cameras support multicast DNS query. I have the format for query, but I do not have the general response format. so that I could write API that can parse MDNS query responses. Can someone have MDNS parser, preferably... |
mDNS responses are formatted as per standard DNS responses, described inRFC1035.
See also the Multicast DNSRFC6762, in particular sections 16, 17, 18 and 19, which cover some differences with Unicast DNS (eg. longer messages are allowed, a wider character set is allowed).
|
I'm currently working on gcov and I need to pointers to study gcov. Perl scripts are being used to automate testing and I need to use gcov for test coverage. Apart from the gcov documentation what are the other things I should be aware of ? How do I proceed ?
|
Devel::Coverhas gcov support.
```
cd project_root
perl Makefile.PL
cover -test -gcov
$BROWSER cover_db/coverage.html
cover -delete
```
|
I need some assistance understanding how variables of a typedef work with structs
```
/*This is the Struct, with a new type Program*/
typedef struct prog{
char move[MAXNUMTOKENS][MAXTOKENSIZE];
int cm;
}Program;
Program prog; // new variable of type Program that has an array and an int
```
My question is... |
Think of a struct as a template for a new object.
The lineProgram progis creating a new structure object based on the template defined at the top.
Soprog.cm=0;means that yes you are initializing that specific objects cm field to zero.
The typedef is there simply so you dont have to writestruct prog 'variableName'wh... |
I have aGtkTreeViewhooked into aGtkListStore, but theGtkCellRendererTextthat's all on it's own in a column, a column which is set to expand.
However the renderer is occupying a max width of 3 characters, just enough for the ellipsis...
While, and after editing the text:
|
Did you create your window with GtkBuilder? It might bethis bugrearing its ugly head again...
|
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.Closed11 years ago.
can somebody give a simple CGI prim... |
I prefer C/C++ if there is a way to replace PHP work with these
In that case, you will findG-WANC and C++ (compiled) scripts very helpful!
Instead of having to stop the server to recompile a C module (like with Nginx or Apache), G-WAN lets you "edit & play" your C/C++ source code in real-time.
|
What is a simple way to see if my low-pass filter is working? I'm in the process of designing a low-pass filter and would like to run tests on it in a relatively straight forward manner.
Presently I open up aWAVfile and stick all the samples in a array of ints. I then run the array through the low-pass filter to crea... |
You can use a broadband signal such as white noise to measure the frequency response:
generate white noise input signalpass white noise signal through filtertake FFT of output from filtercompute log magnitude of FFTplot log magnitude
Rather than coding this all up you can just dump the output from the filter to a te... |
Let's say I have this function, which is part of some gui toolkit:
```
typedef struct _My_Struct My_Struct;
/* struct ... */
void paint_handler( void* data )
{
if ( IS_MY_STRUCT(data) ) /* <-- can I do something like this? */
{
My_Struct* str = (My_Struct*) data;
}
}
/* in main() */
My_Struct s;
sign... |
Yourvoidpointer looses all its type information, so by that alone, you cannot check if it can be cast safely. It's up to the programmer to know if avoid*can be cast safely to a type.
|
How can I get the process name in C? The same name, which is in/proc/$pid/status. I do not want to parse that file. Is there any programmatic way of doing this?
|
If you're on using a glibc, then:
```
#define _GNU_SOURCE
#include <errno.h>
extern char *program_invocation_name;
extern char *program_invocation_short_name;
```
See program_invocation_name(3)
Under most Unices,__prognameis also defined by the libc.
The sole portable way is to useargv[0]
|
Let say I have a multi-dimensional array like
```
int a[10][10]
int b[10][10]
void arrayCopy(int* a, int* b, int size){
memcpy(b, a, size);
}
int main(){
a[0][0] = 13;
a[0][1] = 17;
"and so on..."
arraycopy(&a[0][0], &b[0][0], 10);
}
```
This code is not working I am unable to copy all the values ... |
Yoursizeargument is wrong for a few reasons. First of all, there are 10 * 10 == 100 elements, plus you're passing it tomemcpy()which takes its size inbytesand yourintis probably more like 4 bytes. Further, it's not really necessary to write such a function. This ought to suffice:
```
memcpy(b, a, sizeof(a));
```
|
We have some devices (Like IP cameras) on network. I am writing APIs in C to find these cameras. These cameras support multicast DNS query. I have the format for query, but I do not have the general response format. so that I could write API that can parse MDNS query responses. Can someone have MDNS parser, preferably... |
mDNS responses are formatted as per standard DNS responses, described inRFC1035.
See also the Multicast DNSRFC6762, in particular sections 16, 17, 18 and 19, which cover some differences with Unicast DNS (eg. longer messages are allowed, a wider character set is allowed).
|
I'm currently working on gcov and I need to pointers to study gcov. Perl scripts are being used to automate testing and I need to use gcov for test coverage. Apart from the gcov documentation what are the other things I should be aware of ? How do I proceed ?
|
Devel::Coverhas gcov support.
```
cd project_root
perl Makefile.PL
cover -test -gcov
$BROWSER cover_db/coverage.html
cover -delete
```
|
I need some assistance understanding how variables of a typedef work with structs
```
/*This is the Struct, with a new type Program*/
typedef struct prog{
char move[MAXNUMTOKENS][MAXTOKENSIZE];
int cm;
}Program;
Program prog; // new variable of type Program that has an array and an int
```
My question is... |
Think of a struct as a template for a new object.
The lineProgram progis creating a new structure object based on the template defined at the top.
Soprog.cm=0;means that yes you are initializing that specific objects cm field to zero.
The typedef is there simply so you dont have to writestruct prog 'variableName'wh... |
I have a library in C-language. is it possible to use it in C sharp.
http://zbar.sourceforge.net/is the link of library i want to use
|
C Libraries compiled for Windows can be called from C# usingPlatform Invoke.
FromMSDN, the syntax of making a C function call is as follows:
```
[DllImport("Kernel32.dll", SetLastError=true)]
static extern Boolean Beep(UInt32 frequency, UInt32 duration);
```
The above calls the function Beep in Kernel32.dll, passin... |
This question already has an answer here:Error C2664: 'strcpy' : cannot convert parameter 2 from 'const wchar_t [9]' to 'const char *'.How to solve this error?(1 answer)Closed9 years ago.
Here is the piece of code which display all files in the folder.
```
StringCbCopyN (DirSpec, BUFSIZE, argv[1], length_of_arg+1); ... |
hari, I already told youthat to useTCHARstrings, you should be usingthe functions in#include <strsafe.h>.
|
In many of the C and C++ files I have seen macros like this:
```
#ifdef X
#undef X // no statements in between
#endif
```
I feel that, it's adequate to simply write:
```
#undef X
```
If the macroXwasn't defined, then the#undefshould have no effect.
Is itokto put standalone#undef, if I want to onlyundefinea macro... |
See ISO C99 6.10.3.5 paragraph 2.
A preprocessing directive of the form# undef identifier new-linecauses the specified identifier no longer to be defined as a macro name. It is ignored if
the specified identifier is not currently defined as a macro name.
EvenVisual C++ 6(which was notorious for bad standards compl... |
I'm sure there is a very simple answer to this question. However, I am trying to add a character to the beginning and the end of a line in C. I have the add at the beginning part down but am having issues with adding the add to the end part. Is there a simple solution just using the code I have? Thanks in advance
```... |
You need to check fornewlinebeforeprinting the character, something like this:
```
while (scanf("%c", &c) != EOF) {
if (c == '\n') {
printf("0");
}
printf("%c",c);
}
```
This code will print your new character before thenewline.
|
I am trying to split up an array (string1) of n characters into two character pointers representing i characters (char* first) and n-i characters (char* second) respectively. For the second array, I used
```
char* second = string1+n;
```
What I am wondering is how to use only the first i characters in first. I do ... |
Unless you allocate more memory you can't use the "first" as you would any other C string (e.g. passing it to string functions,printf, etc) because it isn't null terminated at the boundary with "second".
You can certainly still get around that in many cases because you know the length, but there's nothing magical you... |
I recently bought a new Mac and did a time machine restore of my old mac & updated the xCode version to the latest version. After the move I have lost the ability to use Make and GCC; saying these commands are unavailable. I use Make and GCC to develop for homework assignments for classes that I later SCP up to a Linu... |
gcc should be in/Developer/usr/bin/. Check there.
|
I have a 2d matrix created with the code:
```
for(i=0; i < size; i++)
{
for(j=0; j <size; j++)
{
a1[i][j] = i+1 + j+2;
}
}
```
I am trying to replicate that pattern in a matrix created by:
```
double*
a = malloc(sizeof(double)*randk*randk);
```
I can't seem to figure out how to define that same... |
From the comp.lang.c FAQ:
How can I dynamically allocate a multidimensional array?
|
I have a very simple (sample) C program as follows. I want to ensure I release any resources necessary so that valgrind does not complain. Do I need to free mutex1? Or do anything before the program terminates? Or is the mutex1 not allocate memory?
```
02 pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
03 i... |
No, it is fine as it is. It is not necessary to use pthread_mutex_destroy on a statically allocated mutex.
|
Please recommendation for most simple conversion from integer where integers can be only 0 and 1 to char*, in C language.
I have function which returns 0 or 1 as integer.
```
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(mytogglebutton));
```
In other module it is function and in third declaration.
```
int set_lo... |
The shortest way for this would be using the ternary conditional operator:
```
set_locals("my_prop",
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(mytogglebutton)) ? "1" : "0" );
```
However this is aconst char*, but as you presented the problem, I don't think it will be an issue.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.