question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
in the following code :
```
int main()
{
int i = 15, j = 1;
int *a[] = {&i, &j};
printf("%d", (*a)[0]);
return 0;
}
```
the output of(*a)[0]is15(value of i) however when I tried to check(*a)[1]it gives a garbage value. I would expect that the same expression should work for all the entries in the a... |
Here you have declared array of pointers. At first you should know the various representation of array. How a[i] is calculate? a gives you the base address of array.
```
a[ i ] = *(a+i)
(*a)[0] = *(*a+0)
(*a)[1] = *(*a+1)
Thus the value of (*a)[0] = *(address of i + 0) = Value of i
And the value of (*a)[1] = *(a... |
I was writing a code to understandMPI_Comm_spawn. I found some examples in the Internet, all compiled and executed with sucess but when I put the follow statement: mpirun -np 2 ./program I received a error. So,MPI_Comm_spawnonly work with one process (-np 1)?
mpirun -np 1 ./executable - ok
mpirun -np 2 ./executable ... |
You can definitely spawn processes when you have more than 1 process. That example is just designed to only work with one process.Hereis an example of some code that will work with more than 1 process.
|
Suppose I haveunsigned long long x = 0x0123456789ABCDEF.
Which of the following is correct? (I can verify only the first one):
On a 32-bit little-endian processor, it will appear in memory as67 45 23 01 EF CD AB 89.On a 64-bit little-endian processor, it will appear in memory asEF CD AB 89 67 45 23 01.On a 32-bit bi... |
The first one is wrong. On ia32 at least the layout isEF CD AB 89 67 45 23 01.
The others are correct.
|
I was searching for a while and couldn't find any hints.
I am wondering right now: what is a common way of dealing with static function declarations in C? Because static functions aren't accessible from any other module than that which defines the function. I am not sure where to declare it.
My thoughts so far reach... |
Put the declaration of your static function inside the .c source file, in which it is defined and used. No other module will use it, so no other module needs to include the declaration, so there is no need to have it in a header file.
|
I have a signal handler for SIGABRT , when the signal is received, i need some more time for other threads to exit gracefully. Then I will do _exit() inside signal handler to exit the entire process.
But I am not sure how to wait inside a signal handler. I think there are some limitations for using sleep inside signa... |
There are no limitations of what kind of code you can execute inside a signal handler. You just have to keep in mind that another signal may arrive while executing your signal handler leaving you in the middle of half finished functions, locked mutexes or other things that should better remain uninterrupted.
Normally... |
I want the compiler to generate warning for me if structure declared without__attribute__(align(8)).
For example, if a structure is declared like this:
```
struct my_float {
float number;
} __attribute__((aligned(8)));
```
It will not generate any warning. But if I declare another struct like this:
```
st... |
I don't think you can automatically check this an ALL your structure, but you still can check your alignment manually with something like:
```
// x % 16 <=> x & (16-1) (avoid using modulo operator)
#define MODULO_16_MASK 0xFU
ASSERT_COMPILE((sizeof(my_float) & MODULO_16_MASK) == 0);
```
This should trigger a warnin... |
I've managed to build a native executable for Android, after readingHow do I build a native (command line) executable to run on Android?, but I can't execute it on my unrooted phone, it gives
/system/bin/sh: /storage/sdcard0/Download/hello_world: can't execute: Permission denied
because the SD card is mounted withno... |
I found a solution that works for me - it seems that/data/local/tmpis writable, and it isn't on anoexecpartition.
The solution requires usingadb. I connected the phone through USB, and I enabled USB debugging from developer options.
Then I uploaded the file to the phone using:
```
adb push C:\Workspace\hello_world\... |
How to find which data is currently union variable is holding out of the many fields present in the union without keeping extra variable to track it.
|
Unfortunately, you can't do this. All of the variables are holding some or all of the same data in memory, whether that data is meaningful or not.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question appears to be off-topic becauseit lacks sufficient information to diagnose the problem.Describe your problem in more detail orinclude a minimal examplein the question itself.Closed9 years ago.Improve this q... |
```
#include <stdio.h>
int main(int argc, char *argv[])
{
const char str[] = "q3";
char ch;
int num;
sscanf(str,"%c%d",&ch,&num);
printf("char: '%c' num: '%d'\n", ch, num);
return 0;
}
```
N.B. Watch the ampersands (&) in the sscanf(). Forgetting to put those in is a really common c... |
I want the compiler to generate warning for me if structure declared without__attribute__(align(8)).
For example, if a structure is declared like this:
```
struct my_float {
float number;
} __attribute__((aligned(8)));
```
It will not generate any warning. But if I declare another struct like this:
```
st... |
I don't think you can automatically check this an ALL your structure, but you still can check your alignment manually with something like:
```
// x % 16 <=> x & (16-1) (avoid using modulo operator)
#define MODULO_16_MASK 0xFU
ASSERT_COMPILE((sizeof(my_float) & MODULO_16_MASK) == 0);
```
This should trigger a warnin... |
I've managed to build a native executable for Android, after readingHow do I build a native (command line) executable to run on Android?, but I can't execute it on my unrooted phone, it gives
/system/bin/sh: /storage/sdcard0/Download/hello_world: can't execute: Permission denied
because the SD card is mounted withno... |
I found a solution that works for me - it seems that/data/local/tmpis writable, and it isn't on anoexecpartition.
The solution requires usingadb. I connected the phone through USB, and I enabled USB debugging from developer options.
Then I uploaded the file to the phone using:
```
adb push C:\Workspace\hello_world\... |
How to find which data is currently union variable is holding out of the many fields present in the union without keeping extra variable to track it.
|
Unfortunately, you can't do this. All of the variables are holding some or all of the same data in memory, whether that data is meaningful or not.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question appears to be off-topic becauseit lacks sufficient information to diagnose the problem.Describe your problem in more detail orinclude a minimal examplein the question itself.Closed9 years ago.Improve this q... |
```
#include <stdio.h>
int main(int argc, char *argv[])
{
const char str[] = "q3";
char ch;
int num;
sscanf(str,"%c%d",&ch,&num);
printf("char: '%c' num: '%d'\n", ch, num);
return 0;
}
```
N.B. Watch the ampersands (&) in the sscanf(). Forgetting to put those in is a really common c... |
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 do... |
If you're writing it in Python, you can usepycparser. It's a fully compliant C99 parser licensed under the 3-clause BSD license.
|
I can't comparemain()arguments withconst char*strings.
Simple code for explaining:
```
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
if(argc>1)
{
for (i=1;i<argc;++i)
{
printf("arg[%d] is %s\n",i,argv[i]);
if(argv[i]=="hello")
printf(" arg[%d]==\"hello\"\n",i);
... |
Strings can't be compared with==, usestrcmp:
```
if (strcmp(argv[i], "hello") == 0)
```
You have to#include <string.h>
|
How can an application find out that it just started terminating ? Can I use signal handler for that ?
|
Enableatexit(). It will call a function when program terminated normally.
Sample code:
```
#include <stdio.h>
#include <stdlib.h>
void funcall(void);
void fnExit1 (void)
{
printf ("Exit function \n");
}
int main ()
{
atexit (fnExit1);
printf ("Main function start\n");
funcall();
printf ("Main fu... |
I have a code similar to :
```
myThread()
{
pthread_cleanup_push(CleanupHandler , NULL)
while (true)
{
/* some code here */
}
pthread_cleanup_pop(NULL)
}
static void CleanupHandler(void *arg)
{
printf("Cleaned\n");
}
```
But if I terminate my application using ^C (SIGINT), the clea... |
Yes, this is expected, as per man page,pthread_cleanup_push()executes in following 3 circumstances:
```
1) When a thread is canceled
2) thread terminates using pthread_exit()
3) when pthread_cleanup_pop()
```
To workaround your problem you can register a signal handler for SIGINT, from that handler usept... |
So I have a defined a 8 bytes data structure
```
typedef struct __attribute__((__packed__)) entry{
// something here total 64 bits;
}entry_t;
```
and I have avoid* basewhich is a pointer pointing to the base of where I want to put the entry.
Will
```
entry_t a;
*base = a;
```
do the job?
or I have to cast ba... |
Either:
```
*((entry_t *)base) = a;
```
or
```
memcpy(base, &a, sizeof a);
```
Of course, make sure that there are in fact 8 bytes there to copy into.
|
I have googled already. I can't figure out what's going on.
This:
```
perror("some error message");
exit(0);
```
will print this to stdout:
"some error message: Success"
|
It isperrorprints out "Success", NOTexit(0).
The reason is that before the call ofperror, there is no error set (so theerrnois 0 which is its default value when the program starts). Soperrorprints outSuccess.
check this
http://www.cplusplus.com/reference/cstdio/perror/
|
I have a function which deallocates a cubic matrix ofdouble:
```
free_matrix(double ***U, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
free(U[i][j]);
}
free(U[i]);
}
free(U);
}
```
Then I have a cubic matrix of integerint ***matrix;. Compiler gi... |
Unfortunately not; per 6.2.5p28:
[...] Pointers to other types need not have the same representation or alignment requirements.
So there is no guarantee that aint **can be indexed the same way as adouble **, becauseint *anddouble *might e.g. have different sizes.
|
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 do... |
Since you tagged your question withC++, I suggestEigen.
|
I'm working with X11 and I've been looking for the reason why, in every program I've seen trying to create an image with XCreateImage, the parameter vis is set to "CopyFromParent".
I've already seethis questionin stackoverflow.
But the examples also use the same value.
¿Could anyone explain me the reason?
Thank you
|
It's one of Xlib's classes which says "copy the Visual class Type from the parent". Visual Type being "DirectColor", "PsuedoColor", "red_mask", "green_mask", "blue_mask", etc.
http://tronche.com/gui/x/xlib/window/visual-types.html#Visual
CopyFromParentis a flag saying "copy these values from the, typically the main ... |
I would like to make a conditional inclusion of a header file in my program. Is it possible and, if yes, how do I do it?
My idea is to do something like this:
```
switch(opt)
{
case 0:
{
#include "matrix.h"
break;
}
case 1:
{
#include "grid.h"
break;
}
}
```
That is h... |
Atcompile timeyou can have bit control ofconditional inclusion of a header file
```
#ifdef MAGIC
#include "matrix.h"
#else
#include "grid.h"
#endif
```
at compile time
```
gcc -D MAGIC=1 file.c
```
or
```
gcc file.c
```
But atrun-timeconditional inclusion of a header fileis not possible.
It means what your pse... |
```
void main() {
if(-1 > 0U)
printf("True\n");
else
printf("False\n");
}
```
Is it processor-dependent (big endian/little endian)?
|
FromC99 6.3.1.8:
[...] Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
Becauseintandunsigned inthave the same conversion rank ... |
I can't comparemain()arguments withconst char*strings.
Simple code for explaining:
```
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
if(argc>1)
{
for (i=1;i<argc;++i)
{
printf("arg[%d] is %s\n",i,argv[i]);
if(argv[i]=="hello")
printf(" arg[%d]==\"hello\"\n",i);
... |
Strings can't be compared with==, usestrcmp:
```
if (strcmp(argv[i], "hello") == 0)
```
You have to#include <string.h>
|
How can an application find out that it just started terminating ? Can I use signal handler for that ?
|
Enableatexit(). It will call a function when program terminated normally.
Sample code:
```
#include <stdio.h>
#include <stdlib.h>
void funcall(void);
void fnExit1 (void)
{
printf ("Exit function \n");
}
int main ()
{
atexit (fnExit1);
printf ("Main function start\n");
funcall();
printf ("Main fu... |
I have a code similar to :
```
myThread()
{
pthread_cleanup_push(CleanupHandler , NULL)
while (true)
{
/* some code here */
}
pthread_cleanup_pop(NULL)
}
static void CleanupHandler(void *arg)
{
printf("Cleaned\n");
}
```
But if I terminate my application using ^C (SIGINT), the clea... |
Yes, this is expected, as per man page,pthread_cleanup_push()executes in following 3 circumstances:
```
1) When a thread is canceled
2) thread terminates using pthread_exit()
3) when pthread_cleanup_pop()
```
To workaround your problem you can register a signal handler for SIGINT, from that handler usept... |
So I have a defined a 8 bytes data structure
```
typedef struct __attribute__((__packed__)) entry{
// something here total 64 bits;
}entry_t;
```
and I have avoid* basewhich is a pointer pointing to the base of where I want to put the entry.
Will
```
entry_t a;
*base = a;
```
do the job?
or I have to cast ba... |
Either:
```
*((entry_t *)base) = a;
```
or
```
memcpy(base, &a, sizeof a);
```
Of course, make sure that there are in fact 8 bytes there to copy into.
|
I have googled already. I can't figure out what's going on.
This:
```
perror("some error message");
exit(0);
```
will print this to stdout:
"some error message: Success"
|
It isperrorprints out "Success", NOTexit(0).
The reason is that before the call ofperror, there is no error set (so theerrnois 0 which is its default value when the program starts). Soperrorprints outSuccess.
check this
http://www.cplusplus.com/reference/cstdio/perror/
|
I'd like to convert Objective C code into plain C. I can do this by hand rather easily. For example this Objective C code:
```
[object method];
```
could be converted to something like:
```
SEL method = sel_registerName("method");
objc_msgSend(object, method);
```
However this is kind of tedious, especially for la... |
Short answer: No.
Longer answer: clang supports-rewrite-objc, but you are almost certainly not going to like the results.
|
I'm new to C, I have lines of code look like this:
```
char user[16];
fgets(user,16,stdin);
```
I typed "zeyang" on the keyboard, and I have another code:
```
char pwname[1000];
pwname="zeyang";
```
Then I usestrcmpto compare user and pwname:
```
strcmp(user, pwname);
```
The return value is a negative number, I... |
fgetsincludes the typed newline if there's room. You're comparing"zeyang\n"with"zeyang". From thefgets(3)man page:
The newline, if any, is retained.
|
I am calculating the volume of a room and I got a number with 6 decimal places. I was wondering if I can reduce the value to only 2 decimal places. The resulting number for the volume is from 5 different variables, which I do not know if it matters in this situation.
|
@Rashmi solution provides a nicely roundeddisplayof a floating point value.It does not change the value of the original number.
If one wants to round a floating point value to the nearest0.01useround()
```
#include <math.h>
double d = 1.2345;
d = round(d * 100.0)/100.0;
```
Notes:
Due to FP limitations, the rounde... |
I'm seeing this error:
```
*** glibc detected *** perl: double free or corruption (fasttop): 0x0000000003c1daa0 ***
```
The error is followed by a backtrace.
I know what glibc is, I know what Perl is, I know what double-freeing is, but what doesfasttopmean?
|
Usingthe source:
Another simple check: make sure the top of the bin is not the record we are going to add (i.e., double free).
So this is one of several locations where double free situations are detected. It affects so-calledfastbinchunks, which in turn depends on the size of the chunk you freed. In any case, the c... |
How do you do this:
```
printf("I would like %d tomatoes", numTomatoes);
```
with:
```
write(STDOUT, "HOW?", 4);
```
Is there some type of pre-processing that makes it all a char array and then I can find the length and print it out?
Context: I need to use write instead of printf inside of signal handlers.
|
To get a formatted string you can usesprintf/snprintf;
```
char buffer[0x1000];
size_t length = snprintf(buffer, sizeof(buffer), "I would like %d tomatoes", numTomatoes);
write(STDOUT_FILENO, buffer, length);
```
Edit:If you are bothered by the large buffer size then you can (in modern C99) do the following to deter... |
I write this code, which takes an integer number (t) as input from the user. A loop will be executed just 't' times. But I find that it runs for(t-1)times. For example, if I give input3, it runs only2times. Can anyone please explain why this is happening?
I tried and usedscanf("%s", &str), it works, but then I can't ... |
scanf("%d", &t)consumes only the numeral in the input stream and leaves the remaining characters. When you enter a numeral and press enter, there is a newline character after the numeral.
The firstgetsreads this newline and returns a string that is empty except for the newline. The first iteration of the loop prints ... |
```
#include <stdio.h>
int main(){
int i = 0;
do {
i++;
printf("In while loop\n");
} while (i < 3);
}
```
output:
```
In while loop
In while loop
In while loop
```
Why the printf statement is executed three times?
As soon as the loop starts the value of i becomes 1, so the loop should r... |
Pseudo code:
```
i = 1
=> In while loop
i = 2
=> In while loop
i = 3
=> In while loop
exit from loop
```
The condition is checked only at the end, after printf.
|
```
#include <stdio.h>
int main()
{
int x = 0;
if (x++)
printf("true\n");
else if (x == 1)
printf("false\n");
return 0;
}
```
Output:
```
false
```
Why is the output false?
x++is post increment; this means that the value ofxis used then it is in... |
In C,0is treated asfalse. Inx++, the value ofx, i.e,0is used in the expression and it becomes
```
if(0) // It is false
printf("true\n");
```
The body ofifdoesn't get executed. After thatxis now1. Now the condition inelse if, i.e,x == 1is checked. sincexis1, this condition evaluates totrueand hence its body gets... |
I have allocated memory using malloc() in embedded Linux (around 10 MB). And checked the free memory it was 67080 kB but even after freeing it using free() it remains the same. It is only after the application is terminated the memory is available again. Does free() not make the freed memory available to the system, i... |
freeis a libc library call. it marks heap space as available for reuse. It does not guarantee that the associated virtual mapping will be released. Only after a dirty virtual mapping is released by your OS, then that memory will be system wide free again. This can only happen in chunks of pages.
Also if you allocated... |
Test platform is Linux 32 bit.
I found a bug in my code, and I don't know why....
I simplified this code and put it here:
```
unsigned int aa = 0;
unsigned int array[10000];
unsigned int* ptr = array + 2000;
printf("aa: %d ", aa); // value 1
printf("ptr: %d \n", ptr); //value 2
printf("aa+ptr: %d \n", aa + ptr... |
In the second and third cases, you're passing a pointer to printf, but using %d as a formatter. You need %p.
ints and pointers are not interchangeable.
|
This is the code I have
```
const char *s[5];={"abcd","efgh","ijkl","mnop","qrst"};
char a[4];
while (1)
{
scanf("%4s",&a);
//compare a with s array
if(/*a exists in s*/)
printf("it is ok");
if(/*a does not exist in s*/)
printf("it is not ok");
}
```
For example when I ty... |
First declare your arraysaas
```
char a[5];
```
usefgetsto input string (do not usescanf), then usestrcmporstrncmpfunction to compare the two string/(literals).
|
I've got the main function:main(int argc, char *argv[]). I want to use these variables:argc,argvin other function:
```
int function()
int main(int argc, char *argv[])
{
...
function();
...
return 0;
}
int function()
{
int b=argc;
return 0;
}
```
but the compilator give error, thatargvis undeclared. How c... |
Pass them as arguments to your functions.
```
int function(int argc)
{
int b = argc;
return 0;
}
```
and call
```
function(argc);
```
inmain
|
I learnt that comparing a double using==is not a wise practice. However I was wondering if checking if a double has been initialized could be dangerous or not. For example, knowing that a variable doubleVar cannot be zero if it has been initialized, is it safe to do this?
```
Foo::Foo(){
doubleVar = 0.0; // of t... |
In IEEE-754, long story short:
```
double d;
d = 0.0;
d == 0.0 // guaranteed to evaluate to true, 0.0 can be represented exactly in double
```
but
```
double d;
d = 0.1;
d == 0.1 // not guaranteed to evaluate to true
```
|
I need to know how a thread can send its ID to another thread before it goes to wait state. I thought to pass a variable with its ID but I don't know how to do it.
|
If it's only one thread and its parent, you could use a global variable, as they are shared between all threads. Make itvolatilein case you expect concurrent access.
EDIT: I'm not sure if you're using POSIX threads on Linux but you probably have a way to pass a pointer (e.g. to astruct) when creating the thread. It c... |
If malloc calls VirtualAlloc() function to allocate memory (which allocates minimum 4Kb), how malloc allocates 4 bytes for int?
|
mallocrequests memory from the OS in multiples of thepage size(obviously, since the page size is by definition the quantum of allocated memory) and hands it out to you in smaller chunks.
That's not different than what all memory allocators do -- in fact, specialized memory allocators (e.g.Boost.Pool) that usemallocbe... |
Hey guys can we use two or moremain()in different C source files under same project in eclipse? What am I actually trying is to write a server and a client source file under same project with main() in each of it. I am getting an errormain() redeclaration. is there any way to do this? If yes please tell me how to run ... |
You could alsosimulatehaving twomainfunctions in the same project by havingmaincall eithermainClientormainServer(your two main functions renamed) depending on a condition of your choice.
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
What is the meaning of this statement in C?
```
struct foo *ptr = (struct foo *) p2;
```
|
Starting at the left hand side:
```
struct foo *ptr
```
declaresptrto be of typestruct foo *, that is a pointer tostruct foo.
The=initializes thatptrvariable to whatever the right hand side evaluates as.
And the right hand side
```
(struct foo *) p2
```
is an expression that castsp2to be of typestruct foo *.
|
What is a good way to create a double from a coefficient and a power of 10? Or in other words, what is a good way to create a double from the significand and the exponent of a written scientific notation value at runtime?
|
Not sure about numerical quality, but the obvious way would be:
```
double make_double(double coefficient, int power)
{
return coefficient * pow(10.0, power);
}
```
|
I foundthis very helpful exampleabout MenuLayers and it works very well. Inthis lineit is said that the method was defined in another file.
```
showDetail(cell_index); // Defined in detailView.c
```
As i compile and run, everything get´s called correctly. But im wondering how the compiler knows when to include this ... |
Pebble SDK useswafas its build tool. It is configured in thewscriptfile.
If you look at thewscriptfile of your Pebble project you will see the following lines:
```
def build(ctx):
ctx.load('pebble_sdk')
ctx.pbl_program(source=ctx.path.ant_glob('src/**/*.c'),
target='pebble-app.elf')
```
... |
What is the meaning of this statement in C?
wherefagis structure and its pointer ispat.
```
fag *pat = &h.device[d];
d = (pat - &(h.device[0]))/(sizeof(fag)) ;
```
|
```
fag *pat = &h.device[d];
```
takes the address od thedth element of the said array.
It can be used to ease the access to it.
If I do
```
d = (pat - &(h.device[0]))/(sizeof(fag));
```
where I don't have access to the originald, I get the index of the given entry, in the said array.
It takes the difference fro... |
This question already has answers here:C pointer to array/array of pointers disambiguation(12 answers)Closed9 years ago.
```
int (*ptr)[10];
```
I know whatint *ptr[10];its a 10 member array where each element is a pointer to an integer.
But what does the above piece code create ?
|
```
int *ptr[10]
```
is an array of 10intpointers,
int (*ptr)[10]
is a pointer to an array of 10ints
|
In C,
```
...
int num = 'a';
...
```
My question is simple. How can you assign a character such as '0', 'a', 'b' to an integer type variable without getting any type error in C language?
|
For historical reasons (mostly), character constants are of typeintin C.
But even if they weren't, an initialization like
```
int num = 'a';
```
or an assignment like
```
num = 'a';
```
would still be perfectly legal. A value of any numeric type may be assigned to a variable of any (other) numeric type, and the ... |
I have the following code which works fine for N=10 and C=25 but bombs with a segmentation fault if I use N=50 and C=25500
```
#include <stdio.h>
#include <stdlib.h>
// create table
int *table;
table = (int *) malloc(sizeof(int) * C+1 * N+1);
if(table == NULL){
printf("[ERROR] : Fail to allocate memory.\n");
}
/... |
I believe the amount of memory you are allocating is incorrect. You are allocatingC*sizeof(int) + N + 1and you want to be allocating(C+1)*(N+1)*sizeof(int)You're just missing some parens --http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
|
I'm implementing linked lists using structures. I have a structure -
```
typedef struct llist node;
typedef node *nodeptr;
struct llist
{
int data;
nodeptr next;
};
```
Now lets say I declare a variablenodeptr *ptr;. How do I access the membersdataandnextusingptr?
|
You deference the first pointer and then the second one.
To access the data and next in the structure statement would like this
```
(*ptr)->data = 5;
(*ptr)->next = temp;
```
brackets around ptr is required since->has higher priority than*.
->is equivalent to writing*.(e.g.ptr->datais the same as*ptr.data).
|
Is it possible to use a range when using memcpy or memcmp?
```
char data[900000]; // size 900000
char array[20]; // size 20
if (memcmp(data[50-70], array, 20) == 0) {
// do thing
}
```
I'd like to be able to compare the (20) keys data[50-70] with array[]
|
memcmp/memcpysimply take a pointer to the data you want to compare or copy.
Thus, you can essentially copy or compare any "range" by providing a pointer to the start of the data you wish to compare and the length of the data, pretty much as you have done above.
Adjust your code above as follows:
```
if (memcmp(&dat... |
I have some binary data in a file and load the file into memory atchar* data. Now I know e.g. that at offset 123 begins astruct something.
Is it safe to do the following
```
(struct something*) (data + 123) // ??&data [123]??
```
and then access members of the struct. Or should I do something like
```
struct somet... |
Yes, you should usememcpy, not pointer conversion, for exactly the reason you discuss: alignment. Converting pointers is not safe. If the alignment is wrong, the behavior when you use the resulting pointer is not guaranteed by the C standard.
An alternative in some situations is to read the data directly into the obj... |
I was curious if I could write C programs in the Mac Terminal. It seems yes, but when I start trying to use Strings, I get errors when compiling.
```
#include <stdio.h>
#include <string.h>
int main(void) {
string s = "chris";
printf("hello %s \n", s);
}
```
When I compile this I get a message saying... |
stringis a standard C++ library class. Useconst char *instead:
```
#include <stdio.h>
int main(int argc, const char **argv) {
const char *s = "chris";
printf("hello %s \n", s);
return 0;
}
```
|
What is the meaning of this statement in C?
wherefagis structure and its pointer ispat.
```
fag *pat = &h.device[d];
d = (pat - &(h.device[0]))/(sizeof(fag)) ;
```
|
```
fag *pat = &h.device[d];
```
takes the address od thedth element of the said array.
It can be used to ease the access to it.
If I do
```
d = (pat - &(h.device[0]))/(sizeof(fag));
```
where I don't have access to the originald, I get the index of the given entry, in the said array.
It takes the difference fro... |
This question already has answers here:C pointer to array/array of pointers disambiguation(12 answers)Closed9 years ago.
```
int (*ptr)[10];
```
I know whatint *ptr[10];its a 10 member array where each element is a pointer to an integer.
But what does the above piece code create ?
|
```
int *ptr[10]
```
is an array of 10intpointers,
int (*ptr)[10]
is a pointer to an array of 10ints
|
In C,
```
...
int num = 'a';
...
```
My question is simple. How can you assign a character such as '0', 'a', 'b' to an integer type variable without getting any type error in C language?
|
For historical reasons (mostly), character constants are of typeintin C.
But even if they weren't, an initialization like
```
int num = 'a';
```
or an assignment like
```
num = 'a';
```
would still be perfectly legal. A value of any numeric type may be assigned to a variable of any (other) numeric type, and the ... |
I have the following code which works fine for N=10 and C=25 but bombs with a segmentation fault if I use N=50 and C=25500
```
#include <stdio.h>
#include <stdlib.h>
// create table
int *table;
table = (int *) malloc(sizeof(int) * C+1 * N+1);
if(table == NULL){
printf("[ERROR] : Fail to allocate memory.\n");
}
/... |
I believe the amount of memory you are allocating is incorrect. You are allocatingC*sizeof(int) + N + 1and you want to be allocating(C+1)*(N+1)*sizeof(int)You're just missing some parens --http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
|
I'm implementing linked lists using structures. I have a structure -
```
typedef struct llist node;
typedef node *nodeptr;
struct llist
{
int data;
nodeptr next;
};
```
Now lets say I declare a variablenodeptr *ptr;. How do I access the membersdataandnextusingptr?
|
You deference the first pointer and then the second one.
To access the data and next in the structure statement would like this
```
(*ptr)->data = 5;
(*ptr)->next = temp;
```
brackets around ptr is required since->has higher priority than*.
->is equivalent to writing*.(e.g.ptr->datais the same as*ptr.data).
|
Is it possible to use a range when using memcpy or memcmp?
```
char data[900000]; // size 900000
char array[20]; // size 20
if (memcmp(data[50-70], array, 20) == 0) {
// do thing
}
```
I'd like to be able to compare the (20) keys data[50-70] with array[]
|
memcmp/memcpysimply take a pointer to the data you want to compare or copy.
Thus, you can essentially copy or compare any "range" by providing a pointer to the start of the data you wish to compare and the length of the data, pretty much as you have done above.
Adjust your code above as follows:
```
if (memcmp(&dat... |
I have some binary data in a file and load the file into memory atchar* data. Now I know e.g. that at offset 123 begins astruct something.
Is it safe to do the following
```
(struct something*) (data + 123) // ??&data [123]??
```
and then access members of the struct. Or should I do something like
```
struct somet... |
Yes, you should usememcpy, not pointer conversion, for exactly the reason you discuss: alignment. Converting pointers is not safe. If the alignment is wrong, the behavior when you use the resulting pointer is not guaranteed by the C standard.
An alternative in some situations is to read the data directly into the obj... |
I was curious if I could write C programs in the Mac Terminal. It seems yes, but when I start trying to use Strings, I get errors when compiling.
```
#include <stdio.h>
#include <string.h>
int main(void) {
string s = "chris";
printf("hello %s \n", s);
}
```
When I compile this I get a message saying... |
stringis a standard C++ library class. Useconst char *instead:
```
#include <stdio.h>
int main(int argc, const char **argv) {
const char *s = "chris";
printf("hello %s \n", s);
return 0;
}
```
|
I read somewhere that default floating point values like1.2aredoublenotfloat.So what are default integer values like6, are theyshort,intorlong?
|
The type of integer literals given in base 10 is the first type in the following list in which their value can fit:
intlong intlong long int
For octal and hexadecimal literals, unsigned types will be considered as well, in the following order:
intunsigned intlong intunsigned long intlong long intunsigned long long ... |
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed6 years ago.
Help me please understand the following expression:
(seen in a book)
```
*((int *)marks + i++) = i+1
```
A large number of increments and symbols dereference confusing!
|
I hope the book had this as a bad example, because the behavior of that is undefined.
(int *)marksinterpretsmarks(whatever that may be) as a pointer toint, then we have the result ofi++added to that. This pointer is dereferenced andi+1is assigned to the corresponding object.
This expression has no defined behavior b... |
Can you explain the different results:
```
$ file libc-2.8.so
libc-2.8.so: ELF 32-bit MSB shared object, PowerPC or cisco 4500, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.10, with unknown capability 0x41000000 = 0x13676e75, with unknown capability 0x10000 = 0xb0401, not stripped
```
N... |
You typically have to compile in debug mode (-gis the GCC command-line option) toincludethe debug symbols, it's not as if they're always there until stripped out. The default is to build in non-debug mode, without the symbols.
|
In C
we have
```
int B[2][3] = { {1, 2, 3}, {4, 5, 6} };
```
It is stored in memory as
```
1 2 3 4 5 6
int A[6]={1,2,3,4,5,6};
```
It is also stored in memory as
```
1 2 3 4 5 6
```
we can access A[6] by A[i] where i=0,2,3..
but we cannot access B[2][3] by B[i ] where i=0,1,2..
I know there... |
You can interpret them:
```
int B[2][3] = { {1, 2, 3}, {4, 5, 6} };
int* b = ( void* )B ;
for( int i = 0 ; i < 6 ; i++ )
printf("%d " , b[i] ) ;
```
The same goes for single arrays:
```
int A[6]={1,2,3,4,5,6};
int (*a)[3] ;
a = ( void* )A ;
for( int i = 0 ; i < 2 ; i++ )
for( int j = 0 ; j < 3 ; j++ )
... |
As i know, i can create an array with item inside such as:
```
char *test1[3]= {"arrtest","ao", "123"};
```
but how can i store my input into array like code above because i only can code it as
```
input[10];
scanf("%s",&input) or gets(input);
```
and it store each char into each space.
How can i store the input"... |
You need a 2 dimensional character array to have an array of strings:
```
#include <stdio.h>
int main()
{
char strings[3][256];
scanf("%s %s %s", strings[0], strings[1], strings[2]);
printf("%s\n%s\n%s\n", strings[0], strings[1], strings[2]);
}
```
|
Even after trying all orders of header file inclusion,
I still get the error for netinet/in.h
```
/usr/include/netinet/in.h:34: error: expected identifier before numeric constant
```
I have included the following header files
```
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <linux/if... |
netinet/in.hdoesn't have header guard so what's happening is some variable is already been defined innetinet/ip.hheader file. try pushingnetinet/in.hto beginning of the file.
|
Let's say I'm writing a C program which has:
```
int a = 1;
int b = 5;
int *p = &a;
```
Will:
```
int k = *(p+1);
```
always givek = 5?
Formally:
Is this "continuous" property of the variables' address on the stack implementation-dependant? If not, is anything guaranteed (for example&a < &b < &p)?
(This simpl... |
No...though it probably will on most platformsThere's absolutely no guarantee that your code will yield 5. What you have isundefined behaviour, which may result in your program craching. Never rely on undefined behaviour, full stop.
|
I've got some part of linux kernel sources:
```
#define wait_event_timeout(wq, condition, timeout) \
({ \
long __ret = timeout; \
if (!(condition)) ... |
This is aCproblem:__retis the return value of that macro. It is also written in thecomment above that macro
|
Bitwise Operators are pretty interesting so I tried figuring out a way to have the opposite effect of or, but not the effect of xor.
If I have two chars (8 bit):
```
char1 char2
===== =====
1010 1000
after transformation
1000 1000
```
If0010is the value I want to transfer char1 and char2 to disable ... |
The opposite oforisand-not. You can useorto set bits, andand-notto clear bits.
```
#include <assert.h>
int main() {
int a = 16, b, c;
// Set bit 3
b = a | 1<<3; // OR
assert(b == (8+16));
// Clear bit 3
c = b & ~(1<<3); // AND-NOT
assert(c == 16);
}
```
|
gcov primarily is a code coverage tool. However, is there any way we can find LOC (excluding comments...etc) with gcov?
It must be easy for gcov to get that information, but I didn't find any documentation on that.
Also, let me know if you know any other tool which can calculate lines of code in such manner.
|
You can also look atSLOCCount, which is available in packages on most Linux distributions.
|
I have to create an array in a struct and add different values each time the program receive a SIGUSR1 signal.
This is the code
```
if (signo == SIGUSR1){
signal(SIGUSR1, NewUser);
if (NewUser()<11){
i++;
struct users user[i] = {i,0,count};
pthread_create(&tid, NULL, (void*)Actions, ... |
Here is the correction...
```
user[i] = (struct user){i,0,count};
```
When you typestruct users user[i] = ...you are declaring anew variableinstead of assigning a value to an existing global variable.
|
I need to write a usb "driver" in Android that talks to our custom HID device. I have been able to open and get data from the device using android.hardware.usb from Java, but its much better for us to use a C .so file as all the other code is in C.
My problem is getting permissions for talking to the device without r... |
I found it is possible to change device permissions by modifying /ueventd.rc. This obviosuly requires you to build your own version of the OS (or be rooted which makes it pointless to change permissions in the first place).
|
I'm working on an App that I've made for both iOS and Android. On the iOS side, I use a constant TCP connection and JSON messages for the push notifications. I want to do the same thing for the android version, however I'm not sure if it's possible. I think using the Cloud Connection Serverhttp://developer.android.com... |
You can choose whatever programming language to desire to implement the server side. The question is whether you can find an easy to use XMPP C++ library for connecting to the Cloud Connection Server.
I assume it will be easier to find an HTTP C++ library for sending HTTP requests to the GCM HTTP Connection Server. I... |
my project must be "not CDT project". I'm building it by Makefile from command line, and its build correctly. But whole project in Eclipse in many places have unresolved errors. Not all statements are unresolved. It's looks randomly on first shoot (but its not).
I'm don't know where to add paths (I knows path to unre... |
CheckProject->Properties->C++ General->Path and Symbolsand set your include path's there. Rerun the indexer on the project afterwards.
Such a project is called a 'Makefile' project BTW, of course it's still a CDT project!
|
I'm confused by the output of the following bit of code:
```
float a = 1.32;
int* b;
b= &a;
printf("%d", *b);
```
This bit of code turns the float into an int, but the output I'm getting is: 1068037571
Is this related to the IEEE 754 converting capabilities of the computer?
Thanks!
|
Your program invokes undefined behaviour. You are simply reinterpreting the representation of thefloatas anint. You are categorically not converting anintto afloat. You cannot expect any particular behaviour.
To convert the float into an int you would use code like this:
```
int b = a;
```
which truncates thefloatt... |
I want to know if it is possible, using C and the WindowsAPI, if there is a function that will get me the 32 bit(I think) memory address of a function in a dll. For example. How do I get the 32 bit $xxxxxxxx address of Beep() in kernel32.dll. Secondly, if I use the memory address instead of the function name in assemb... |
This program will print the address ofBeepin kernel32:
```
#include <windows.h>
#include <stdio.h>
int main(void)
{
HMODULE hMod = GetModuleHandle("kernel32.dll");
void* fn = GetProcAddress(hMod, "Beep");
printf("%p", fn);
}
```
I omitted error checking for the sake of simplicity. In a real program you ... |
I read somewhere that default floating point values like1.2aredoublenotfloat.So what are default integer values like6, are theyshort,intorlong?
|
The type of integer literals given in base 10 is the first type in the following list in which their value can fit:
intlong intlong long int
For octal and hexadecimal literals, unsigned types will be considered as well, in the following order:
intunsigned intlong intunsigned long intlong long intunsigned long long ... |
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed6 years ago.
Help me please understand the following expression:
(seen in a book)
```
*((int *)marks + i++) = i+1
```
A large number of increments and symbols dereference confusing!
|
I hope the book had this as a bad example, because the behavior of that is undefined.
(int *)marksinterpretsmarks(whatever that may be) as a pointer toint, then we have the result ofi++added to that. This pointer is dereferenced andi+1is assigned to the corresponding object.
This expression has no defined behavior b... |
I tried compiling using gcc it gives me
```
$ gcc demo.c -o samp.o
```
```
/tmp/cclnweNC.o: In function `main':
demo.c:(.text+0x12b): undefined reference to `aes256_init'
demo.c:(.text+0x142): undefined reference to `aes256_encrypt_ecb'
demo.c:(.text+0x1b2): undefined reference to `aes256_init'
demo.c:(.text+0x1c9... |
You want something like:
```
$> gcc demo.c aes256.c -o demo
```
|
I'm trying to create a folder inside /var/mobile/Library/MyAppName. I read on internet that I must use the command:
```
mkdir(“/var/mobile/Library/YOURAPPNAME”, 0755);
```
but xcode cannot recognize that command... how can I solve?
|
Formkdir(), add
```
#include <sys/stat.h>
```
You can get this information from "man 2 mkdir" on the command line,
or fromhttp://pubs.opengroup.org/onlinepubs/009695399/functions/mkdir.html.
|
I tried compiling using gcc it gives me
```
$ gcc demo.c -o samp.o
```
```
/tmp/cclnweNC.o: In function `main':
demo.c:(.text+0x12b): undefined reference to `aes256_init'
demo.c:(.text+0x142): undefined reference to `aes256_encrypt_ecb'
demo.c:(.text+0x1b2): undefined reference to `aes256_init'
demo.c:(.text+0x1c9... |
You want something like:
```
$> gcc demo.c aes256.c -o demo
```
|
I'm trying to create a folder inside /var/mobile/Library/MyAppName. I read on internet that I must use the command:
```
mkdir(“/var/mobile/Library/YOURAPPNAME”, 0755);
```
but xcode cannot recognize that command... how can I solve?
|
Formkdir(), add
```
#include <sys/stat.h>
```
You can get this information from "man 2 mkdir" on the command line,
or fromhttp://pubs.opengroup.org/onlinepubs/009695399/functions/mkdir.html.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question
just trying to test socket programming. I am thinking to create a project and write both ... |
Yes you can. but if you're using an IDE (eclipse, or something else you prefer) it would be easier for you to do it in separate projects, as you can just build & run each one and both projects will run in parallel, and then the server & client will be able to communicate with each other.
When they are in the same pro... |
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question appears to be off-topic becauseit lacks sufficient information to diagnose the problem.Describe your problem in more detail orinclude a minimal examplein the question itself.Closed9 years ago.Improve this q... |
This should do the trick:
```
for(i=0;i<x;i+=5)
{
for(j=i;((j<i+5) && (j<x));j++)
{
printf("%d,",a[j]);
}
//Wait for next character here
printf("\nnext\n");
}
```
Edit: Fixed an issue with the code for arrays of non-multiples of 5.
|
How do I assign the highest nibble (4 bits) in one register (8 bits), to the highest nibble of another register in one step? without altering the 4 LSbs?
Here is my proposed solution, when I can do it in two steps, but I believe there is more ingenious solution to do it in only one step (maybe with less gates or inst... |
```
A = (A & 0x0F) | (B & 0xF0)
```
(Note that this operation requires zero gates, though...)
|
```
#include <stdio.h>
int main()
{
reverse(1);
return 0;
}
void reverse(int i)
{
if (i > 5)
exit(0);
printf("%d\n", i);
return reverse(i++);
}
```
How this recursion is working?
When I am running it1is printed infinitely. I expected the ... |
when the++operator isafterthe variable, it does a "postincrement" oparation, so while it increments theivariable just before discarding it, theexpressionresult is theoriginalvalue ofi, so the function is called with the same value every time.
|
```
#include <stdio.h>
void main()
{
int k = 8;
int m = 7;
int z = k < m ? k = m : m++;
printf("%d", z);
k = 8;
m = 7;
z = k < m ? m++ : k=m;
printf("%d", z);
}
```
Output
```
Compile Error:
main.c: In function 'main':
main.c:19:32: error:... |
Due tohigher precedenceof?:conditional operator in comparison to=
```
z = k < m ? m++ : k=m;
```
Is equivalent to (or say parse as):
```
z = ((k < m ? m++ : k) = m);
// ^^^^^^^^^^^^^^^^
// expression = m
```
mis assigned to an expression that is -Lvalueerror.
ReadConditional operator diffe... |
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed9 years ago.Improve this question
I need some help with writing such program which would read a .txt file containing... |
```
float x,i=~(257<<23),a,s,t;main(int n,char**f){a=-i;f=fopen(f[1],"r"
);for(n=0;fscanf(f,"%f",&x)>0;n++,s+=x,x<i?i=x:0,x>a?a=x:0,t+=x*x);
printf("%d %f %f %f %f\n",n,a,i,s/n,sqrtf(t/n));}
```
Sorry for the long code. Didn't have time to make it shorter.
|
Okay, I need to use md5() function from OpenSSL library, but when I compile gcc gives me an error - "undefined reference to md5". I tried few things, which I found in different StackOverFlow questions, but still no effect.
First of all I installed packages (Ubuntu 13.04):
sudo apt-get install opensslsudo apt-get ins... |
It looks like that your OpenSSL is compiled withno-md5option. So, download OpenSSL and build it with md5 if required.
|
I have a statically linked executable compiled from a C program.objdump -x a.outindicates the presence of the.eh_framesection, even afterstrip -s.Why is this section useful in a C(non-C++) program?What are the risksof stripping it (withstrip -R .eh_frame)?
|
From remyabel's comment and OP's confirmation, the answer to the OP question is available via another SO question as linked by:
Why GCC compiled C program needs .eh_frame section?
|
So I have thischar const* blahblahblah(const char* s)function but when I try to usestrcat(s, " ")orreturn s[k]in it it says
```
const char*s
Error: argument of type "const char*" is incompatible of parameter of type "char"
```
If I want the function to stay as is what should I change in my parameters in order for it... |
If you declare const char* s, then you should not write strcat(s, " "), because strcat modifies s.
if you declare char const* reverseWordsOnly, then why do you return s[k]? s[k] is not a pointer.
EDIT:
This depends on what you want to do. I don't know what you want to do in this function.
If you don't modify s, the... |
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed9 years ago.Improve this question
I've got a question regarding an assignment i've been given.
-There are two integ... |
Your code is equivalent to this one:
```
int a = -1;
int b = 1;
a += 1;
if (a == 0) {
b += a;
a += 1;
}
```
You should see why both variables end up as 1 here. Now try to figure out why these codes are equivalent.
|
This question already has answers here:How dangerous is it to compare floating point values?(12 answers)Closed9 years ago.
Look at the output ofthis link(scroll down to see the output) to find out what I'm trying to accomplish
The problem is with theforloop on line number 9-11
```
for(i=0; i<=0.9; i+=0.1){
printf... |
Using float here is source of problem. Instead, do it with an int:
```
int i;
for(i = 0; i <= 10; i++)
printf("%6.1f ", (float)(i / 10.0));
```
Output:
```
0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
```
|
This question already has answers here:MIN and MAX in C(16 answers)Closed9 years ago.
Is there any library function incfor finding out the largest number between two numbers?
|
You can do
```
#define new_max(x,y) (((x) >= (y)) ? (x) : (y))
#define new_min(x,y) (((x) <= (y)) ? (x) : (y))
```
valter
|
I'm "trying" to study the Pcap library. Currently I'am using a Windows machine so I downloaded the Winpcap Dev pack. I would like to know the content of the function pcap_sendpacket. I searched the source files in the Winpcap Dev pack and only found the function in a header file, which doesn't contain the body of the ... |
I downloaded 4.1beta5_WpcapSrc.zip fromhttp://www.winpcap.org/archive/and that appears to contain full source code. The function you refer to,pcap_sendpacketis defined inwpcap\libpcap\pcap.c.
|
The following definition in limits.h header of GNU C compiler,
```
#define LONG_MAX 2147483647L
```
The L suffix used indicates the number 2147483647 should be treated as a long integer literal. But the statement is actually the definition of long integer, so doesn't using L as suffix make the definition circular... |
This is not a definition of a type, this is a literal constant.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.