question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I'm using an open source library which seems to have lots of preprocessing directives to support many languages other than C. So that I can study what the library is doing I'd like to see the C code that I'm compiling after preprocessing, more like what I'd write.
Can gcc (or any other tool commonly available in Linux) read this library but output C code that has the preprocessing converted to whatever and is also readable by a human?
|
Yes. Pass gcc the-Eoption. This will output preprocessed source code.
|
I just saw the signature forprintf. it isint printf(const *f). Now, if I declare anint iand do the following:
```
int i=5;
printf("%d",i);
```
it displays the correct value ofi. I am wondering why is is this so. Sinceprintfaccepts a pointer, should it not treat the value ofias an address and print the value stored at that address.
Note thatprintf("%d", &i)does not work.
|
printf()is avariadic function. That means that its first argument indicates the number and type of remaining arguments to be pulled from the stack.
The first argument - and the only one that is not affected by the function being variadic - is astringand therefore a pointer (to an array ofchar, if it matters). The remaining arguments are processed differently and are not listed in the simplistic prototype that you mentioned.
BTW, here's the full prototype ofprintf()as pulled from mystdio.hheader:
```
extern int printf (const char *format, ...);
```
|
Is there any specific reason why has support for designated initializers not been added to g++? Is the reason that C99 standards came late and g++ was developed earlier and later people didn't care about this issue, or there is some inherent difficulty in implementing designated initializers in the grammar of C++?
|
I ran into this same problem today. g++ with -std=c++11 and c++14 does support designated initializers, but you can still get a compilation error "test.cxx:78:9: sorry, unimplemented: non-trivial designated initializers not supported" if you don't initialize the struct in the order in which it's members have been defined. As an example
```
struct x
{
int a;
int b;
};
// This is correct
struct x x_1 = {.a = 1, .b = 2};
// This will fail to compile with error non-trivial designated initializer
struct x x_2 = {.b = 1, .a = 2};
```
|
I have two integers (amount of bytes of two files). One is always smaller if not the same than the other. I want to calculate the percentage that the smaller is of the bigger.
I'm using plain C. I've applied the math formula, but am getting always 0:
```
printf("%d\r", (current/total)*100);
```
Any ideas?
|
Try
```
printf("%g\r", (((double)current)/total)*100);
```
instead. Integer division always rounds towards zero. By converting one of the numbers todoublefirst, you will trigger floating point division. If you would like to use integer arithmetic, you could also use
```
printf("%d\r", (100*current)/total);
```
which will print the percentage rounded down to the next integer.
|
I am looking for a prototype or implementation for a queueing/scheduling system with dependencies between the individual tasks. To be more specific:
task_0, task_1, task_2, ... task 10 arrive at the queue. Tasks are http requests.
I want to send task_2 only if task_0 is completed. task_1 can be sent without expecting
task_1 to complete but task_2 has to wait.
Ideas? Models that already exist and match this description?
|
The queue can be topologically sorted.
http://en.wikipedia.org/wiki/Topological_sorting
http://www.cs.sunysb.edu/~algorith/files/topological-sorting.shtml
|
This might be a very broad question. But this is what i want. I open a website and enter some details in the website like my credentials to login or it may be any data that pass from my browser to the website. Now what i want is that i should cache ( write to a temp file ) whatever that i send to that website. How can this be done? I tried to extract the data present in the packets that are flowing out of my machine but i find only junk characters in that (may be header). any ideas are welcomed. I am using Ubuntu Linux and would like to achieve this using shell script/C/C++
|
One option would be to use the Fiddler Web Debugger which is scriptable (C#).
Although it's a Win32 program, it can act as a proxy for any Linux machine. SeeDebug traffic from another machine (even a Mac or Unix box)for details.
There's also a native Linux app calleddsniffwhich can be used to log all HTTP traffic to a file.
|
I am compiling this C program and comparing the generated assembly code:
```
int main(){ return 0; }
```
GCCgives this main function (cc hello.c -S):
```
_main:
LFB2:
pushq %rbp
LCFI0:
movq %rsp, %rbp
LCFI1:
movl $0, %eax
leave
ret
```
LLVMgives this main function (clang hello.c -S):
```
_main:
Leh_func_begin0:
pushq %rbp
Ltmp0:
movq %rsp, %rbp
Ltmp1:
movl $0, %eax
movl $0, -4(%rbp)
popq %rbp
ret
Leh_func_end0:
```
What aremovl $0, -4(%rbp)andpopq %rbpneeded for? Moving something on the stack and popping it directly afterwards seems useless to me.
|
Themovl $0, -4(%rbp)instruction is dead, because this is unoptimized code. Try passing in-Oto both compilers to see what changes.
|
I am making an app that needs to check if certain apps are installed with a given identifier.
Is there a way to do this without private symbols and without a jailbreak?
Thanks.
|
Bumpdeveloper gives a hint of how they do iton their blog(see comment at the bottom):
Q: […] How do you check wich
applications the end-user have
installed? I thought that apple didn't
aprove apps that do that..A: […] There's not a simple way to
detect which apps are installed. We
use a combination of several methods.
If the other app you need to detect
has a custom URL registered, you can
check to see if that URL exists.
Otherwise, you can look for that app's
process name running in the
background.
|
I would like char, short and int types to be 1, 2 and 4 bytes width. I have included astdint.hheader into my sources. Does this guarantee that int8_t, int16_t and int32_t integer types will be of widths specified? What is the best way to achieve this?
|
If these types exist, they have the correct width and are encoded in two's complement.
Edit: you should be able to check if the types exist with something like
```
#ifdef INT32_MAX
...
#endif
```
but on all end user architectures (PC etc) these types do usually exist.
|
I am doing some sse vector3 math.
Generally, I set the 4th digit of my vector to 1.0f, as this makes most of my math work, but sometimes I need to set it to 0.0f.
So I want to change something like:
(32.4f, 21.2f, -4.0f, 1.0f) to (32.4f, 21.2f, -4.0f, 0.0f)
I was wondering what the best method to doing so would be:
Convert to 4 floats, set 4th float, send back to SSExor a register with itself, then do 2 shufpsDo all the SSE math with 1.0f and then set the variables to what they should be when finished.Other?
Note: The vector is already in a SSE register when I need to change it.
|
AND with a constant mask.
In assembly ...
```
myMask:
.long 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000
...
andps myMask, %xmm#
```
where # = {0, 1, 2, ....}
Hope this helps.
|
I made this code in Python
```
def hitsin(a):
a = a*57.3
return math.sin(a)
```
so whenever i put hitsin(x) the x converted to radian. I confuse when I put hitsin(90) the answer is not 1 or any number near 1, but negative (it was -0.9971392129043587). Am I doing it wrong?
p.s: I also try to write the same kind of code in C
```
#include <stdio.h>
#include <math.h>
int main(){
float degree;
float result;
degree = 90;
degree = degree*57.3;
result = cos(result);
printf("%f",result);
return 1;
}
```
But the answer is same.
sincerely yours
Giri
|
You should divide by180/pi, not multiply. In Python, you can also usemath.radians()for the conversion from degree to radians:
```
def hitsin(a):
return math.sin(math.radians(a))
hitsin(90)
# 1.0
```
Furthermore, I doubt the C code gives the same result as the Python code, because it usescos()instead ofsin().
|
I'm using an open source library which seems to have lots of preprocessing directives to support many languages other than C. So that I can study what the library is doing I'd like to see the C code that I'm compiling after preprocessing, more like what I'd write.
Can gcc (or any other tool commonly available in Linux) read this library but output C code that has the preprocessing converted to whatever and is also readable by a human?
|
Yes. Pass gcc the-Eoption. This will output preprocessed source code.
|
I just saw the signature forprintf. it isint printf(const *f). Now, if I declare anint iand do the following:
```
int i=5;
printf("%d",i);
```
it displays the correct value ofi. I am wondering why is is this so. Sinceprintfaccepts a pointer, should it not treat the value ofias an address and print the value stored at that address.
Note thatprintf("%d", &i)does not work.
|
printf()is avariadic function. That means that its first argument indicates the number and type of remaining arguments to be pulled from the stack.
The first argument - and the only one that is not affected by the function being variadic - is astringand therefore a pointer (to an array ofchar, if it matters). The remaining arguments are processed differently and are not listed in the simplistic prototype that you mentioned.
BTW, here's the full prototype ofprintf()as pulled from mystdio.hheader:
```
extern int printf (const char *format, ...);
```
|
Is there any specific reason why has support for designated initializers not been added to g++? Is the reason that C99 standards came late and g++ was developed earlier and later people didn't care about this issue, or there is some inherent difficulty in implementing designated initializers in the grammar of C++?
|
I ran into this same problem today. g++ with -std=c++11 and c++14 does support designated initializers, but you can still get a compilation error "test.cxx:78:9: sorry, unimplemented: non-trivial designated initializers not supported" if you don't initialize the struct in the order in which it's members have been defined. As an example
```
struct x
{
int a;
int b;
};
// This is correct
struct x x_1 = {.a = 1, .b = 2};
// This will fail to compile with error non-trivial designated initializer
struct x x_2 = {.b = 1, .a = 2};
```
|
I have two integers (amount of bytes of two files). One is always smaller if not the same than the other. I want to calculate the percentage that the smaller is of the bigger.
I'm using plain C. I've applied the math formula, but am getting always 0:
```
printf("%d\r", (current/total)*100);
```
Any ideas?
|
Try
```
printf("%g\r", (((double)current)/total)*100);
```
instead. Integer division always rounds towards zero. By converting one of the numbers todoublefirst, you will trigger floating point division. If you would like to use integer arithmetic, you could also use
```
printf("%d\r", (100*current)/total);
```
which will print the percentage rounded down to the next integer.
|
I am looking for a prototype or implementation for a queueing/scheduling system with dependencies between the individual tasks. To be more specific:
task_0, task_1, task_2, ... task 10 arrive at the queue. Tasks are http requests.
I want to send task_2 only if task_0 is completed. task_1 can be sent without expecting
task_1 to complete but task_2 has to wait.
Ideas? Models that already exist and match this description?
|
The queue can be topologically sorted.
http://en.wikipedia.org/wiki/Topological_sorting
http://www.cs.sunysb.edu/~algorith/files/topological-sorting.shtml
|
This might be a very broad question. But this is what i want. I open a website and enter some details in the website like my credentials to login or it may be any data that pass from my browser to the website. Now what i want is that i should cache ( write to a temp file ) whatever that i send to that website. How can this be done? I tried to extract the data present in the packets that are flowing out of my machine but i find only junk characters in that (may be header). any ideas are welcomed. I am using Ubuntu Linux and would like to achieve this using shell script/C/C++
|
One option would be to use the Fiddler Web Debugger which is scriptable (C#).
Although it's a Win32 program, it can act as a proxy for any Linux machine. SeeDebug traffic from another machine (even a Mac or Unix box)for details.
There's also a native Linux app calleddsniffwhich can be used to log all HTTP traffic to a file.
|
In recent I was attend one Interview on "SureSoft Technology"...... In that interview, they ask one question lik "What is size for the sizeof operator in c? "
If any one Know answer Share with me?
|
Thesizeofoperator itself has no size. Its result will generally* turn into a constant value at compile time.
As for the value it returns, that would be the size, in bytes, of the argument. The type of the result issize_t(defined in<stdlib.h>) (§6.5.3.4.4)
* - with the notable exception of dynamically-sized automatic arrays.
|
I have time in Seconds and I want to convert this time in to Readable Time Sting as,DAY-Date-Hour-Min-Sec-Month-Year.
How to do this in CPP or C.
|
time(),localtime()andsprintf()should do the trick.
```
#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>.
#endif
#include <time.h>
static const char *Weekdays[] = {
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
int main() {
time_t curSec;
struct tm *curDate;
char dateString[32];
curSec = time(NULL);
curDate = localtime(&curSec);
sprintf(dateString,
"%s-%02d-%02d-%02d-%02d-%02d-%d",
Weekdays[curDate->tm_wday],
curDate->tm_mday,
curDate->tm_hour,
curDate->tm_min,
curDate->tm_sec,
curDate->tm_mon+1,
curDate->tm_year+1900);
printf("%s\n",dateString);
return 0;
}
```
|
I am writing a simple videophone ( for study ) and I would to know what APIs I have to use to capture and send images from a webcam in a network.
P.s. I wouldn't use complex library like OpenCV.
|
You can useWindows Image Acquisition (WIA)or/andDirectShow. Another good alternative isMicrosoft Media Foundation(chapter oncapturing video).
Mind you that this are cumbersome apis which make this no easy task and you might end up better by using OpenCV.
As for the network part, that's up to your design and preference.
|
When compiling this code with gcc
```
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
typedef struct _Nodo
{
unsigned int id_thread;
int id_mutex;
_Nodo *solicita;
_Nodo *asignado;
}Nodo;
```
I get:
```
libdrm.c:13: error: expected specifier-qualifier-list before ‘_Nodo’
```
Why?
|
Try:struct _Nodo *solicita.
|
can anyone explain these lines to me:
```
int xyz( void )
{
extern void abc( void );
}
```
a function declaration within a function definition?
or am I missunderstanding something?
|
Yes, your guess is correct. It's declaring the existence of the functionabc(), so it may be referenced withinxyz(). Note that theexternis unnecessary, as functions areexternby default.
|
If for the following code:
```
printf("HEllo\n"); // do not change this line.
printf("\b\bworld");
```
I need an output: Helloworld (In a single line). But this does not work fine. Could anyone please explain the reason? And other escape sequence if any.
|
There is no platform-independent control character to move back up a line. This harkens back to the days of line printers, whereprintfactually would print a line of text onto a sheet of paper and there was no way of retracting the paper to overwrite what had already been printed.
That said, there are libraries like ncurses that let you move the cursor around the console. They're just not part of the standard libraries.
|
For thestruct
```
typedef struct sharedData
{
sem_t *forks;
}sharedData;
```
I get a warning when I try to do this:
```
sharedData sd;
sem_t forks[5];
sd.forks = &forks; // Warning: assignment from incompatible pointer type
```
Am I misunderstanding or missing something?
|
The problem is that&forkshas type
```
sem_t (*)[5]
```
That is, a pointer to an array of fivesem_ts. The compiler warning is becausesd.forkshas typesem_t*, and the two pointer types aren't convertible to one another.
To fix this, just change the assignment to
```
sd.forks = forks;
```
Because of C's pointer/array interchangeability, this code will work as intended. It's becauseforkswill be treated as&forks[0], which does have typesem_t *.
|
In C/C++, what does the following mean?
```
for(;;){
...
}
```
|
It's an infinite loop, equivalent towhile(true). When no termination condition is provided, the condition defaults to false (i.e., the loop will not terminate).
|
Guys I am new to data structures.Most of the time in books and references i see this structure for a binary tree
```
struct btree {
int data;
struct btree *left;
struct btree *right;
};
```
But in above image it would be like
```
struct btree
{
int data;
struct btree *left;
struct btree *right;
struct btree *parent;
};
```
So my question is that is it dependent on programmer to choose the structure of a node of a tree (for e.g also including a pointer to the parent )or we can have only two pointers one to the left child and other to the right child.
|
It is up to you whether you include parent pointers. They require more work to maintain, but some tree operations (like removing a node given just that node rather than its parent) become much easier.
|
I'm fairly sure the set code should look like this:
```
function setPYR(float pitch, float yaw, float roll) {
glLoadIdentity();
glRotatef(pitch, 1, 0, 0);
glRotatef(yaw, 0, 1, 0);
glRotatef(roll, 0, 0, 1);
}
```
How can I get the pitch, yaw and roll from the current modelview matrix?
|
Give a look atThe Matrix and Quaternions FAQ.
|
So I have my config file .vimrc that has this code which should save the file compile and run it when I press F3. This doesn't work.
```
map <F3> ^M:w^M:!gcc *.c -g; ./a.out^M
```
|
Your keymapping worked for me (assuming you type^Mas e.g. Ctrl-V Ctrl-M).
If you have a makefile setup (and you probably should) you can just use:make.
You can set themakeprgoption if you use something other thanmake, e.g.cmakesconsantor something else.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been done so far to solve it.Closed9 years ago.Improve this question
I've looked around quite a bit for a fast math parser in either C or Objective-C Almost all of the libraries I saw are written in C++, and I don't really want to go through the hassle of getting that to compile. Can anyone make a recommendation?
|
I haven’t used them myself, but you could tryGCMathParserandDDMathParser.
|
I need some help with a program for converting Fahrenheit to Celsius in C. My code looks like this
```
#include <stdio.h>
int main(void)
{
int fahrenheit;
double celsius;
printf("Enter the temperature in degrees fahrenheit:\n\n\n\n");
scanf("%d", &fahrenheit);
celsius = (5 / 9) * (fahrenheit - 32);
printf("The converted temperature is %lf\n", celsius);
return 0;
}
```
Every time I execute it it the result is 0.000000. I know I'm missing something but can't figure out what.
|
5/9 will result in integer division, which will = 0
Try5.0/9.0instead.
|
I would like to know exactly what is going on withomp parallel forand other similiar constructs. How do I find how these are implemented? A short summary of someone who knows about this would be great. Thanks.
|
Open MP is merely a spec, how a vendor chooses to implement it is up to them. that being said, the libraries GCC uses are open source, so is Intels Thread building blocks, which has a parallel for, just not as a pragma, but its implementation is what your after
|
input to lexer
```
abc gef4 44jdjd ghghg
x
ererete
xyzzz
55k
hello wold
33
```
my rules
```
rule1 [0-9]+[a-zA-Z]+
rule2 [x-z]
rule3 .*
```
{rule1} {
printf("%s \n", yytext);
}
{rule2} {
printf("%s \n", yytext);
}
{rule3} {
// prints nothing
}
output :-
```
x
55k
```
I cannot understand the output ? Can someone please help me.
|
The first character of the input neither matches rule1 nor rule2. Instead rule3 eats input up to the end of line. The same happens on line 3, 4, 6, and 7. You probably want a less greedy rule3, i.e. one that doesn't consume the spaces:
```
[^ \t\n]* /* Do nothing */
```
Then 44jdjd is being found by rule1.
|
Actually, I want to execute DOS command by a C program and want to display the output of DOS command in my C Output Window.
example:
use "dir C:\" which displays output to C- program
|
To execute a command in the samecmd.exewindow where your C program is running:
```
#include <stdlib.h>
.
.
.
system("dir C:\\");
```
To launch a separate windows, you need to callcmd.exe:
```
system("cmd.exe /c dir c:\\");
```
(Note: I have not tested this one);
|
I realise this code is faulty.
However, I came across some curious behaviour which I was wondering if somebody could explain.
Example 1 :
```
char *foo;
scanf("%s",foo);
printf("%s",foo);
```
Output is :(null).
Example 2 :
```
int i;
char *foo;
scanf("%s",foo);
printf("%s",foo);
```
Output is :val of foo!
Why would the presence ofint icause this to "work"?
|
foois a pointer, but you haven't set it to point at any memory that you've allocated, so instead it just has a random value at startup, and hence is pointing at some random section of memory. Hence, anything could happen (i.e.undefined behaviour).
The presence ofint ijust changes the position offooon the stack, and hence the particular random value that it has. You shouldn't read anything meaningful into this differing behaviour, as it's still undefined.
|
I have an unsigned char and I need to check bits 1 and 2 to find the status. What is the best way to determine the last 2 bits?
I am attempting to perform an OR, but my results aren't correct. Any help would be appreciated. Thanks.
Example:
```
10101000 = off
10101001 = on
10101010 = error
10101011 = n/a
if(data_byte_data[0] | 0xfe)
//01
else if(data_byte_data[0] | 0xfd)
//10;
else if(data_byte_data[0] | 0xfc)
//11
else if(data_byte_data[0] | 0xff)
//00
```
|
I would do something like:
```
v = data_byte_data[0] & 0x03;
switch (v)
{
case 0: ...
case 1: ...
case 2: ...
case 3: ...
}
```
|
Hi I created a server program that forks a new process after its accepts a socket connection.
There are several statically allocated global variables defined in the program. My question is are these static buffers allocated twice after the fork? Or does the fork only duplicate address space on the heap and the call stack?
|
Theentireaddress space is duplicated, including all global variables and the program text.
|
Already read throughthis related question, but was looking for something a little more specific.
Is there a way to tell your compiler specifically how wide you want your enum to be?If so, how do you do it? I know how to specify it in C#; is it similarly done in C?Would it even be worth doing? When the enum value is passed to a function, will it be passed as anint-sized value regardless?
|
I believe there is a flag if you are using GCC.
-fshort-enums
|
How would I do the following:
```
unsigned short x = 0xFFFF;
unsigned short y = 0xAE;
x |= y & 1;
x |= y & (1 << 1);
x |= y & (1 << 2);
x |= y & (1 << 3);
x |= y & (1 << 4);
x |= y & (1 << 5);
x |= y & (1 << 6);
x |= y & (1 << 7);
x |= y & (1 << 8);
x |= y & (1 << 9);
x |= y & (1 << 10);
x |= y & (1 << 11);
x |= y & (1 << 12);
x |= y & (1 << 13);
x |= y & (1 << 14);
x |= y & (1 << 15);
printf("%x", x);
```
I want x to be equal to 0xAE, but it is still equal to 0xFFFF.
|
All bits are set already in x - so any|=operation on it won't change that.
|
I have a few dd images and I wanted to know the best way of extracting files out of these using C. The images are of mixed file systems (fat32, ntfs, ext2/3) and the host machine doing the extraction would be an Ubuntu box, so you can assume kernel headers and GNU C library, etc.
Natively would be best, but external libraries that do the job would also be fine. A link to an example would be perfect.
|
This is a significant effort. You'd have to essentially reimplement filesystem drivers for NTFS, FAT, and EXT2. I've done this for FAT and NTFS, but it took more than two years, though much of that was reverse engineering NTFS.
Consider using thefile mountoption of the mount command so you can use the Ubuntu filesystem drivers and not reinvent the significantly large wheel. Then you can peruse the mounted filesystems.
|
I would like to convert aint32_tfrom host byte order to network byte order and vice versa. I know about thehtonl()function and its variants, but this takes unsigned integers. Is there a standard library function which can do the same with signed integers or do I have to implement it myself? And if I have to implement it myself, how should I do it?
I'm looking to find a routine that will work on Linux and Mac OS X.
|
It does not matter. htonl is concerned with bytes, not with arithmetical value of the number. Use reinterpret_cast to change the number to unsigned and back again, if you have to.
|
My fedora12 installed a tool called ABRT that comes probably with GNOME. This
tool operates at the background and reports at realtime any process that has crashed.
I have used a signal handler that was able to catch a SIGSEGV signal, ie it could report
crashed.
What other ways exist in order a process to get information about the state (especially a core) of an other process without having parent-child connection?
Any ideas? It seems a very interesting issue.
|
ABRT is open source, after all, so why not look at theircode. The architecture is explainedhere-- it looks like they monitor$COREDUMPDIRto detect when a new core file appears.
|
My string length is constant but actual data length will vary as like below,
```
" 1,54" // will be displayed as "- 1,54"
"123456789012,12" // will be dsiplayed as "- 123456789012,12"
```
|
Wouldn't it be easiest to just put a '-' in the format string when you display the data?
```
printf("-%f", 1.54);
```
|
I've the following piece of code and I think it can cause an overflow in the readlink() function.
```
pid_t get_pid_from_proc_self()
{
char buffer[4];
pid_t pid;
readlink("/proc/self", buffer, sizeof(buffer));
sscanf(buffer, "%d",(int *)&pid);
return pid;
}
```
Since the PID is 4 bytes in Linux,readlink()copies 32 bits from "/proc/self" intotarget[]. Then, according to me, an extra byte should be used for'\0', which makes it 5 bytes.
Also, doesreadlink()automatically inserts'\0'at the end if string or do I have to specifically assign it to the last byte?
|
No, it won't cause an overflow. It'll read in at mostsizeof(buffer)bytes, and then stop. It doesn't null-terminate your string, so you will have to do so. Readingbufferbefore ensuring the last byte is a\0will lead to undefined behavior (which is what yoursscanf()call is doing).
|
What is the proper way to initializeunsigned char*? I am currently doing this:
```
unsigned char* tempBuffer;
tempBuffer = "";
```
Or should I be usingmemset(tempBuffer, 0, sizeof(tempBuffer));?
|
To "properly" initialize a pointer (unsigned char *as in your example), you need to do just a simple
```
unsigned char *tempBuffer = NULL;
```
If you want to initialize an array ofunsigned chars, you can do either of following things:
```
unsigned char *tempBuffer = new unsigned char[1024]();
// and do not forget to delete it later
delete[] tempBuffer;
```
or
```
unsigned char tempBuffer[1024] = {};
```
I would also recommend to take a look atstd::vector<unsigned char>, which you can initialize like this:
```
std::vector<unsigned char> tempBuffer(1024, 0);
```
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
```
putchar(263); // edit: fixed typo, was 264
```
it produced beep (By internally CPU speaker);
How?? (Any Ascii value relation)
|
putcharconverts its argument to anunsigned char, so I suppose that you get the ASCII value of BEL after the conversion.
BEL is the code for making the system bell ring.
|
Assume that I have allocated a C-style dynamic array of doubles in C/C++ code, I thus have:
```
double *x; //Pointing to beginning of allocated memory
int size; //Size of array
```
Is it possible to write lua code (or even C/C++ code to be used in lua) such that a C/C++ embedded instance of lua can read/write efficiently on the elements of this "view" on the array?
I would just need support for the following C++ operations:
```
double y = x[2]; //Reading
x[2] = 3.0; //Writing
int vecSize = x.size(); //Size of array
```
No memory management is needed (nor wanted).
|
Sure, export the pointer as userdata and set __index and __newindex metamethods.
|
Guys this is a program which i ran on my compiler and i am getting30 0 0 0as the output.Can one explain me why the values are 0 .Because in 2'nd loop tmp would point to something outside the array so wouldn't it be a garbage value. Why Garbage values are not getting printed instead 0's are coming in the output.
```
void main()
{
int array[4]={10,20,30,40};
int *tmp=array;
for (int i=0;i<4;i++)
{
tmp+=sizeof(int);
printf("%d",*tmp);
}
getch();
}
```
|
You do not addsizeof(int)to anintpointer to get to the next array element; you add 1. Addingsizeof(int)will advance bysizeof(int)elements(probably 4 elements), putting you past the end of the array. This is your problem.
Edit:OK apparently the program was part of an interview question meant to illustrate undefined behavior, and the correct answer to the interview question is that once undefined behavior has been invoked, anything could happen.
|
My string length is constant but actual data length will vary as like below,
```
" 1,54" // will be displayed as "- 1,54"
"123456789012,12" // will be dsiplayed as "- 123456789012,12"
```
|
Wouldn't it be easiest to just put a '-' in the format string when you display the data?
```
printf("-%f", 1.54);
```
|
I've the following piece of code and I think it can cause an overflow in the readlink() function.
```
pid_t get_pid_from_proc_self()
{
char buffer[4];
pid_t pid;
readlink("/proc/self", buffer, sizeof(buffer));
sscanf(buffer, "%d",(int *)&pid);
return pid;
}
```
Since the PID is 4 bytes in Linux,readlink()copies 32 bits from "/proc/self" intotarget[]. Then, according to me, an extra byte should be used for'\0', which makes it 5 bytes.
Also, doesreadlink()automatically inserts'\0'at the end if string or do I have to specifically assign it to the last byte?
|
No, it won't cause an overflow. It'll read in at mostsizeof(buffer)bytes, and then stop. It doesn't null-terminate your string, so you will have to do so. Readingbufferbefore ensuring the last byte is a\0will lead to undefined behavior (which is what yoursscanf()call is doing).
|
What is the proper way to initializeunsigned char*? I am currently doing this:
```
unsigned char* tempBuffer;
tempBuffer = "";
```
Or should I be usingmemset(tempBuffer, 0, sizeof(tempBuffer));?
|
To "properly" initialize a pointer (unsigned char *as in your example), you need to do just a simple
```
unsigned char *tempBuffer = NULL;
```
If you want to initialize an array ofunsigned chars, you can do either of following things:
```
unsigned char *tempBuffer = new unsigned char[1024]();
// and do not forget to delete it later
delete[] tempBuffer;
```
or
```
unsigned char tempBuffer[1024] = {};
```
I would also recommend to take a look atstd::vector<unsigned char>, which you can initialize like this:
```
std::vector<unsigned char> tempBuffer(1024, 0);
```
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
```
putchar(263); // edit: fixed typo, was 264
```
it produced beep (By internally CPU speaker);
How?? (Any Ascii value relation)
|
putcharconverts its argument to anunsigned char, so I suppose that you get the ASCII value of BEL after the conversion.
BEL is the code for making the system bell ring.
|
Assume that I have allocated a C-style dynamic array of doubles in C/C++ code, I thus have:
```
double *x; //Pointing to beginning of allocated memory
int size; //Size of array
```
Is it possible to write lua code (or even C/C++ code to be used in lua) such that a C/C++ embedded instance of lua can read/write efficiently on the elements of this "view" on the array?
I would just need support for the following C++ operations:
```
double y = x[2]; //Reading
x[2] = 3.0; //Writing
int vecSize = x.size(); //Size of array
```
No memory management is needed (nor wanted).
|
Sure, export the pointer as userdata and set __index and __newindex metamethods.
|
Guys this is a program which i ran on my compiler and i am getting30 0 0 0as the output.Can one explain me why the values are 0 .Because in 2'nd loop tmp would point to something outside the array so wouldn't it be a garbage value. Why Garbage values are not getting printed instead 0's are coming in the output.
```
void main()
{
int array[4]={10,20,30,40};
int *tmp=array;
for (int i=0;i<4;i++)
{
tmp+=sizeof(int);
printf("%d",*tmp);
}
getch();
}
```
|
You do not addsizeof(int)to anintpointer to get to the next array element; you add 1. Addingsizeof(int)will advance bysizeof(int)elements(probably 4 elements), putting you past the end of the array. This is your problem.
Edit:OK apparently the program was part of an interview question meant to illustrate undefined behavior, and the correct answer to the interview question is that once undefined behavior has been invoked, anything could happen.
|
I want to generate 2 random numbers between 0 and 20
```
int one = rand() % 20;
```
it gives me 1 steady value i.e 1...
Am I missing something?
|
You have to give a seed to the random number.
```
srand( time(NULL) );
int num1 = rand() % count;
int num2 = rand() % count;
```
Random number between 1 and 20
```
int num = rand() % 20 ;
if( num == 0 )
num += 2;
else if( num == 1 )
++num ;
```
|
I am a beginner of C. I run the C program, but the window closes too fast before I can see anything. How can I pause the window?
|
you can put
```
getchar();
```
before the return from the main function. That will wait for a character input before exiting the program.
Alternatively you could run your program from a command line and the output would be visible.
|
```
#include <stdio.h>
#define print_int(a) printf("%s : %d\n",#a,(a))
int main(void) {
int y = 10;
print_int(y);
return 0;
}
```
i am taking a class and have been asked to explain why this is bad... So i guess stringizing #a is the problem. It does work, so why is it dangerous?
|
because it bypasses type safety. What happens when someone hates you and goesprint_int("5412");
```
#include <stdio.h>
#define print_int(a) printf("%s : %d\n",#a,(a))
int main(void) {
print_int("1123123");
return 0;
}
```
outputs
```
$ gcc test.c
test.c: In function ‘main’:
test.c:4: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘char *’
$ ./a.out
"1123123" : 3870
```
|
Suggestions needed for best instrumentation tools for a C project. I actually like to know when control was transferred from a function to another function and therefore I want to do something like instrumenting printf commands at the end and start of each function.
|
Thevalgrindtool has all sorts of hooks you can program that would let you watch this happen. In particular,thecallgrindtoolmight be appropriate here.
|
when we write something like this
int arr[5] = 0;orint arr[5] = {0};
there is no problem
but when we do something like this
```
int arr[5];
arr[5] = {0};
```
an error occurs. Any explanation for this ?
|
It is simply a part of the language definition that arrays can be initialised, but not directly assigned. You can do what you want in C99 usingmemcpy()with a compound literal:
```
int arr[5];
/* ... */
memcpy(&arr, &(int [5]){ 0 }, sizeof arr);
```
With GCC'stypeofextension, you can add a little more safety:
```
memcpy(&arr, &(typeof(arr)){ 0 }, sizeof arr);
```
In C89 you must give the source array a name:
```
{ static const int zero[5] = { 0 }; memcpy(&arr, &zero, sizeof arr); }
```
|
Reading the glibc documentation, I recently learned that calls to getc may have to wait to acquire a lock to read a file. I wanted to verify that when using buffering a lock is only acquired when the actual file needs to be read to replenish the buffer.
Thanks!
|
The lock invoked bygetcprovides application-level locking of the stdio FILE object, to allow thread-safe access to the same FILE object by multiple threads in the same application. As such, itwillneed to be acquired every time a character is read, not just when the buffer is replenished.
But, if you aren't accessing the FILE from multiple threads, you'll never have to wait for the lock. If the overhead of acquiring/releasing the lock is too much (measure this; don't just assume), you also have the option of manually locking/unlocking usingflockfileandfunlockfile, then usinggetc_unlocked.
|
I recently installed cygwin on my windows 7 machine which I installed all the packages that came with cygwin. Now i have a simple "Hello World" program in C code that uses GTK objects. When I type make and compile the program in CYGWIN, it gives me a big error:
"gtk/gtk.h: no such file or directory"
........... and it goes on an lists bunch of GTK errors
doesnt CYGWIN include GTK? If it does I am pretty sure I installed it. Is there another plugin for GTK and cygwin i dont know about? I really need this to work for my course throughout the semester. Aprreciate any help I can get.
|
As far as I'm concerned Cygwin does not include Gtk. You can download Gtk for windows onhttp://www.gtk.org/download-windows.html, I recommend you download the all-in-one bundle.
|
I am experienced at multithreaded programming in Java and C#, and am starting to learn how to do it in C on Linux. I "grew up" in the programming sense on Linux, so I understand it's memory philophy, process handling, etc. at a high level.
My question is not how to do threading. I would like to know how pthread actually does it. Does it fork a process and handle your interprocess communication for you somehow? Or does it just manage the address space? I want nitty-gritty details :) Googling has only produced "how to do it" questions, not "how it works".
|
The details are probably too complex to really get into (without posting a link to the glibc source code), but I can give you better things to look up:
Pthread usessys_clone()to create new threads, which the kernel sees as a new task that happens to share many data structures with other threads.To do synchronization, pthread relies heavily onfutexesin the kernel.
|
I have a bunch of int's in my c++ code that I need to change to int32's. Same with my bool's. What header do I need to include in order to use int32's and bool32's. Also how do I declare these once I make them. Am I able to just replace the int's with int32's?
For example:
```
int x;
```
Becomes
```
int32 x;
```
I am getting lots of errors when I try to change from int to int32. Here's a few:
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2086: 'const int x' : redefinition
|
```
<cstdint>
```
If your compiler supports it, will get you int32_t, the C99 fixed width integer type.
Never heard of no bool32 and I can't imagine what kind of sense it would even make.
Yes, you can just replaceintwith your type so long as your type remains fundamental and/or has a default constructor/non-implicit constructor...depending on use.
|
I have written a simple client server program in C under linux. I have created UDP sockets. The client broadcasts a message using
```
sendto(clientsock, buf, 100, 0, (struct sockaddr *)&to, sizeof (to));
```
The server receives the broadcasted message using
```
recvfrom(serversock, buf, 100, 0, (struct sockaddr *)&rcv,&size);
```
The message is being successfully received by the server. On the server side, I need to find the source IP address of the message received. How can I do that ?
|
for a call like -
```
recvfrom(s, buf, BUFLEN, 0, &si_other, &slen)
```
use
```
printf("Received packet from %s:%d\nData: %s\n\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf);
```
|
This question already has answers here:Closed12 years ago.
Possible Duplicates:main() functions return value?What should main() return in C/C++?
What is the purpose of the returning of a value from main() in the languages C and C++?
How the return value helps us?
Can the return value be used to achieve anything important?
|
It's theexit status. It's typically used to signal to the OS whether the process was successful or not in whatever it was doing.
|
When implementing stubs etc. you want to avoid "unused variable" warnings. I've come across a few alternatives of UNUSED() macros over the years, but never one which either is proven to work for "all" compilers, or one which by standard is air tight.
Or are we stuck with #ifdef blocks for each build platform?
EDIT:Due to a number of answers with non c-compliant alternatives, I'd like to clarify that I'm looking for a definition which is valid for both C and C++, all flavours etc.
|
According tothis answerbyuser GManthetypicalway is to cast tovoid:
```
#define UNUSED(x) (void)(x)
```
but ifxis marked asvolatilethat would enforce reading from the variable and thus have a side effect and so the actual way to almost guarantee a no-op and suppress the compiler warning is the following:
```
// use expression as sub-expression,
// then make type of full expression int, discard result
#define UNUSED(x) (void)(sizeof((x), 0))
```
|
I'm retriving a result from MySQL with from the variable row[2].
The data from this variable is int in the mysql table but I can't put this into an int variable in c++ because I get the error message
```
average.cpp:40: error: invalid conversion from char* to int
```
Line 40 istotal += row[2];
What am I doing wrong:?
Thanks
|
Look at the error, when you get the value it's converted to a char *, so you have to convert it back to int.
```
#include <sstream>
#include <string>
using namespace std;
string input(row[2]);
stringstream SS(input);
int n;
SS >> n;
total+=n;
```
|
I have been associated with C language during my college and soon shifted to scripting languages. Now I am interested to brush off my C skills and also enhance with C internals programming. I request for good resources (books, websites, articles, ...) to learn and get me started off.
|
K&R, Second Edition
Often times the best source is the original source :)
Expert C Programming, Deep C Secrets
Excellent stories of how professional programmers have been bitten by hard-to-find problems and how you can learn from their efforts.
Advanced Programming in the Unix Environment
THE resource for learning how to program for Unix environments; it may be lacking some of the neater new features, but it is one of the best resources for learning details of how to write systems programs.
|
I have time in epoch format.I just want to retrieve Year from it.
how should we do it in c or c++ ?
Actually i have time since epoch in seconds and i need to calculate age depending on it.So input will be seconds since epoch and out put should be Age based on current date.
Thanks,PP.
|
Using thegmtimeorlocaltimefunctions to convert thetime_tto astruct tm. Then you can use thetm_yearfield of the struct to get the year.
Or for offline use, you can use a web converter,like this.
Edit:
Sample code:
```
time_t nowEpoch = time(NULL);
struct tm* nowStruct = gmtime(&nowEpoch);
int year = nowStruct->tm_year + 1900;
```
|
```
#include<stdio.h>
int main()
{
printf("%d",printf("%d %d",2,2) & printf("%d %d",2,2));
}
```
The output comes like this:2 2 2 2 3
I cannot figure out why the output is like this. Any ideas?
|
printfreturns the numbers of characters printed, so here is the explanation:
```
printf("%d",printf("%d %d",2,2) & printf("%d %d",2,2));
\_________/ \_________________/ | \_________________/
| | | |
| prints "2 2" | prints "2 2"
| and returns 3 | and returns 3
| |
| computes 3 & 3
| (which equals 3)
|
prints "3"
```
|
My GNU/Linux machine is connected to a DHCP. I want to retrieve the value of theoption 015of DHCP (DNS Domain Name), but without usinggetnameinfo, since it is using DNS in order to retrieve domain name.
How can I do that with C/C++?
|
Mydhclientwrites a pile of lease information into/var/lib/dhcp3/dhclient-[uuid]-[iface].leasefiles. I haven't got a clue what the uuid in those filenames represents, but it does report the different options from the dhcp server.
|
Given a unsigned char bitmapRep[8192], how to efficiently find out all "1" bits' positions? Thanks.
|
What do you mean by "find"?
This may seem like a smart-ass answer, but I'm perfectly serious: you alreadyhavefound them. There's a perfect map describing exactly where all the 1 bits are found, and it has a bit set in the corresponding positions.
|
I have this in my code and it is causing the warning that follows:
```
long ans = ((long) INT_MIN) * 2 - 1;
```
The warning that I get is:
```
warning: integer overflow detected: op "*"
```
I have included limits.h so that I could use INT_MIN
```
#include <limits.h>
```
|
This means that the calculation will overflow the range oflong. Signed overflow yields undefined behavior.
The only correlation between the range of values representable bylongand the valueINT_MINis thatINT_MINis representable as along. There is no guarantee that one less than twiceINT_MINis representable as along.
|
I need a way to open a generic file with thedefault application for that file.
For example: if the file is an HTML file, then it will be opened with Internet Explorer; if the file is an image (JPG, BMP, etc.), then it will be opened with "Paint"; if the file is an MP3 file, then it will be opened with Windows Media Player.
How can I do this ? What function or API do I have to use ?
|
Use the ShellExecute function:http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx
EDIT: orShellExecuteEx
|
I need to print a variable which is a COLORREF.
|
You might also want to break it up into the individual RGB components:
```
printf("R: %i, G: %i, B: %i", GetRValue(color), GetGValue(color), GetBValue(color));
```
this would give you something like:
R: 255, G: 150, B: 75
|
Good day guys. I'm using bloodshed devc++ as ide which, I believe, is using mingw as compiler. I've been reading up lots of articles talking about optimization of code and bottlenecks which makes me want to try their recommended techniques :)). So the questions are:
How do I measure how efficiently or how poorly my code is running?How do I know which parts of my code are the 'bottlenecks' (am I using the term right?)
thanks!
|
You can use a profiler. As you are using MinGW compiler, use gprof.
|
hi guys can you explain what does that greater than sign do in the follwing code
```
if (header->mode > forceMode)
{
*rate >>= (header->mode - forceMode); //What does this mean >>=
*granule_frame_size <<= (header->mode - forceMode); //What does this mean <<=
}
```
|
While all the answers above are correct, it's possible you might still not understand it. You will need to understand binary.
Imagine you have the expression
7 << 2
That means "Convert 7 into binary, then shift all the bits left 2 times."
So 7 is 00000111
shifted left twice (and inserting zeros) yeilds:
00011100
This is equal to 28.
So if the variable A is 7, and B is 2, then:
```
A <<= B;
```
Leaves A equal to 28;
|
I know this is wrong:
```
char* getSomething() {
char szLocal[5];
/* Put something in the char array somehow */
return szLocal;
}
```
...becauseszLocalcan be destroyed sometime after the function returns.
But is this ok?
```
char* getSomethingElse() {
return "something else";
}
```
|
That is actually OK. The string literal is usually allocated in an immutable memory area that remains available for as long as your program is running.
See also the answers towhen does c/c++ allocate string literals.
|
For my compiler tests, I need to generate this warning "Statement has no effect" in my test code. How can I do this?
Using VS cl.exe compiler
|
```
so ross$ cat > noeff.c
void f(void) {
1;
}
so ross$ cc -Wall -c noeff.c
noeff.c: In function ‘f’:
noeff.c:2: warning: statement with no effect
so ross$
```
|
So I have many log files that I need to write to. They are created when program begins, and they save to file when program closes.
I was wondering if it is better to do:
fopen() at start of program, then close the files when program ends - I would just write to the files when needed. Will anything (such as other file io) be slowed down with these files being still "open" ?
OR
I save what needs to be written into a buffer, and then open file, write from buffer, close file when program ends. I imagine this would be faster?
|
Well,fopen(3) + fwrite(3) + fclose(3)isa buffered I/O package, so another layer of buffering on top of it might just slow things down.
In any case, go for a simple and correct program. If it seems to run slowly, profile it, and then optimize based on evidence and not guesses.
|
I need to allocate an N sized array and assign it values, how can I do it without int indexes?
Here is the code I have so far but it doesn't do what I need:
```
#include <stdlib.h>
#include <stdio.h>
int main() {
int *array;
int n;
printf("Size of array: ");
scanf("%d", &n);
array = (int*) malloc(n*sizeof(int));
if (array == NULL) printf("Memory Fail");
for(; *array; array++)
{
printf("Store:\n");
scanf("%d", &n);
*array = n;
}
for(; *array; array++)
{
printf("Print: %d\n",*array);
}
free(array);
return 0;
}
```
thanks
|
for(; *array; array++);you should remove;at the endNumber of iterations for this loop is undefined and you are going to lose a pointer
You should do something like this:
```
int *cur;
for(cur = array; cur < array+n; ++cur)
{
*cur = ...;
}
```
|
Okay so I have a file of input that I calculate the amount of words and characters in each line with success.
When I get to the end of the line using the code below it exits the loop and only reads in the first line. How do I move on to the next line of input to continue the program?
EDIT: I must parse each line separately so I cant use EOF
```
while( (c = getchar()) != '\n')
```
|
Change'\n'toEOF. You're reading until the end of the line when you want to read until the end of the file (EOF is a macro in stdio.h which corresponds to the character at the end of a file).
Disclaimer: I make no claims about the security of the method.
|
I have a C function, which takes a string called 'buffer', and parses it, it will match keywords and use that to assign values in a structure.
However, some keywords I want to completely ignore.
This program parses VCard files (.vcf, virtual business cards).
Here is a sample line buffer might supply:
```
FN;CHARSET=UTF-8:David Celery
```
FN is a keyword im interested in, and David Celery is the value associated with FN.
However, CHARSET=UTF-8 is something I dont care about at all.
So my question is, is there a way for me to scan my buffer and simply replace 'CHARSET=UTF-8" with "", so that I don't have to worry about parsing it (and other similar keywords I just want to ignore).
Thanks,
|
have a look at a simple ANSI C solution like:
```
void removeSubstring(char *s,const char *toremove)
{
while( s=strstr(s,toremove) )
memmove(s,s+strlen(toremove),1+strlen(s+strlen(toremove)));
}
```
|
I have confusion on following c code
```
#define MACRO (xx) \
foo(xx)
...
#ifdef A
return MACRO(a);
#endif
...
```
The source can not compile. But when I change definition to
```
#define MACRO \
foo(a)
```
So if I want to use MACRO with argument in this case, how should I do? Thanks..
|
Remove the space betweenMACROand(xx).
If you leave the space there, the preprocessor doesn't treat(xx)as the argument, but as part of the expansion. So whenever it seesMACRO, it replaces it with(xx) foo(xx).
|
I have inherited a sample.pot file. Now, I have added new messages in a1.c and a2.cpp. Is it possible for me to use xgettext and output the contents to same sample.pot instead of creating a new one? Eg:-
```
xgettext -d sample -s -o sample.pot a1.c
xgettext -d sample -s -o sample.pot a2.cpp
```
Is this preferred way to go in order to update the template such that old messages are also preserved? The other question is how do we distinguish translatable strings from normal strings in source code. I assume xgettext will pull all strings from mentioned source code file.
It would be great if anybody can share the correct approach..Thanks
|
Does the-j,--join-existingoption ("join messages with existing file") not do what you need?
Note that you can specify more than one input file on the command line.
```
xgettext -d sample -s -j -o sample.pot a1.c a2.cpp
```
|
Within my C program, I’d like to temporarly redirect stdout to/dev/null(for example). Then,
after writing to/dev/null, I’d like to restore stdout. How do I manage this?
|
On POSIX systems, you can do it as follows:
```
int bak, new;
fflush(stdout);
bak = dup(1);
new = open("/dev/null", O_WRONLY);
dup2(new, 1);
close(new);
/* your code here ... */
fflush(stdout);
dup2(bak, 1);
close(bak);
```
What you want is not possible in further generality.
Any solution usingfreopenis wrong, as it does not allow you to restore the originalstdout. Any solution by assignment tostdoutis wrong, asstdoutis not an lvalue (it's a macro that expands to an expression of typeFILE *).
|
Expanding myother question..
```
unsigned char* s_char = data + offset;
(*s_char) = size_t(((*s_char) & 0xf0)) | new_doff;
```
How to print s_char's bit representation?
|
You'll need to manually print it using something like:
```
printf("%d%d%d%d%d%d%d%d", *s_char & 0x80, *s_char & 0x40, ..., *s_char & 0x01);
```
|
what is the complexity of a program having only one loop, is it log n?
can someone give me some ideas about estimating complexity of codes?
|
Well, that really depends on what is going on in that loop.
This loop is linear time, i.e., O(n):
```
int sum = 0;
foreach( int i in SomeCollection )
{
sum += i;
}
```
However, consider a loop which performs a substring search during each iteration. Now you have to consider the complexity of the string searching algorithm. Your question can't be answered as it stands. You will need to provide a code sample if you want a meaningful answer.
|
HI all
I have this code taken from a C project. I am not able to compile it in any way under g++.
What can I do with this?
```
enum EnumIndexID{
ID_VALUE_A=2,
ID_VALUE_B=2
}
struct newtype {
enum MyEnumID eid;
const char *name;
} table[] = {
[ID_VALUE_A] = { MyEnumA, "ID_MSG_HeartbeatReq"},
[ID_VALUE_B] = { MyEnumB, "ID_MSG_HeartbeatReq"},
};
```
|
Are you sure that your compiler supports theDesignated Initializersyntax?
g++ does not.
From that hyperlink:
Standard C89 requires the elements of an initializer to appear in a fixed order, the same as the order of the elements in the array or structure being initialized.In ISO C99 you can give the elements in any order, specifying the array indices or structure field names they apply to, and GNU C allows this as an extension in C89 mode as well.This extension is not implemented in GNU C++.
|
I have a C program that usessprintf_s. It works fine in Windows, but when I compile my code in Linux it gives this error:
```
sprintf_s was not declared in this scope.
```
Why does this happen and how can I fix it?
|
It's not standard, you won't find such function on Linux.
Standard functionsnprintfshould have a similar semantics.
|
I need to write a C-function to extend my PostgreSQL server functionality. One of the arguments of that function is a string representing any PostgreSQL valid expression returning a number. For example:
3+5*cos(7.4)/872+2log(34)degrees(0.5)power(9.0, 3.0)case when 8 > 2 then 1 when 7*5 < 43 then 2 else 3 end
and so on
The point is my function first replaces some values in the expression (variable names) for numbers and then it should execute the expression and returns the result (a number). With PL/pgSQL I can use EXECUTE expr INTO val, but how could I do it in a C function?
Many thanks in advance, and best regards
|
SPI_execute_with_argssounds closer to what are you looking for. Check out theexamplestoo.
|
I am having trouble installing a dependency for a program that itself depends on pcre.h. I have this installed to /opt/local/include, but the C compiler does not see it and thus gives me:
error: pcre.h: No such file or directory
I have confirmed this by writing a hello world program that tries to include it:
```
#include <pcre.h>
#include <stdio.h>
int main(void)
{
printf("hello, world\n");
return 0;
}
```
This also gives the error unless I specify the path as</opt/local/include/pcre.h>.
I would like the C compiler to find this by default but I do not know where this is configured. Tab completion hasn't revealed anyHEADER_PATHenvironment variables and I cannot find anything like it that isn't specific toXCode. I am, however, using Mac OSX Snow Leopard on the off chance that makes a difference.
|
Use-I /opt/local/includeon the command line orC_INCLUDE_PATH=/opt/local/includein the environment.
|
What's the quickest, easiest way to find the memory address of the first local variable in the activation record? (In C..)
Doesn't matter what we have declared already. Could be simple as char *s = 'Hello world!'
Thanks!
|
You can't do that - the C standard doesn't even require that thereisa stack, let alone requiring a standard way to find out the order in which variables were put on it.
|
I want after I do some calculation create an array inCwould u please help me?
```
int len_arr = (sizeof inputs)/(sizeof inputs[0]);
int half_arr = len_arr / 2;
if(len_arr%2 != 0)
half_arr++;
int m[half_arr][half_arr];
```
|
I'm assuming you wish to create a matrix with row/column size ofhalf_arr.
```
int i;
int len_arr = (sizeof inputs)/(sizeof inputs[0]);
int half_arr = len_arr / 2;
if(len_arr%2 != 0)
half_arr++;
int **m = malloc(half_arr * sizeof(int));
for (i = 0; i < half_arr; i++)
*m = malloc(half_arr * sizeof(int));
```
You should then be able to accessmusingm[row][column]orm[column][row].
|
While coding very simple program for removing blanks, tabs, newlines I came across something I don't actually catch on first; even thoughifcondition is true only when tab, space or newline doesn't exist it's still executed with the mentioned for some reason.. here is the code
```
#include <cstdio>#include <cstring>
```
```
#include <stdio.h>
#include <string.h>
#define LGT 100
void rem(char s[])
{
int i;
for(i=(strlen(s)-1);i>=0;i--)
if(s[i]!=' ' || s[i]!='\t' || s[i]!='\n')
break;
s[i+1]='\0';
}
int main(void)
{
char v[LGT]={"sdsfg\t"};
rem(v);
printf("%s\n",v);
getchar();
}
```
|
s[i]!=' ' || s[i]!='\t' || s[i]!='\n'isalwaystrue. A character can't be equal to both a space, a tab and a newline.
|
I find myself needing a hash table container in a C project which includes Lua. I am wondering if it is possible to use the hash table in Lua as a generic container. I have looked atltable.hand all of the functions require a Lua state and seem tied to the Lua environment so I am guessing this is not practical if the data needs to be independent of Lua.
|
It is possible and the easiest way is just to use the official C API for Lua. No need to dig into the innards of ltable.h.
|
It seems that some autoconf projects use aconfigure.infile to generate aconfigurescript, and some useconfigure.ac.
What is the difference/advantage between using one or the other?
|
Its just a matter of style. Historically autoconf files were namedconfigure.in. Nowconfigure.acis the preferred naming scheme. Its also discussed in thedocumentation.
|
I'm trying to format a number that has a value from 0 to 9,999. I would like the 2 most significant digits to always display, i.e.
5000 -> 500000 -> 00
If either of the least significant digits are non-zero they should be displayed, i.e.
150 -> 015101 -> 0101
It can be done with some hackery, but can C's printf do this directly?
|
Yes you can useprintffor this
```
int v = 5000;
if ((v % 100) != 0)
printf("%04d", v);
else
printf("%02d", v/100);
```
|
Can Instruments be used as a replacement for
valgrind
If one wants to check for memory leaks using instruments can it be used from the terminal?
|
Instruments has a command line interface:
```
$ instruments -h
```
Example usage:
```
$ instruments -t mytemplate -a myapp.app
```
For leaks, try theLeaks.tracetemplate. To see all available templates, use-s.
There is another executable, just calledleaks. You can inspect any running application by givingleaksits PID:
```
$ echo $$
620
$ leaks 620
leaks Report Version: 2.0
Process: bash [620]
Path: /bin/bash
Load Address: 0x100000000
...
Process 620: 37983 nodes malloced for 1123 KB
Process 620: 0 leaks for 0 total leaked bytes.
```
Read more about leaks in the Apple developerreference library.
|
Anyone please tell me where the main() function of the 'C' language returns its value?
|
C'smainfunction returns an int... that int goes to the program which executed it (the parent process, if you will) as an exit status code.
Specifically, on most operating systems, a 0 exit code signifies a normal run (no real errors), and non-zero means there was a problem and the program had to exit abnormally.
|
Working on a project that sends multicast data packets, and the receivers can opt in/out of the group as necessary. I noticed there are two ways of joining/leaving the groups: IP_ADD_MEMBERSHIP/IP_DROP_MEMBERSHIP and IP_ADD_SOURCE_MEMBERSHIP/IP_DROP_SOURCE_MEMBERSHIP. Couldn't get anything out the man pages here, so throwing this one out to the SO gurus. What's the difference, if any, and can you give an example of when to use one instead of the other?
|
IP_ADD_SOURCE_MEMBERSHIP and IP_DROP_SOURCE_MEMBERSHIP are for SSM (source specific multicast) support.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.