question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
As I've discovered from my tests iPhone's malloc has 16 byte alignment. But I'm not sure whether it is guaranteed or just coincidence.
So the question is: what is the guaranteed memory alignment when using malloc() on iOS and Android(NDK)?
|
On iOS, the alignment is currently 16 bytes, as you've discovered. However, that isn't guaranteed, nor documented. I.e. don't rely on it.
Assuming it is available on iOS,posix_memalign()allows for the allocation of specifically aligned memory. There may be other mechanisms.
Android is not my bailiwick.
|
I have a few planes (3-10 of them) in 3d defined by their equations (three coefficients and the offset). These planes are the edges of a convex polyhedron. I need to draw that polyhedron. How can I do that? What software/libraries/algorithms can I use? I work in Linux and I'm usually using C or C++.
|
Every plane pair intersects in a line on both planes. Each plane then contains a set of lines that intersect in points, all of those are the edge points of your polyhedron you'll have to connect in a convex way.
With some math/geometry skills, you should be able to solve this, but using a library (f.e.CGAL) of course simplifies it and prevent you from reinventing the wheel.
|
can anybody explain C C++ Java regarding dynamic typed or static typed language.
I read somewhere that C C++ and Java are all static language. But I recall there are other opinions about these. Very confused.
Thanks!
|
What other opinions? There is no question that C, C++, and Java are all statically typed languages, with C++ and Java having some dynamically typed features. There's another issue: strongly vs. weakly typed, which pertains primarily to implicit conversions and overloading. There are numerous in-depth discussions of these issues available on the web; you might want to start withhttp://en.wikipedia.org/wiki/Type_system
|
I'm making a program which controls other processes (as far as stopped and started states).
One of the criteria is that the load on the computer is under a certain value.
So i need a function or small program which will cause the load to be very high for testing purposes. Can you think of anything?
Thanks.
|
I can think of this one :
```
for(;;);
```
|
I need something similar to this in PHP:
```
struct MSG_HEAD
{
unsigned char c;
unsigned char size;
unsigned char headcode;
};
struct GET_INFO
{
struct MSG_HEAD h;
unsigned char Type;
unsigned short Port;
char Name[50];
unsigned short Code;
};
void Example(GET_INFO * msg)
{
printf(msg->Name);
printf(msg->Code);
}
```
|
```
class MSG_HEAD
{
public $c;
public $size;
public $headcode;
}
class GET_INFO
{
public $h;
public $Type;
public $Port;
public $Name;
public $Code;
}
function Example(GET_INFO $msg)
{
echo $msg->Name;
echo $msg->Code;
}
```
|
I have a program which forks off other processes. The arguments to my program include the process name of the process to be forked, along with any arguments.
This means, when I make the call to exec(), I need to be able to handle however many arguments were supplied.
Any ideas?
Thanks.
|
Theexecvfunction takes a pointer to an array of arguments.
Just like inmain, the last element in the array needs to be a null pointer.
|
```
for (nbyte=0; nbyte<6; nbyte++) {
mac->byte[nbyte] = (char) (strtoul(string+nbyte*3, 0, 16) & 0xFF);
}
```
This is a small piece of code found in macchanger, string is a char pointer that points a MAC address, what i don't know is that why must i convert it to a unsigned long int,and why must i *3 then AND it with 0xFF.
|
Most likely the string is a mac address in the form of
```
XX:YY:ZZ:AA:BB:CC
```
Doingnbyte*3moves the "starting offset" pointer up 3 characters in the string each iteration, skipping over the:. Then strotoul reads 16bits (2 characters) and converts them to an unsigned long, which is then ANDed with 0xFF to strip off all but the lowest byte, which gets cast to a char.
|
I want to parse the output of the commandwfor use in my program
I know i can executewusingexeclpbut is there a way to get the output from w into my program directly? I'm thinking i could use a pipe or something, but I don't know very much about it or how pipes work in an execlp command.
Thanks for the help
|
Look atpopenfor a simple way to do that, although it has various weaknesses (calling out to the shell, for example).libslackalso has apopenreplacement (the coprocess functions); it is under the GPL.
|
```
static struct K { int x; };
```
Is this valid in C and C++?
|
In C, it's valid butuseless.
In C++ it's invalid. You can only specify storage class for objects and functions.
|
I am searching for a solution to delete all files from my pendrive using a C program. I don't want the code to detect the pendrive as that's not a concern right now. I would appreciate any links that could help me out on this.
Note: I am working on Windows 7 64-bit and I want to delete the entire contents from my pendrive, which contains .exes and .dlls.
Thanks and Regards,
Radix
|
The non-hackcorrectway to do this, is via theVirtual Disk Service.
|
I'm trying to read a text file built with the following format in every line:
char*,char*,int
i.e.:
aaaaa,dfdsd,23bbbasdaa,ddd,100
i want to use fscanf to read a line from file, and automatically parse the line into the varilables string1,string2,intA
What's the correct way of doing it ?
Thanks
|
Assuming you have:
```
char string1[20];
char string1[20];
int intA;
```
you could do:
```
fscanf(file, "%19[^,],%19[^,],%d\n", string1, string2, &intA);
```
%[^,]reads a string of non-comma characters and stops at the first comma.19is the maximum number of characters to read (assuming a buffer size of 20) so that you don't have buffer overflows.
|
```
const int size = 10; // realna ilość danych
int tablica[size+1];
```
i have:variable-size type declared outside of any function
|
Use
```
#define size 10
```
instead of aconst int. The latter is not a compile-time constant in C, but a variable that cannot be assigned to (unless via a pointer and a cast to get rid ofconst).
(This is a difference between C and C++.)
|
In WINUSER.H, it defines WS_OVERLAPPEDWINDOW like this:
```
#define WS_OVERLAPPEDWINDOW (WS_OVERLAPPED | \
WS_CAPTION | \
WS_SYSMENU | \
WS_THICKFRAME | \
WS_MINIMIZEBOX | \
WS_MAXIMIZEBOX)
```
What I don't understand is, rather thanoperator |, what does| \do?
|
\as the LAST character of a line means "this line is not finished". It disappears from the preprocessed output.
Those lines are equivalent to:
```
#define WS_OVERLAPPEDWINDOW (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | ...
```
just a bit more readable.
|
I just readhttp://olstrans.sourceforge.net/release/OLS2000-ext3/OLS2000-ext3.htmlwhich is an excellent review of the design issues used when journaling was implemented in ext3. Could someone point me towards the section of the linux kernel code where ext3 journaling is implemented?
|
You can uselxrto search the linux code.
ext3 and journaling interface code ishereand JDB code ishere
|
This question already has answers here:Closed12 years ago.
Possible Duplicates:Query about working out whether number is a power of 2How to check if a number is a power of 2
I require a function body for this prototype:
```
bool isPOT(int x);
```
So it would return eg isPOT(3) = FALSE, but isPOT(8) = TRUE
What is the most pretty/concise algorithm? And what is the most efficient?
PS: I am amazed that I cannot find this question on SO, so I am fully expecting someone to detect some duplicate.
PPS: can someone please create POT, NPOT, Power-Of-Two tags?
|
```
bool IsPOT(int x)
{
return (x > 0) && ((x & (x - 1)) == 0);
}
```
|
Is the strtok function in standard C89?
|
the man page says:
```
CONFORMING TO
strtok()
SVr4, POSIX.1-2001, 4.3BSD, C89, C99.
strtok_r()
POSIX.1-2001.
```
So I would say yes.
According to the C89 draft I have (the actual standard costs money), the appropriate section is:
4.11 STRING HANDLING <string.h>4.11.5.8 The strtok function
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a book, tool, software library, tutorial or other off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.Closed9 years ago.Improve this question
I want to learn how C is interpreted,
anyone knows where to download it?
|
http://www.thefreecountry.com/compilers/cpp.shtml
I found that in about 10 seconds using Google. You can too.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed12 years ago.
I need to write a Linux shell for a school project. We can use C or C++. I am a little more comfortable with C++, and since I'm working with a partner, the object-oriented aspect of it is helpful. However, I suspect that for some reason C is better, and that most if not all Linux shells are written in C and not C++. What are the pros and cons of using one or the other?
|
the only difference I'd say is the dependency on libstd-c++ if you end up using STL and stuff. Plain C implementation if done correctly will run on bare minimum system requirements (libc only)
|
I'm working on a homework assignment that basically asks us to parse a DNS response to get the IP address and such. The problem is the professor has told us in great detail what the response looks like from the DNS server, but I don't know what to send the server. My first attempt was tonetcat <ip address of local name server> 53and just type in www.google.com and hit enter and look for a response but I didn't get anything back.
Can anyone describe to me what a DNS query looks like (like how many bytes are allowed for each part of the query)?
|
Download wireshark, and run itDo something that uses DNS (make sure you aren't using a cached hostname)Look through the wireshark packets that are captured.
|
In my app I use theJavaScriptCoreAPI to install a JS function in the WebView context with a C callback in my Cocoa class. Now there is no way I can pass that callback auserData/refconpointer to know what class the callback belongs to.
Is there a way to resolve this without passing a pointer? Globals don't seem to work since they get overwritten by other class instances.
|
If a global won't work (because of multiple / concurrent calls, most likely), then you need some kind of context info.
If the API returns any kind of a unique identifier -- session #, an allocated struct, anything -- you could set up an NSMapTable that maps between that identifier and whatever Objective-C goop you might need.
|
I've seen code where people initialize float variables like this:
```
float num = 0.0f;
```
Is there a significant difference between this and just doing the following below?
```
float num = 0;
```
Thanks.. :)
|
float x = 0has an implicit typecast from int to float.float x = 0.0fdoes not have such a typecast.float x = 0.0has an implicit typecast from double to float.
Depending on the compiler, implicit typecast can require the compiler to generate extra code.
|
I want to use theselect()function to wait for 1 second, as my program uses signals to control stuff, sosleep()would return prematurely. The weird thing is that when usingselect()it also returns prematurely.
I am calling select like this
```
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 1000000;
select (0 ,NULL, NULL, NULL, &timeout);
```
but whenever a signal arrives, it returns (I am using a nano second timer for the signal)
Anyone knows why?
|
Try something like this:
```
struct timespec timeout;
timeout.tv_sec = 10;
timeout.tv_nsec = 0;
while (nanosleep(&timeout, &timeout) && errno == EINTR);
```
The "remaining time" pointer tonanosleepwill take care of letting you restart the sleep with the necessary amount of remaining time if it gets interrupted.
|
math.h->cmath
stdlib.h->cstdlib
I understand the difference between the ".h" version and the "c-prefix" version, but what was the reason to choose to use the "c" prefix?
|
EDIT: Okay, we have some people who maybe didn't read the question carefully enough, or made assumptions on what the question meant or how answers were to be interpreted.
I'm answering the below question here:
but what was the reason to choose to use the "c" prefix?
To emphasize that it's originally from the C language, I presume.
|
My 2 main development environments are C, and Objective-C. With Clang and LLVM, using closures has become or is becoming a complete reality, called Blocks.. but they're still closures. I'm not concerned with the technical "how to"
What I want to know is, what are the best ways to design software to use Closures?
I know that you can do nice sorting things using them, but what other possibilities exist? I've seen ways to simplify program structure, but the topic is very heard to search on. I've never seen any exhaustive list or a good resource.
Bounty placed: a bounty answer will give a thorough list and specific examples for uses of blocks in C and Objective-C
|
For Blocks in Objective-C or C:
Programming with C BlocksUsing Objective-C Blocks
More on Closure/Blocks/Lambdas :
When to use closureWhy use closure
|
Is there any way to execute Linux commands with c without usingexeclp(), like predefined functions or something else.
Thanks.
|
Usesystem()orpopen()if you need the commands output.
|
There is a code snippet,
```
int matchhere(char *regexp, char *text)
{
/* do sth */
return *test== '\0';
}
```
I do not understand what does
```
return *test== '\0';
```
mean. Or what it will return? How does "==" function here?
|
compare*testto'\0', return 0 if inequal, return 1 if equal.
|
I want to know how I can write 64-bit values into memory in C. I'm doing embedded development and in order for something to function areas of memory must be initialized using 64-bit writes.
|
This should do it:
```
#include <stdint.h>
void write_64bit_zero_to(void *address)
{
*((uint64_t *) address) = 0;
}
```
if your platform doesn't providestdint.h, I'm sure it has something similiar as long as the architecture actually supports 64-bit integers (which, of course, you've said that it does). Seethis pagefor more talk about the type.
|
Is there easy way to create FILE* from WinApi HANDLE which points to one end of pipe?
Something like we do in unix:fdopen(fd,<mode>);
|
You can do this but you have to do it in two steps. First, call_open_osfhandle()to get a C run-time file descriptor from a Win32 HANDLE value, then call_fdopen()to get aFILE*object from the file descriptor.
|
I have following code:
```
typedef int (*t_Function) (int x);
t_Function Functions[MAX_FUNCTIONS];
int f(int x)
{
return 0;
}
```
But I cannot initialize it properly. If I add following line:
```
Functions[0] = f;
```
then compiler generates following error:
```
prog.c:217: warning: data definition has no type or storage class
prog.c:217: error: conflicting types for Functions
```
How to initialize this array of pointers to functions?
|
You should either do it inside a function, whereFunctions[0] = f;works fine, or with an array initializer:
```
t_Function Functions[MAX_FUNCTIONS] = {f};
```
For this to work,f(and all functions you want inFunctions) must have been declared at the point where this definition appears. Note that all otherMAX_FUNCTIONS-1elements ofFunctionswill beNULLautomatically if at least one of them is filled this way.
|
I am doing it wrong, yes?
```
...
if( you_think_youre_genius )
goto goto_sucks:
...
pthread_mutex_lock(&mutex);
do_stuff();
goto_sucks:
do_other_stuff();
pthread_mutex_unlock(&mutex);
```
|
Yes, goto is direct jmp down at the binary code level soanyfunction calls between the goto and the label will be skipped, period.
|
Why can't it be done like this?
```
#include<stdio.h>
#include<stdlib.h>
struct test
{
value z;
int x;
};
main()
{
enum value {a,b,c,d};
struct test come;
come.z = 2;
if (a == z) printf("they match ");
else printf("dont match");
}
```
|
Make the enum a typedef enum and place it above the struct.
```
#include <stdio.h>
#include <stdlib.h>
typedef enum { a,b,c,d } value;
struct test
{
value z;
int x;
};
int main()
{
struct test come;
come.z = 2;
if (a == come.z)
printf("they match ");
else
printf("dont match");
}
```
Edit: fixed some minor typos.
|
Does anyone know a function to get the hostname of the linux server? I don't really want to have to include any headers or compile other libraries, hoping there is a function built in by default. I'm new to c :)
|
likegethostname()?
That's the name of the machine on which your app is running.
Or read from
```
/proc/sys/kernel/hostname
```
Update
Simple example
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
char hostname[1024];
gethostname(hostname, 1024);
puts(hostname);
return EXIT_SUCCESS;
}
```
|
Hii ALL,
i am new to c and learing structure.I came across to one of structure declaration and have a doubt on its validation ...
```
struct a
{
int x;
struct a b;
}
```
is it fine to have such structure declaration and if not then why??
|
No. A structure cannot contain itself. This simply would not make any sense, since the resultant type will be infinitely large.
In other words, your structure includes an instance of itself, which in turn also includes an instance of itself, which in turn also includes an instance of itself, and so on and so forth ad infinitum...
Form the formal point of view, you are trying to declare a structure memberbthat hasincomplete type. It is illegal to declare struct members of incomplete type in C.
|
What should be the output of this following code snippet and why?
```
#include <stdio.h>
#include <string.h>
int main()
{
char ch = 'A';
char str[3];
strcpy(str, "ABCDE");
printf("%c", ch);
}
```
|
The output of this program could be anything because you overrun the bufferstrand get undefined behavior. In fact, the program might not output anything, it might crash, or it might do something far worse.
|
I have:
printf("%.2s\n", &s[2]);
How can I represent that as a chosen value?
So I would want something like:
printf(%.%is\n", someInt, &s[2]); #
but this doesnt work, where %i is someInt
|
You wantprintf("%.*s\n", someInt, &s[2]);. Consult theprintf man pagefor more details.
|
In C, how to remove all characters present in one array from another array?
|
Sounds like homework but here's a solution.
Make an array of 256 entries, likechar set[256].
Read the first string. For each charactercsetset[(unsigned char)c]to 1.
Read and copy the second string. For each charactercifset[c]then skipc.
I forgot and left out that you must firstmemset(set, 0, sizeof(set))before setting any of its values to 1.
|
So:
```
char *someCArray; # something
```
I want to print out "ethin" from "something".
|
You can use theprintfprecision specifier
```
#include <stdio.h>
int main(void) {
char s[] = "something";
int start = 3;
int len = 5;
printf("%.*s\n", len, s + start);
return 0;
}
```
Code also posted to codepad:http://codepad.org/q5rS81ox
|
Let's say I made a C program that is called like this:
```
./something -d dopt filename
```
So-dis a command,doptis an optional argument to-dandfilenameis an argument to./something, because I can also call./something filename.
What is thegetoptform to represent get the filename?
|
Use optstring"d:"
Capture-d doptwithoptargin the usual way. Then look atoptind(compare it withargc), which tells you whether there are any non-option arguments left. If so, your filename is the first of these.
getoptdoesn't specifically tell you what the non-option arguments are or check the number. It just tells you where they start (having first moved them to the end of the argument array, if you're in GNU's non-strict-POSIX mode)
|
Can anyone enlighten me as to why I should bother to specify the size of a C array argument in a function header? For example:
```
void foo (int iz[6]) { iz[42] = 43; }
```
With:
```
int is[2] = {1,2,3};
```
we get a useful error. Perhaps it helps with commenting/documentation?
|
Can anyone enlighten me as to why I should bother to specify the size of a C array argument in a function header? For example:void foo (const char sz[6]) { sz[42] = 43; }
IMO, you shouldn't. When you try to pass an array to a function, what's really passed is a pointer to the beginning of the array. Since what the function receives will be a pointer, it's better to write it to make that explicit:
```
void foo(char const *sz)
```
Then, since it's now clear that the function has been given no clue of the size, add that as a separate parameter:
```
void foo(char const *sz, size_t size)
```
|
I have a little utility I wrote in C that uses libpng. Under linux, I just install libpng-dev and do "gcc myapp.c /usr/lib/libpng.so -o myapp". In Mac OS X, I have the Xcode tools installed, which I believe includes libpng. What do I link against, and do I need to specify an include path for png.h?
|
Try /usr/X11/include/png.h - you'll find the libs in ../lib ( or /usr/X11/lib ) as well.
EDITMavericks doesn't appear to have this anymore. You may need to usehomebreworMacPortsto install libpng.
|
I am a newbie to C programming and was trying to prepare some sorting programs. I made the program of linear/ normal Sorting.
Now I want to make a program to sort 2D array.
i.e. If the matrix is
```
4 6 1
3 2 9
5 7 8
```
Then the result should be
```
1 2 3
4 5 6
7 8 9
```
|
Since you want your 2D array to be sorted row-wise, which happens to be the order in which multidimensional arrays are stored in C, you could pretend it is a 1D array and sort it that way.
Assuming you have a functionvoid sort(int[], int size);that takes a pointer to the first element of a 1D array and its size, you could do
```
int a[3][3] = {{4,6,1}, {3,2,9}, {5,7,8}};
sort(&a[0][0], 9);
```
Naturally, this only works for true 2D arrays, not for arrays of pointers, which is how dynamically allocated 2D arrays are often implemented in C.
|
I need function count_sprintf() that should returnnumber of characters (not inc nul byte) needed for the formatted buffer, on Win32 and on Linux.
```
int count_sprintf(const char *format, va_list ap);
```
There are subtle diffs beteen Win32 vs Linux in return value of vsnprintf when formatted value is longer than buffer size. That's why I ask for help.
Can you give portable code (#ifdef WIN32) for this function.
The function to be used like this:
```
int bufsize = 1 + count_snprintf(format, ap);
char *buf = (char*)malloc(bufsize);
vsnprintf(buf, bufsize, format, ap); // on WIN32, _vsnprint, on Linux, vsnprintf.
```
Thanks
|
The VS runtime has the _vscprintf which counts characters needed.
```
int count_sprintf(const char *format, va_list ap) {
#ifdef WIN32
return _vscprintf(format, ap);
#else
char c;
return vsnprintf(&c, 1, format, ap);
#endif
}
```
|
Why do local variables use Stack in C/C++?
|
Technically, C does not use a stack. If you look at theC99 standard, you'll find no reference to the stack. It's probably the same for the C++ standard, although I haven't checked it.
Stacks are just implementation details used by most compilers to implement the C automatic storage semantics.
|
I get input from command line as a int d. Now I am facing this problem:
```
float a,b;
int d;
float piece;
printf("Please enter the parts to divide the interval: ");
scanf("%d", &d);
a=0;
b=1;
piece=b-a/(float)d;
printf("%f\n",piece);
```
All I want is to printf some float number dependent on &d. e.g. when I write here 5, I would get 0.20000, for 6 - 0,166666 but I am still getting 1.000000 for all numbers, does anyone knows solution?
|
Division has precedence over subtraction, so you need to put the subtraction inside parentheses. You don't have to explicitly cast d to float; dividing a float by it will promote it to float.
```
piece = (b - a) / d;
```
|
How do I use regular expressions in GNU G++ / GCC for matching, searching and replacing substrings? E.g. could you provide anytutorialonregex_tand others?
Googling for above an hour gave me no understandable tutorial or manual.
|
I strongly suggest using theBoostC++ regex library. If you are developing serious C++, Boost is definitely something you must take into account.
The library supports both Perl and POSIX regular expression syntax. I personally prefer Perl regular expressions since I believe they are more intuitive and easier to get right.
http://www.boost.org/doc/libs/1_46_0/libs/regex/doc/html/boost_regex/syntax.html
But if you don't have any knowledge of this fine library, I suggest you start here:
http://www.boost.org/doc/libs/1_46_0/libs/regex/doc/html/index.html
|
My 2 main development environments are C, and Objective-C. With Clang and LLVM, using closures has become or is becoming a complete reality, called Blocks.. but they're still closures. I'm not concerned with the technical "how to"
What I want to know is, what are the best ways to design software to use Closures?
I know that you can do nice sorting things using them, but what other possibilities exist? I've seen ways to simplify program structure, but the topic is very heard to search on. I've never seen any exhaustive list or a good resource.
Bounty placed: a bounty answer will give a thorough list and specific examples for uses of blocks in C and Objective-C
|
For Blocks in Objective-C or C:
Programming with C BlocksUsing Objective-C Blocks
More on Closure/Blocks/Lambdas :
When to use closureWhy use closure
|
Is there any way to execute Linux commands with c without usingexeclp(), like predefined functions or something else.
Thanks.
|
Usesystem()orpopen()if you need the commands output.
|
There is a code snippet,
```
int matchhere(char *regexp, char *text)
{
/* do sth */
return *test== '\0';
}
```
I do not understand what does
```
return *test== '\0';
```
mean. Or what it will return? How does "==" function here?
|
compare*testto'\0', return 0 if inequal, return 1 if equal.
|
I want to know how I can write 64-bit values into memory in C. I'm doing embedded development and in order for something to function areas of memory must be initialized using 64-bit writes.
|
This should do it:
```
#include <stdint.h>
void write_64bit_zero_to(void *address)
{
*((uint64_t *) address) = 0;
}
```
if your platform doesn't providestdint.h, I'm sure it has something similiar as long as the architecture actually supports 64-bit integers (which, of course, you've said that it does). Seethis pagefor more talk about the type.
|
Is there easy way to create FILE* from WinApi HANDLE which points to one end of pipe?
Something like we do in unix:fdopen(fd,<mode>);
|
You can do this but you have to do it in two steps. First, call_open_osfhandle()to get a C run-time file descriptor from a Win32 HANDLE value, then call_fdopen()to get aFILE*object from the file descriptor.
|
I have following code:
```
typedef int (*t_Function) (int x);
t_Function Functions[MAX_FUNCTIONS];
int f(int x)
{
return 0;
}
```
But I cannot initialize it properly. If I add following line:
```
Functions[0] = f;
```
then compiler generates following error:
```
prog.c:217: warning: data definition has no type or storage class
prog.c:217: error: conflicting types for Functions
```
How to initialize this array of pointers to functions?
|
You should either do it inside a function, whereFunctions[0] = f;works fine, or with an array initializer:
```
t_Function Functions[MAX_FUNCTIONS] = {f};
```
For this to work,f(and all functions you want inFunctions) must have been declared at the point where this definition appears. Note that all otherMAX_FUNCTIONS-1elements ofFunctionswill beNULLautomatically if at least one of them is filled this way.
|
I am doing it wrong, yes?
```
...
if( you_think_youre_genius )
goto goto_sucks:
...
pthread_mutex_lock(&mutex);
do_stuff();
goto_sucks:
do_other_stuff();
pthread_mutex_unlock(&mutex);
```
|
Yes, goto is direct jmp down at the binary code level soanyfunction calls between the goto and the label will be skipped, period.
|
Why can't it be done like this?
```
#include<stdio.h>
#include<stdlib.h>
struct test
{
value z;
int x;
};
main()
{
enum value {a,b,c,d};
struct test come;
come.z = 2;
if (a == z) printf("they match ");
else printf("dont match");
}
```
|
Make the enum a typedef enum and place it above the struct.
```
#include <stdio.h>
#include <stdlib.h>
typedef enum { a,b,c,d } value;
struct test
{
value z;
int x;
};
int main()
{
struct test come;
come.z = 2;
if (a == come.z)
printf("they match ");
else
printf("dont match");
}
```
Edit: fixed some minor typos.
|
Does anyone know a function to get the hostname of the linux server? I don't really want to have to include any headers or compile other libraries, hoping there is a function built in by default. I'm new to c :)
|
likegethostname()?
That's the name of the machine on which your app is running.
Or read from
```
/proc/sys/kernel/hostname
```
Update
Simple example
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
char hostname[1024];
gethostname(hostname, 1024);
puts(hostname);
return EXIT_SUCCESS;
}
```
|
Hii ALL,
i am new to c and learing structure.I came across to one of structure declaration and have a doubt on its validation ...
```
struct a
{
int x;
struct a b;
}
```
is it fine to have such structure declaration and if not then why??
|
No. A structure cannot contain itself. This simply would not make any sense, since the resultant type will be infinitely large.
In other words, your structure includes an instance of itself, which in turn also includes an instance of itself, which in turn also includes an instance of itself, and so on and so forth ad infinitum...
Form the formal point of view, you are trying to declare a structure memberbthat hasincomplete type. It is illegal to declare struct members of incomplete type in C.
|
What should be the output of this following code snippet and why?
```
#include <stdio.h>
#include <string.h>
int main()
{
char ch = 'A';
char str[3];
strcpy(str, "ABCDE");
printf("%c", ch);
}
```
|
The output of this program could be anything because you overrun the bufferstrand get undefined behavior. In fact, the program might not output anything, it might crash, or it might do something far worse.
|
I have:
printf("%.2s\n", &s[2]);
How can I represent that as a chosen value?
So I would want something like:
printf(%.%is\n", someInt, &s[2]); #
but this doesnt work, where %i is someInt
|
You wantprintf("%.*s\n", someInt, &s[2]);. Consult theprintf man pagefor more details.
|
In C, how to remove all characters present in one array from another array?
|
Sounds like homework but here's a solution.
Make an array of 256 entries, likechar set[256].
Read the first string. For each charactercsetset[(unsigned char)c]to 1.
Read and copy the second string. For each charactercifset[c]then skipc.
I forgot and left out that you must firstmemset(set, 0, sizeof(set))before setting any of its values to 1.
|
So:
```
char *someCArray; # something
```
I want to print out "ethin" from "something".
|
You can use theprintfprecision specifier
```
#include <stdio.h>
int main(void) {
char s[] = "something";
int start = 3;
int len = 5;
printf("%.*s\n", len, s + start);
return 0;
}
```
Code also posted to codepad:http://codepad.org/q5rS81ox
|
Let's say I made a C program that is called like this:
```
./something -d dopt filename
```
So-dis a command,doptis an optional argument to-dandfilenameis an argument to./something, because I can also call./something filename.
What is thegetoptform to represent get the filename?
|
Use optstring"d:"
Capture-d doptwithoptargin the usual way. Then look atoptind(compare it withargc), which tells you whether there are any non-option arguments left. If so, your filename is the first of these.
getoptdoesn't specifically tell you what the non-option arguments are or check the number. It just tells you where they start (having first moved them to the end of the argument array, if you're in GNU's non-strict-POSIX mode)
|
How do I use regular expressions in GNU G++ / GCC for matching, searching and replacing substrings? E.g. could you provide anytutorialonregex_tand others?
Googling for above an hour gave me no understandable tutorial or manual.
|
I strongly suggest using theBoostC++ regex library. If you are developing serious C++, Boost is definitely something you must take into account.
The library supports both Perl and POSIX regular expression syntax. I personally prefer Perl regular expressions since I believe they are more intuitive and easier to get right.
http://www.boost.org/doc/libs/1_46_0/libs/regex/doc/html/boost_regex/syntax.html
But if you don't have any knowledge of this fine library, I suggest you start here:
http://www.boost.org/doc/libs/1_46_0/libs/regex/doc/html/index.html
|
hi every one i have an array
21 44 56 777
i am using strtok function to seperate them on the basis of space
```
int i;
char *token;
token = strtok(payload1, " ");
printf ( "\n\n\nTOKEN %s" , token);
```
i works fine that is it displayed 21.
now i want display 44 using the same variable token how to do that
thanks kindly help me
|
You will need to repeatedly apply strtok.
```
token = strtok(payload1, " ");
while ( token != NULL)
{
token = strtok(NULL, " ");
// do your stuffs
}
```
|
Given the decimal71744474in binary it is0100010001101011101111011010what I am trying to extract from this decimal is every seven bits starting from the lower bits. Each of the seven bits are to represent a printable ASCII character which can only have 7 bits. In total I am pulling out four characters. The first character is1011010which isZin ASCII. The next character iswand so on. I am thinking there is a way to mask out the bits I care about some how.
|
Use bitwise operators:
```
0100010001101011101111011010 & 0000000000000000000001111111 = 1011010
```
To get the second character, do
```
0100010001101011101111011010 & 0000000000000011111110000000
```
and so on..
|
Let us say that cmd1 print something on stdout. How can I capture it with cmd1 in C such that cmd1 | cmd2 works.
i.e
```
cmd1{
fprintf(stdout, "Hello");
}
cmd2 : should take "hello" and only print "hel".
```
|
To enable pipeline operation, cmd2 should read fromstdin.
For example, sincefgets()reads fromstdin, you can do something like:
```
#include <stdio.h>
int main() {
char buf[1024];
while (fgets(buf, sizeof(buf), stdin)) {
printf("%.*s\n", 3, buf);
}
return 0;
}
```
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:What is the point of function pointers?
I just read about pointers to function in K+R. I understand how these pointers work, but I don't see the utility for they. What's the use for this type of pointers in programming?
|
You can use function pointers for a variety of tasks such as registering factories, applying an algorithm on a data structure (e.g. sorting a list using a user-defined sort function). There are a few other uses but essentially you need them for inversion of control: let someone else call back into your code, and you do this by providing a pointer to the function.
|
I am learning C language. In the book, it says:
"initialize a variable when declaring it only if the initial value is part of the semantic of the variable. If the initial value is part of an algorithm, use a separate assignment statement. For example, instead of
```
int price = units * UNIT_PRICE;
int gst = price * GST;
```
Write
```
int price, gst;
price = units * UNIT_PRICE;
gst = price * GST;
```
I do not understand why we should do that? What are the reasons behind it?
|
This is really just a matter of programming style. What the author is probably saying is that separating the declaration from a normal assignment makes the code cleaner and easier to understand at a glance. If, on the otherhand, the initial assignment is part of the meaning of the variable, then it's ok to combine declaration and definition. An example of this might be an int with a boolean value such asint AnExceptionHasOccurred = FALSE.
|
I have the following line of code:
```
contents[pos++] ^= key[shift++];
```
What does operator^=mean?
|
It is theXORassignment operator. Basically:
```
x ^= y;
```
is the same as:
```
x = x ^ y;
```
|
I am coding in C and running the programs in a Linux terminal. I want to save the output of the program in a .txt file. I usually do this by executing./a.out>filename.txt
But I have written an interactive program in which I have to enter a number to initiate the program. In that case how do I do it?
Thanks a lot and your valuable suggestions are most welcomed.
|
Move the requirement to enter a number from the terminal to a command line parameter.
```
./a.out 42 > filename.txt
```
Or, easier, accept the input from a redirected input
```
echo 42 | ./a.out > filename.txt
./a.out < input.txt > filename.txt
```
|
I'm trying to generate a random number that's between 0 and 1. I keep reading aboutarc4random(), but there isn't any information about getting a float from it. How do I do this?
|
Random value in[0, 1[(including 0, excluding 1):
```
double val = ((double)arc4random() / UINT32_MAX);
```
A bit more detailshere.
Actual range is[0, 0.999999999767169356], as upper bound is (double)0xFFFFFFFF / 0x100000000.
|
I need to form a string, inside each iteration of the loop, which contains the loop indexi:
```
for(i=0;i<100;i++) {
// Shown in java-like code which I need working in c!
String prefix = "pre_";
String suffix = "_suff";
// This is the string I need formed:
// e.g. "pre_3_suff"
String result = prefix + i + suffix;
}
```
I tried using various combinations ofstrcatanditoawith no luck.
|
Strings are hard work in C.
```
#include <stdio.h>
int main()
{
int i;
char buf[12];
for (i = 0; i < 100; i++) {
snprintf(buf, 12, "pre_%d_suff", i); // puts string into buffer
printf("%s\n", buf); // outputs so you can see it
}
}
```
The12is enough bytes to store the text"pre_", the text"_suff", a string of up to two characters ("99") and the NULL terminator that goes on the end of C string buffers.
Thiswill tell you how to usesnprintf, but I suggest a good C book!
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:How to create a Singleton in C ?
Hello, if I have astructuredefinition as follows:
```
struct singleton
{
char sharedData[256];
};
```
Can I impose the singleton pattern on instance variables of the abovestructurein C [not in C++]?
|
If you just forward declare yourstructin the header file, it will be impossible for clients to create an instance of it. Then you can provide a getter function for your single instance.
Something like this:
.h:
```
#ifndef FOO_H
#define FOO_H
struct singleton;
struct singleton* get_instance();
#endif
```
.c:
```
struct singleton
{
char sharedData[256];
};
struct singleton* get_instance()
{
static struct singleton* instance = NULL;
if (instance == NULL)
{
//do initialization here
}
return instance;
}
```
|
I'm porting code from Linux C to Visual C++ for windows.
Visual C++ doesn't know#include <stdint.h>so I commented it out.
Later, I found a lot of those'uint32_t': identifier not founderrors. How can it be solved?
|
This type is defined in the C header<stdint.h>which is part of the C++11 standard but not standard in C++03. According tothe Wikipedia page on the header, it hasn't shipped with Visual Studio until VS2010.
In the meantime, you could probably fake up your own version of the header by addingtypedefs that mapMicrosoft's custom integer typesto the types expected by C. For example:
```
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
/* ... etc. ... */
```
|
I'm an intern student and my boss told me to do porting from Linux c to Visual C++.
When I built the coding, I found this error "unexpected in macro formal parameter list", here is the code
```
#define cache_info(format, msg...)
do { \
;\
} while (0)
```
I don't know what is wrong and what the coding is for .
I can't also ask the Linux programmer since he is out. Can someone help me ???
|
Sounds like your version of Visual C++ doesn't support variadic macros.
you might need to try something like this to get it to work.
```
#define FUNC(foo) ThisFunc foo
void ThisFunc(int, ...);
int main()
{
FUNC((123, 456));
}
```
or you could just be missing a comma?....
```
#define cache_info(format, msg,...)
```
|
I'm reading from a text file which contains:
```
Mary 55334422 24.90 56.6 45.68
```
and am reading it in:
```
....char name[20]; int num; double worked; double rate; double total;....
fscanf(fp, "%s %d %f %f %f\n", name, &num, &worked, &rate, &total);
```
I'm getting the name and the integer fine, but the floating point numbers come out something like -9522999990000000000000000000.00
Am I doing something wrong here?
|
You need to use theformat for a double:%lf, rather than that for a float%f... or change to floats instead of doubles.
|
Do anyone know of a general algorithm to detect memory leak?
|
Memory Leak Analysis by Contradiction
http://www.cs.cornell.edu/~rugina/papers/sas06.pdf
And less relevantly...
Apple dev docs have an article on the topic also (specific)...
http://developer.apple.com/library/mac/#documentation/Performance/Conceptual/ManagingMemory/Articles/FindingLeaks.html
and on tracking memory usage generally (also specific)...
http://developer.apple.com/library/mac/#documentation/Performance/Conceptual/ManagingMemory/Articles/FindingPatterns.html#//apple_ref/doc/uid/20001882-CJBJFIDD
|
this is an integer array:
```
int values[] = { 75, '*', 5,'-' };
for(i=0 ; i<size ; i++){
// Here
}
```
how to check if thevalues[i]is an integer or an operation ??
maybe the value equals the Ascii of an operation,, how to deal with it in this case??
|
You can't. As for as the compiler is concerned, the constants42an'*'are one and the same. In the compiled object code, they're both represented as the integer 42.
If you need to differentiate between integers and characters, either use a boolean flag or enum indicating the type of the value, or keep your integers and characters in separate arrays.
Note that in C++, butnotin C, there is a slight difference:42has the typeint, whereas'*'has the typechar, so you can differentiate this fact using overloaded functions or templates.
|
I am implementing in C on Windows : A channel of communication between a sender and a receiver.
The channel has to receive packages from sender, transfer them to the receiver and then back from receiver to the sender.
The Channel connects to sender (maybe multiple senders) on port 1 and connects to the receiver on port 2
What is a good way of doing it? Both ports 1 and 2 have to be able to send and receive. how to I use select in such situation?
I want to use a single threaded environment.
|
Not sure either about your exact question, but indeed TCP sockets are bidirectional.
You can put the same file descriptor in both the read and write (and except) FD_SETs in the same select call.
|
I am looking over some code someone else did and I see this:
```
if (numDetects == 0) {
Table[Index].minF =
Table[Index].maxF = F;
}
```
The Table[Index].minF = blank does not make any sense to me. I've never seen this in my life. BUT the code does compile and run, so could someone explain to me if this is possible or not to just have a equal sign left hanging there? Thanks!
|
Yes; C doesn't care about the white space between the first line and the second, so it sees it as
```
Table[Index].minF = Table[Index].maxF = F;
```
It's syntactically equivalent to
```
Table[Index].minF = (Table[Index].maxF = F);
```
since the assignment operator=not only assigns the left-hand side to the right-hand side, but also returns the value that was assigned. In this case, that return value is then in turn assigned to the outer left-hand side.
|
i have a program with queues using linked lists.when i compile it, it has the following error:
expected ‘)’ before ‘*’ token >>in error_line
```
///USEFUL PART OF THE PROGRAM
//queue struct
typedef struct{
int embros,piso,adeia;
int pinakas[PLITHOS];
}Q;
int main(){
Q oura_apo; //define a new queue
dimiourgia(&oura_apo);//create the new queue
return 0;
}
//this function creates a new empty list
void dimiourgia(Q *oura){ //this is error_line
oura->embros=0;
oura->piso=0;
}
```
|
You should put the definition of thedimiougiafunction in between the struct declaration and main. Otherwise, you need a preceding declaration:
```
void dimiourgia(Q *oura);
```
It is not very clear where the error can happen in your program, however, that error message is typically obtained when the structure Q is not recognized.
|
Normally, if my code has any performance issue, I will follow the below steps to understand the cause.
top command to see cpu's usagefree command to see memory usageadd timing information to the codeprint progress statements in the codeunderstand and improve the algorithm
What do you do, if your code is running very slow.
|
1) with a profiler, spot the slowest part of your code2) once you've found them, think of a way to improve themstep 2 is the most difficult. You could need some small changes or rewrite everything
|
What would be the best (fastest) way to parse through a mmap-ed file? It contains pairs of data (string int), but I cannot persume number of whitespaces/tabs/newlines between them.
|
Assuming you've mmaped the whole file in (rather than chunks - as that would make life awefully complicated), I'd do something like the following...
```
// Effectively this wraps the mmaped block
std::istringstream str;
str.rdbuf()->pubsetbuf(<pointer to start of mmaped block>, <size of mmaped block>);
std::string sv;
std::string iv;
while(str >> sv >> iv)
{
// do stuff...
}
```
I think that should work...
WARNINGThis is implementation defined behaviour, seethis answerfor an altogether better approach.
|
```
for (row=0; row<8; row++)
{
for (col=0; col<8; col++)
{
answer+=my_data[row][col];
}
printf("The sum of row %i is: %i\n", row,answer);
answer = 0;//to reset answer back to zero for next row sum
}
```
I have an 8x8 array and I'm adding each row and resetting the answer back to zero so you get the exact answer for each row. However it's not working... What is wrong?
|
How isanswerdeclared ?
If it is declared without an initial value then your existing code will fail asanswerwill have junk value for 1st row. To fix this :
```
for (row=0; row<8; row++) {
answer = 0; // clear the running sum.
for (col=0; col<8; col++) {
answer+=my_data[row][col];
}
printf("The sum of row %i is: %i\n", row,answer);
}
```
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:Datatypes used in C
Hi
I'm doing porting from Linux to Visual C ++. And I found quite a few errors.
What is u_int32_t ?
I can't find it in Visual C ++? Is it only available in Linux? Which type should I use in Visual C++?
Thanks in advance !!!
Kevin
|
The C99 headerstdint.hdefines types that do not depend on architecture or compiler. The meaning of unsigned int can differ (e.g. 16bit wide on a 16bit system), but those types fromstdint.hhave a specific size.
Either the additional underscore accidentally slipped in there, or someone re-typed them for some library or whatever. If the latter one is the case, include some header of your own, in that header includestdint.hand make sure totypedef uint32_t u_int32_tafter the include.
|
I'm porting code from Linux C to Visual C++ for windows.
Visual C++ doesn't know#include <stdint.h>so I commented it out.
Later, I found a lot of those'uint32_t': identifier not founderrors. How can it be solved?
|
This type is defined in the C header<stdint.h>which is part of the C++11 standard but not standard in C++03. According tothe Wikipedia page on the header, it hasn't shipped with Visual Studio until VS2010.
In the meantime, you could probably fake up your own version of the header by addingtypedefs that mapMicrosoft's custom integer typesto the types expected by C. For example:
```
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
/* ... etc. ... */
```
|
I'm an intern student and my boss told me to do porting from Linux c to Visual C++.
When I built the coding, I found this error "unexpected in macro formal parameter list", here is the code
```
#define cache_info(format, msg...)
do { \
;\
} while (0)
```
I don't know what is wrong and what the coding is for .
I can't also ask the Linux programmer since he is out. Can someone help me ???
|
Sounds like your version of Visual C++ doesn't support variadic macros.
you might need to try something like this to get it to work.
```
#define FUNC(foo) ThisFunc foo
void ThisFunc(int, ...);
int main()
{
FUNC((123, 456));
}
```
or you could just be missing a comma?....
```
#define cache_info(format, msg,...)
```
|
I'm reading from a text file which contains:
```
Mary 55334422 24.90 56.6 45.68
```
and am reading it in:
```
....char name[20]; int num; double worked; double rate; double total;....
fscanf(fp, "%s %d %f %f %f\n", name, &num, &worked, &rate, &total);
```
I'm getting the name and the integer fine, but the floating point numbers come out something like -9522999990000000000000000000.00
Am I doing something wrong here?
|
You need to use theformat for a double:%lf, rather than that for a float%f... or change to floats instead of doubles.
|
Do anyone know of a general algorithm to detect memory leak?
|
Memory Leak Analysis by Contradiction
http://www.cs.cornell.edu/~rugina/papers/sas06.pdf
And less relevantly...
Apple dev docs have an article on the topic also (specific)...
http://developer.apple.com/library/mac/#documentation/Performance/Conceptual/ManagingMemory/Articles/FindingLeaks.html
and on tracking memory usage generally (also specific)...
http://developer.apple.com/library/mac/#documentation/Performance/Conceptual/ManagingMemory/Articles/FindingPatterns.html#//apple_ref/doc/uid/20001882-CJBJFIDD
|
this is an integer array:
```
int values[] = { 75, '*', 5,'-' };
for(i=0 ; i<size ; i++){
// Here
}
```
how to check if thevalues[i]is an integer or an operation ??
maybe the value equals the Ascii of an operation,, how to deal with it in this case??
|
You can't. As for as the compiler is concerned, the constants42an'*'are one and the same. In the compiled object code, they're both represented as the integer 42.
If you need to differentiate between integers and characters, either use a boolean flag or enum indicating the type of the value, or keep your integers and characters in separate arrays.
Note that in C++, butnotin C, there is a slight difference:42has the typeint, whereas'*'has the typechar, so you can differentiate this fact using overloaded functions or templates.
|
I am implementing in C on Windows : A channel of communication between a sender and a receiver.
The channel has to receive packages from sender, transfer them to the receiver and then back from receiver to the sender.
The Channel connects to sender (maybe multiple senders) on port 1 and connects to the receiver on port 2
What is a good way of doing it? Both ports 1 and 2 have to be able to send and receive. how to I use select in such situation?
I want to use a single threaded environment.
|
Not sure either about your exact question, but indeed TCP sockets are bidirectional.
You can put the same file descriptor in both the read and write (and except) FD_SETs in the same select call.
|
I am looking over some code someone else did and I see this:
```
if (numDetects == 0) {
Table[Index].minF =
Table[Index].maxF = F;
}
```
The Table[Index].minF = blank does not make any sense to me. I've never seen this in my life. BUT the code does compile and run, so could someone explain to me if this is possible or not to just have a equal sign left hanging there? Thanks!
|
Yes; C doesn't care about the white space between the first line and the second, so it sees it as
```
Table[Index].minF = Table[Index].maxF = F;
```
It's syntactically equivalent to
```
Table[Index].minF = (Table[Index].maxF = F);
```
since the assignment operator=not only assigns the left-hand side to the right-hand side, but also returns the value that was assigned. In this case, that return value is then in turn assigned to the outer left-hand side.
|
i have a program with queues using linked lists.when i compile it, it has the following error:
expected ‘)’ before ‘*’ token >>in error_line
```
///USEFUL PART OF THE PROGRAM
//queue struct
typedef struct{
int embros,piso,adeia;
int pinakas[PLITHOS];
}Q;
int main(){
Q oura_apo; //define a new queue
dimiourgia(&oura_apo);//create the new queue
return 0;
}
//this function creates a new empty list
void dimiourgia(Q *oura){ //this is error_line
oura->embros=0;
oura->piso=0;
}
```
|
You should put the definition of thedimiougiafunction in between the struct declaration and main. Otherwise, you need a preceding declaration:
```
void dimiourgia(Q *oura);
```
It is not very clear where the error can happen in your program, however, that error message is typically obtained when the structure Q is not recognized.
|
Normally, if my code has any performance issue, I will follow the below steps to understand the cause.
top command to see cpu's usagefree command to see memory usageadd timing information to the codeprint progress statements in the codeunderstand and improve the algorithm
What do you do, if your code is running very slow.
|
1) with a profiler, spot the slowest part of your code2) once you've found them, think of a way to improve themstep 2 is the most difficult. You could need some small changes or rewrite everything
|
What would be the best (fastest) way to parse through a mmap-ed file? It contains pairs of data (string int), but I cannot persume number of whitespaces/tabs/newlines between them.
|
Assuming you've mmaped the whole file in (rather than chunks - as that would make life awefully complicated), I'd do something like the following...
```
// Effectively this wraps the mmaped block
std::istringstream str;
str.rdbuf()->pubsetbuf(<pointer to start of mmaped block>, <size of mmaped block>);
std::string sv;
std::string iv;
while(str >> sv >> iv)
{
// do stuff...
}
```
I think that should work...
WARNINGThis is implementation defined behaviour, seethis answerfor an altogether better approach.
|
Is it possible to write a#definethat defines a#define?
For example:
```
#define FID_STRS(x) #x
#define FID_STRE(x) FID_STRS(x)
#define FID_DECL(n, v) static int FIDN_##n = v;static const char *FIDS_##n = FID_STRE(v)
```
But instead:
```
#define FID_DECL2(n, v) #define FIDN_##n v \
FIDS_##n FID_STRE(v)
```
FID_DECLworks fine but creates two static variables. Is it possible to makeFID_DECL2work and having define two defines?
|
No; preprocessing is performed in a single pass. If you want or need more advanced behavior, consider using another tool to preprocess the source, like m4.
Further, the#in the replacement list (at the beginning of#define FIDN...would be parsed as the#(stringize) operator: the operand of this operator must be a named macro parameter, whichdefineis not.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed5 years ago.Improve this question
Is there a C API function that will give me the number of CPUs/cores on Mac OS X? Ideally, it should be something that just works across all flavors of OS X. (I really know nothing about Mac OS. This is for a library I'm working on that needs to support OS X.)
|
You can usesysctlbyname()with e.g.machdep.cpu.core_count. Do asysctl -afrom the command line to see what might be useful to you.
|
The code confused me.
```
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
void create_int(int *p)
{
p = (int *) malloc(sizeof(int));
}
int main()
{
int *p = NULL;
create_int(p);
assert(p != NULL); /* failed. why? I've allocated memory for it. */
return 0;
}
```
|
You are not passing the pointer value back from the function. Try:
```
void create_int(int **p) {
*p = (int *) malloc(sizeof(int));
}
int main() {
int *p = NULL;
create_int(&p);
assert(p != NULL); /* failed. why? I've allocated memory for it. */
return 0;
}
```
|
I want write program which creates child process and redirecting its stdout and stderr streams to parent. So what is good choice to do this for good performance tmpfile() or pipe(), and why?
|
Usepipewhere possible, unless you expect large amounts of input to build up in the stream without being read. A pipe keeps data in RAM where a temporary file requires filesystem operations. Anfdsyncon a file will be much more expensive than on a pipe. A pipe is also less vulnerable to security issues caused by race conditions.
If your application cannot use pipe semantics (requires a filesystem path for its output or a similar problem), try using a "named pipe" (also called a FIFO).
|
I'm building a J2EE project, in which I would like to use an API which is only available in C.
I was thinking of using JNI to do so, but after a quick look atthis tutorial, it looks that I in order to use JNI, I need to have the source code (.c files) to compile some kind of "JNI library".
In my case, the API only comports the .h with the signature of all the methods, and the already compiled .dll (or .so).
How could I do this?
Thank you!
|
JNAis a JNI-based library that allows calling normal C functions without needing a JNI-specific wrapper for each one.
|
I'm developing an NPAPI plugin for Mac OS X, and need an Open/Save dialog at various times. Accessing the window directly fails, since plugins are now run out-of-process... but Apple's documentation makes vague references to being able to launch dialogs and other things via provided APIs.
Can anyone shed light on how I might do something like launch an Open dialog, a modal sheet if possible? I was developing this as a WebKit Cocoa plugin for Safari but as of Mac OS X Lion they're now deprecated.
|
You can't open a modal sheet, because you have no reference to the browser window; it's impossible to get one across processes.
You can open an open/save dialog as a modal dialog using standard calls like-[NSSavePanel runModal], since you don't need any window references for that. The browser will take care of managing the process activation so that the dialog ends up in front of the browser.
|
Is there a way to count the number of lines in my file using C?
|
If you want to perform this programmatically, open the file in text mode and perform fgetc() operation until you reach end of file. Keep a count of number of times fgetc was called.
```
FILE *fp = fopen("myfile.txt");
int ch;
int count=0;
do
{
ch = fgetc(fp);
if(ch == '\n') count++;
} while( ch != EOF );
printf("Total number of lines %d\n",count);
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.