question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
Why issizeofgiving the wrong output?What is meant byvoid pointer? Why is it 4 bytes?
In this code:
```
struct s1
{
int p;
void *q;
char r;
};
struct s2
{
int p;
char r;
void *q;
};
int main()
{
struct s1 s;
struct s2 r;
printf("%d %d",sizeof(s),sizeof(r));
printf("\n");
pr... |
It is not giving wrong output. The size of int on your system would be 4, the size of a void pointer also 4, and while char can usually be 8 bits long, the struct itself will not be 9 bytes long, as most systems are at least 32 bit, so the compiler is "padding" them to be multiples of 4 bytes.
A void pointer is just a... |
Canstdoutfile descriptor differ from1(STDOUT_FILENO) assumingstdoutneed not be a modifiable lvalue?
For example, canfreopen("/dev/null", "w", stdout)changefileno(stdout)result?
|
Yes.
Test program:
```
#include <stdio.h>
int main() {
fclose(stdin);
freopen("stdout.txt", "w+", stdout);
fprintf(stderr, "%d\n", fileno(stdout));
return 0;
}
```
This prints 0 on my machine (OS X 10.9.4).
File descriptors are typically reused starting from the lowest number first. By closingstdi... |
I've just seen a strange part of code in the David Griffiths book "Head First C", part 6:
```
island* start = NULL; island* i = NULL;
island* next = NULL;
char name[80];
for(; fgets(name, 79, stdin) != NULL; i = next) {
next = create(name);
if (start == NULL)
start = next;
if (i != NULL)
... |
Yes, it works.
fgets returns NULL if there is an Error or there is no next word typed in.
|
If I uselua_getfield()and read a table from an already existing table, how can I add this table to another table? As far as I understand, this "adding" will be a "referencing" instead of a real copy, right?
|
Yes. In fact, it is rather involved to create a copy of table.
A table doesn't have an owner. You only ever have references; You can have as many as you copy around. When there are none accessible to the garbage collector, the table is eligible for deletion. (The same goes for function values.)
|
The code:
```
struct result
{
char won[MAX_NAME_LEN+1];
char lost[MAX_NAME_LEN+1];
};
void add_to_scoreboard(struct result * scoreboard,
struct result * latest_game)
{
if (latest_game = struct result * won)
{
}
}
```
When I try to compile this I get the error:
```
error: expected expression before ... |
You can access thewonproperty oflatest_gamewithlatest_game->wonrather thanlatest_game = struct result * won
|
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
ltrace mylsshould give output with no library calls.
I wish to implement ls with -(paramenters) too and dir... |
Usegetdents(2), the low-level Linux system call for reading a directory. Make sure you read theNotessection: you have to usesyscallto call this, there's no library wrapper. TheExamplethere is a simplelsprogram that uses it.
|
A bug was found in "mod_authn_core.c" which is an Apache module and a fix has been given to it,
it has been given in the simplest form of .c file (C code)
apparently i need to compile it and replace my existing module file and it should work
Bug Report in Apache forums
Suggested (Working) patch to be replaced with... |
well i found out that apache2 has a built in compiler for mods called apxs2:
```
sudo apxs2 -c -i mod_authn_core.c
echo “LoadModule mod_authn_core /usr/lib/apache2/modules/mod_authn_core.so” > /etc/apache2/mods-available/mod_authn_core.load
```
|
With printf it is perfectly normal to do:
```
int dec = 3;
float n = 4.3232;
printf("%.*f", dec, n);
```
But in scanf() I want to replace 100
```
scanf(%100[^~], string)
```
with something like:
```
int a = 100;
scanf(%[***somtehing goes here***][^~], a, string);
```
But I didn't manage to do it.
Not sure if it... |
For your stated purpose it's probably better to do this:
```
fgets(string, a, stdin);
```
http://linux.die.net/man/3/fgets
|
I have inherited some heavily obfuscated and poorly written PIC code to modify. There are two macros here:
```
#define TopByteInt(v) (*(((unsigned char *)(&v)+1)))
#define BottomByteInt(v) (*((unsigned char *)(&v)))
```
Is anyone able to explain what on earth they do and what that means please?
Thanks :)
|
They access a 16-bit integer variable one byte at a time, allowing access to the most significant and least significant byte halves. Little-endian byte order is assumed.
Usage would be like this:
```
uint16_t v = 0xcafe;
const uint8_t v_high = TopByteInt(&v);
const uint8_t v_low = BottomByteInt(&v);
```
The above ... |
In the program below, I'm trying to count the characters in a line
```
#include <stdio.h>
/* count characters in input; 1st version */
int main()
{
double nc;
for (nc = 0; getchar() != EOF; ++nc)
;
printf("%.0f\n", nc);
}
```
But the lineprintf("%.0f\n", nc)is not getting executed
The resul... |
EOFis only end offile, not end of line. Seethe documentation. So when you hit enter, your program stays in thatforloop. You can fix this one of two ways:
Actually send your programEOF(Ctrl-Don most *nix-based systems), orcheck for a newline instead ofEOF.
Try this:
```
for (nc = 0; getchar() != '\n'; ++nc)
```
Not... |
Allocating memory for structure element in heap but i am getting segmentation fault please help me to fix
```
#include<stdio.h>
struct st
{
int i;
int *p;
char ch;
};
int main()
{
struct st *q; // creating object pointer *q
int i=89;
q->p=malloc(10);
printf("%d\n",*((q->p)-1))... |
struct st *q;declares a pointer to struct only.qpointing at unknown memory location. You need to allocate memory forqtoo otherwise it will invoke undefined behavior.
```
struct st *q = malloc(sizeof(struct st));
```
Also ,q->p=&i;will cause memory leak.
|
Alright so I have a array of string literals
```
char* messages[] = {
"t",
"123",
"test3",
"test4",
"test5",
"test1000"
};
```
I want to make a pointer to the array, I make it like so:
```
char *(*p)[6] = &messages;
```
I was wondering why is it that
```
p[0][3];
```
returns "test4" when... |
The line
```
char *(*p)[6] = &messages;
```
definespto be a pointer that points toan array of 6 pointers to char.
That means:
```
*p == messages
p[0] == messages
(*p)[3] == messages[3]
p[0][3] == messages[3]
```
However,p[1]is invalid sincepis not an array. You are going to see undefined behavior (segmentation v... |
like this code
```
fp1=fopen("Fruit.txt","r");
if(fp1==NULL)
{
printf("ERROR in opening file\n");
return 1;
}
else
{
for(i=0;i<lines;i++)//reads Fruits.txt database
{
fgets(product,sizeof(product),fp1);
id[i]=atoi(strtok(product,","));
strcpy(name[i],strtok(NULL,","));
... |
REF:
Used a random online tool to generate this flowchart from your code.http://code2flow.com/
Study more about flowcharts here :http://creately.com/blog/diagrams/flowchart-guide-flowchart-tutorial/
See sample flowcharts here :http://www.conceptdraw.com/samples/flowcharts
|
I have a problem with the code below.
```
...
int anInteger;
...
//anInteger gets a value
...
int *anotherInteger;
label = (int *)malloc(sizeof(int));
strncpy(anotherInteger, anInteger, 40);
```
Essentially what I want to do is to copy the value from an integer to my other integer which I have allocated memory for.... |
Just dereferenceanotherInteger.
```
*anotherInteger = anInteger;
```
strncopyis for strings.
|
I need to know if there is 3 d array say :
```
int a[2][3][2]={{{1,2},{9,8},{3,7}},{{2,2},{1,4},{5,4}}};
```
How And what does the expression a[1]-a[0] calculate?
|
what does the expression a[1]-a[0] calculate?
It calculates the difference between the pointers to whicha[1]anda[0]decay if use as operators to the arithemtic operator-.
|
Third argument in memcmp should be of type sizeof(). I read this code with the following
```
memcmp(st.magic, "outpt_01",sizeof(st.magic)) == 0 && st.version == 0 )
```
wherestis a struct.
What is the type of the third parameter in the call above? what is it doing ?
|
What is the type of the third parameter in the call above?
size_tNumber of bytes to compare.
what is it doing ?
```
if (sizeof(st.magic) == 0 && st.version == 0)
memcmp(st.magic, "outpt_01", 1);
else
memcmp(st.magic, "outpt_01", 0);
```
As pointed out by @JoachimPileborg, there is a typo in:
```
memcmp(st... |
I found this code in page no. 127 ofthis Bookwriter says it print 42. But when i try this it prints some garbage value. Why this is so?
```
#include <stdio.h>
void foo()
{
int a ;
printf("%d \n", a);
}
void bar()
{
int a = 42;
}
int main()
{
bar();
... |
ainfoo()is uninitialized, so it's undefined behavior.
However, in practice, some compilers actually do output42(especially if optimization is off). That's because after the call ofbar(), the value42is left in the stack. And insidefoo(), the uninitializedagets it. Again, it's undefined behavior so anything may happen... |
I was just reading a tutorial for bitwise operators and I don't understand why this number is -61.
```
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );
```
shouldn't 11000011 be 195... |
No it shouldn't be!
you probabely want to useunsigned charfor all your parameters
```
unsigned char a = 60;
unsigned char b = ~a;
char c = ~a;
printf("b=%d\nc=%d\n", b, c);
```
gives the output :
```
b=195
c=-61
```
|
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
Correct me if I'm wrong, but in the C/C++ heap has no limit, you do not need to pass any ... |
There are several reasons:
first you have the minimum heap size, which is there to prevent slow startupthe max heap size is there so that the GC knows when to start doing it's job, without it it would be much harder (but doable, you would just need to take into account different heuristics like number of allocations ... |
I have some arrays that are declared like this:
```
static double covalent_radius[256] = {
[ 0 ] = 0.85,
[ 1 ] = 0.37,
...
};
```
C++ doesn't allow this kind of declaration. Is there any way to achieve this?
|
```
static double covalent_radius[256] = {
0.85, /* ?, Unknown */
0.37, /* H, Hydrogen */
...
};
```
It's C89, not C99 so I suppose it should work.
|
I'm trying to use a library called pvcam (Photometrics Virtual Camera Access Method) with ctypes. This proprietary library is distributed as a compiled shared object (.so file) with a Software User Manual and works fine for C development.
I would like to wrap this library with ctypes so I can use python instead of C.
... |
Try loading the required library beforehand:
```
ctypes.CDLL('libraw1394.so.X.Y', mode=ctypes.RTLD_GLOBAL)
ctypes.CDLL('libpvcam.so.2.7.4.2', mode=ctypes.RTLD_GLOBAL)
```
|
Third argument in memcmp should be of type sizeof(). I read this code with the following
```
memcmp(st.magic, "outpt_01",sizeof(st.magic)) == 0 && st.version == 0 )
```
wherestis a struct.
What is the type of the third parameter in the call above? what is it doing ?
|
What is the type of the third parameter in the call above?
size_tNumber of bytes to compare.
what is it doing ?
```
if (sizeof(st.magic) == 0 && st.version == 0)
memcmp(st.magic, "outpt_01", 1);
else
memcmp(st.magic, "outpt_01", 0);
```
As pointed out by @JoachimPileborg, there is a typo in:
```
memcmp(st... |
I found this code in page no. 127 ofthis Bookwriter says it print 42. But when i try this it prints some garbage value. Why this is so?
```
#include <stdio.h>
void foo()
{
int a ;
printf("%d \n", a);
}
void bar()
{
int a = 42;
}
int main()
{
bar();
... |
ainfoo()is uninitialized, so it's undefined behavior.
However, in practice, some compilers actually do output42(especially if optimization is off). That's because after the call ofbar(), the value42is left in the stack. And insidefoo(), the uninitializedagets it. Again, it's undefined behavior so anything may happen... |
I was just reading a tutorial for bitwise operators and I don't understand why this number is -61.
```
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );
```
shouldn't 11000011 be 195... |
No it shouldn't be!
you probabely want to useunsigned charfor all your parameters
```
unsigned char a = 60;
unsigned char b = ~a;
char c = ~a;
printf("b=%d\nc=%d\n", b, c);
```
gives the output :
```
b=195
c=-61
```
|
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
Correct me if I'm wrong, but in the C/C++ heap has no limit, you do not need to pass any ... |
There are several reasons:
first you have the minimum heap size, which is there to prevent slow startupthe max heap size is there so that the GC knows when to start doing it's job, without it it would be much harder (but doable, you would just need to take into account different heuristics like number of allocations ... |
I have some arrays that are declared like this:
```
static double covalent_radius[256] = {
[ 0 ] = 0.85,
[ 1 ] = 0.37,
...
};
```
C++ doesn't allow this kind of declaration. Is there any way to achieve this?
|
```
static double covalent_radius[256] = {
0.85, /* ?, Unknown */
0.37, /* H, Hydrogen */
...
};
```
It's C89, not C99 so I suppose it should work.
|
I'm trying to use a library called pvcam (Photometrics Virtual Camera Access Method) with ctypes. This proprietary library is distributed as a compiled shared object (.so file) with a Software User Manual and works fine for C development.
I would like to wrap this library with ctypes so I can use python instead of C.
... |
Try loading the required library beforehand:
```
ctypes.CDLL('libraw1394.so.X.Y', mode=ctypes.RTLD_GLOBAL)
ctypes.CDLL('libpvcam.so.2.7.4.2', mode=ctypes.RTLD_GLOBAL)
```
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a book, tool, software library, tutorial or other off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the prob... |
-lmlinks your program against math library, neededon some platformswhen you use functions from<math.h>
|
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed9 years ago.
I wish to know that why this code shows different Output on different compilers.
Here's the Code:-
```
int a = 5;
printf("%d %d",a++,++a);
```
Output:- 6 7 (Visual Studio)
... |
This is undefined behavior and it depends on the compiler which you are using. And to add it has nothing to do with the order of precedence.
You may checkPrecedence and Order of Evaluation
Also from C99 standard:
The order of evaluation of the operands is unspecified. If an attempt
is made to modify the result of... |
If I do
```
LoadLibrary("MyTest.dll")
```
Windows will locate and load it from"C:\TestFolder\Test\MyTest.dll", because"C:\TestFolder\Test\"is in%PATH%folder.
How can I emulate same function? I need to locateC:\TestFolder\Test\MyTest.dll(C:\TestFolder\Test\is in%PATH%) by passingMyTest.dllas an argument to a functio... |
To load the DLL without running any malicious code inside, useLoadLibraryExwith theDONT_RESOLVE_DLL_REFERENCESandLOAD_LIBRARY_AS_DATAFILEflags.
Then you can useGetModuleFileName.
You should also read about all the other flags, which allow you to perform all the various searches Windows is capable of.
|
Today I was asked a C question in a company where i have to find the sum of all divisors of elements of an array individually except itself and store each sum in the same array.For example if array consists of {10,4,6}.Then for 10,it should store 1+2+5=8 in place of 10,then for 4,1+2=3 and so on.I was given 4 variabl... |
Since you said you're given the array size as avariablen, feel free to use it as a loop counter:
```
while (n > 0) {
--n;
temp = 0; // the sum
for (i = a[n] - 1; i > 0; --i) {
if (a[n] % i == 0) {
temp += i;
}
}
a[n] = temp;
}
```
|
I'm trying to understand a piece of code shown below. I'm having problems with understanding what "array +7" or "array,+3" means. Does it increment the first number in the array by 7/3?
```
int array[8] = {1,2,4,8,16,32,64,128};
int *ptr_array[4];
int *dyn_array = malloc(sizof(int)*8);
ptr_array[0] = array;
ptr_arr... |
array + 7is a pointer to the eight element of the array, it's equal to&array[7], becausex[y]is defined as*(x + y).
|
I am using netbeans IDE for my C++ implementation. I have two source files main.cpp and univ.cpp. And i defined a function show() in univ.cpp. How can i call this function from main. When i call normally like below, i get "show() not in scope".
```
int main(int argc, char**argv)
{
show();
return 0;
... |
You should create a header for univ called univ.h here would be the code:
```
#ifndef _UNIV_H_
#define _UNIV_H_
void show();
#endif
```
The you will need to include it in both cpp files.
```
#include <univ.h>
```
|
I just want to make sure, if i declare an array in the main.c function or any other function, and pass is to an other function which stores information into the array. Is the information stored in the array when i use it outside the function I stored the information in?
|
This simple example will clear your doubt.
```
#include <stdio.h>
#include <string.h>
void func ( int arr[] )
{
int i;
for(i=0;i<10;i++)
arr[i]=i;
}
int main(int argc, char** argv)
{
int arr[10],i;
func(arr);
for(i=0;i<10;i++)
printf("%d\n",arr[i]);
return 0;
}
```
output:
```
0
1... |
HI i am unable to figure out how function pointer is typedef in below code .please can anyone explain
```
#include<stdio.h>
typedef int(*fp)(int,int) ; this is typedef with function pointer i m unable to figure out?
int sum (int,int);
int main()
{
fp p,q; // p, q become function pointer too how?
p=sum;
... |
Well, there's not much to understand. You define a new type int(*fp)(int, int). This is not a function pointer, but a function pointer type. Compare fp to float, int, or any other primitive types. Then you declare p and q of the above mentioned type and assign to p the function sum which is of the same type (implicit)... |
How can I make my input string S1 of the fgets (or similar statement) to be equal to my declared static string S2?
```
#include <stdio.h>
#include <string.h>
main() {
char s1[80];
char s2[] = "This is a test.";
int l1, l2;
system("clear");
printf("%s\n\n", s2);
printf("Please type exactly th... |
You're doing a pointer comparison, not a string comparison. To compare the content of the strings, usestrcmp(docs):
```
if (strcmp(s1, s2) == 0)
...
```
|
Can someone explain why this expression produces 1 as result?
```
i = 1 && 2 + 3 | 4;
```
What is exactly the order of the operations here?
|
```
i = (1 && ((2 + 3) | 4)))
```
Boolean expression in C always evaluates to 0 or 1. Anything that's not 0 is considered true.
1 != 02 + 3 == 55 | 4 == 5 (| is the bitwise or operator)5 != 01 && 5 == 1
|
when a DLL comes with plain, undecorated C-functions, this DLL itself does not contain any information regarding parameters and return types of these functions.
So when I want to use such a DLL out of a C# application: how/where do I define the types of these functions in my C#-code?
Thanks
|
If you want to use win32-Libraries just have a look athttp://www.pinvoke.net/, there are many samples of how to invoke win32 calls and how to handle datatypes/conversions. Hope that helps.
|
I'm trying to understand a piece of code shown below. I'm having problems with understanding what "array +7" or "array,+3" means. Does it increment the first number in the array by 7/3?
```
int array[8] = {1,2,4,8,16,32,64,128};
int *ptr_array[4];
int *dyn_array = malloc(sizof(int)*8);
ptr_array[0] = array;
ptr_arr... |
array + 7is a pointer to the eight element of the array, it's equal to&array[7], becausex[y]is defined as*(x + y).
|
I am using netbeans IDE for my C++ implementation. I have two source files main.cpp and univ.cpp. And i defined a function show() in univ.cpp. How can i call this function from main. When i call normally like below, i get "show() not in scope".
```
int main(int argc, char**argv)
{
show();
return 0;
... |
You should create a header for univ called univ.h here would be the code:
```
#ifndef _UNIV_H_
#define _UNIV_H_
void show();
#endif
```
The you will need to include it in both cpp files.
```
#include <univ.h>
```
|
I just want to make sure, if i declare an array in the main.c function or any other function, and pass is to an other function which stores information into the array. Is the information stored in the array when i use it outside the function I stored the information in?
|
This simple example will clear your doubt.
```
#include <stdio.h>
#include <string.h>
void func ( int arr[] )
{
int i;
for(i=0;i<10;i++)
arr[i]=i;
}
int main(int argc, char** argv)
{
int arr[10],i;
func(arr);
for(i=0;i<10;i++)
printf("%d\n",arr[i]);
return 0;
}
```
output:
```
0
1... |
HI i am unable to figure out how function pointer is typedef in below code .please can anyone explain
```
#include<stdio.h>
typedef int(*fp)(int,int) ; this is typedef with function pointer i m unable to figure out?
int sum (int,int);
int main()
{
fp p,q; // p, q become function pointer too how?
p=sum;
... |
Well, there's not much to understand. You define a new type int(*fp)(int, int). This is not a function pointer, but a function pointer type. Compare fp to float, int, or any other primitive types. Then you declare p and q of the above mentioned type and assign to p the function sum which is of the same type (implicit)... |
How can I make my input string S1 of the fgets (or similar statement) to be equal to my declared static string S2?
```
#include <stdio.h>
#include <string.h>
main() {
char s1[80];
char s2[] = "This is a test.";
int l1, l2;
system("clear");
printf("%s\n\n", s2);
printf("Please type exactly th... |
You're doing a pointer comparison, not a string comparison. To compare the content of the strings, usestrcmp(docs):
```
if (strcmp(s1, s2) == 0)
...
```
|
I was wondering if it's possible to use a regex.replace in flex BEFORE the parsing starts.
Is there a predefined variable representing the whole input string?
|
No, there is no variable representing the whole input string.
Think about it, this would not be possible for a generic scanner as Flex which must be able to handle very large file sizes, and can be used for a virtually infinite input in an interactive command parser.
|
```
system("C:\\server.exe ine >> request.xml");
```
This program takes ine as parameter and writes output to file request.xml. The program successfully writes output to file, but it does not close the file. I tried
```
exit(0)
```
but it not execute after system(...)
It looks like the program is hanged, and i hav... |
Don't usesystem. It seems like the process you call (C:\server.exe) is not exiting after you launch it.systemwill just hang until the process exits.
Instead, consider usingCreateProcessandTerminateProcessto control the lifecycle of your program more carefully. In that case, you will have to specify the output file ma... |
I am looking for a tool to help me minimize the memory allocations inside a C project I'm currently porting.
Mainly, the following information would be useful:
```
1. line of code where memory zone was accessed
2. memory location
3. access mode (read/write)
```
Any form of parsing would be just a bonus, as well as ... |
For 1 and 2 you could just
```
void *log_malloc(const char *file, int line, const char *function, size_t size) {
void *mem = malloc(size);
/* log or do something with file, line, function, size and mem */
return mem;
}
#define malloc(size) log_malloc(__FILE__, __LINE__, __func__, size);
```
And the s... |
void *is a generic pointer, but what aboutvoid **? Isvoid **also a generic pointer?
Can we typecastvoid **toint **,char **and so on.
I would be thankful to stack overflow family for any information on this.
|
No.void**is a pointer tovoid*, and nothing else. Onlyvoid*acts like a generic pointer.
Note that actually trying it will probably yield consistent results, but only the above is mandated by the Standard, anything else is Undefined Behaviour and may crash without mercy.
|
I'm compiling a C program for an embedded application using eclipse, but I need the code to know (at runtime) where exactly it ends in flash. What is the simplest way of doing this?
Thanks
|
You will need to go into the linker command file and create some labels that mark the start and end of the .text section in memory then in the code take the difference.
|
is there a way to check the value oflvaluevariables without using theprintcommand when debugging the code step by step, what I'm looking to do is the following:
If I have the following code:
```
> x = 5;
y = 6;
```
when I'm debugging the code and I usenext, I wantgdbto display the value ofx, that is the variable ... |
You can use the display command:
```
(gdb) help display
Print value of expression EXP each time the program stops.
```
For instance if you display both you will get:
```
(gdb) next
4 y=6;
2: y = 0
1: x = 5
(gdb)
5 return 0;
2: y = 6
1: x = 5
```
|
I'd like to fork and exec and program as a non root user while the parent retains root permissions.
pseudo code:
```
pid = fork();
if (pid == 0) {
if (RunAsUser(ConvertStringToUserId("John")) == false) {
stop();
}
if (RunAsUser(ConvertStringToUserId("admin")) == true) {
stop(... |
If you want to drop privileges in C code, use the functionsetuid.
|
The following small program compiles on gcc and runs fine:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct foo dne;
int main(int argc, char *argv[]) {
dne *dne_var = malloc(sizeof(void*));
printf("%p\n", dne_var);
return 0;
}
```
Why is the typedef valid?
|
The line
```
typedef struct foo dne;
```
implicitly declares an (incomplete at this point) structurestruct foo. A pointer to an incomplete type is a complete type, so e.g. it’s size is known and you can declare an object of that type. However,struct fooitself isn’t complete until you provide a full declaration of it... |
I was wondering if it's possible to use a regex.replace in flex BEFORE the parsing starts.
Is there a predefined variable representing the whole input string?
|
No, there is no variable representing the whole input string.
Think about it, this would not be possible for a generic scanner as Flex which must be able to handle very large file sizes, and can be used for a virtually infinite input in an interactive command parser.
|
```
system("C:\\server.exe ine >> request.xml");
```
This program takes ine as parameter and writes output to file request.xml. The program successfully writes output to file, but it does not close the file. I tried
```
exit(0)
```
but it not execute after system(...)
It looks like the program is hanged, and i hav... |
Don't usesystem. It seems like the process you call (C:\server.exe) is not exiting after you launch it.systemwill just hang until the process exits.
Instead, consider usingCreateProcessandTerminateProcessto control the lifecycle of your program more carefully. In that case, you will have to specify the output file ma... |
I am looking for a tool to help me minimize the memory allocations inside a C project I'm currently porting.
Mainly, the following information would be useful:
```
1. line of code where memory zone was accessed
2. memory location
3. access mode (read/write)
```
Any form of parsing would be just a bonus, as well as ... |
For 1 and 2 you could just
```
void *log_malloc(const char *file, int line, const char *function, size_t size) {
void *mem = malloc(size);
/* log or do something with file, line, function, size and mem */
return mem;
}
#define malloc(size) log_malloc(__FILE__, __LINE__, __func__, size);
```
And the s... |
void *is a generic pointer, but what aboutvoid **? Isvoid **also a generic pointer?
Can we typecastvoid **toint **,char **and so on.
I would be thankful to stack overflow family for any information on this.
|
No.void**is a pointer tovoid*, and nothing else. Onlyvoid*acts like a generic pointer.
Note that actually trying it will probably yield consistent results, but only the above is mandated by the Standard, anything else is Undefined Behaviour and may crash without mercy.
|
I have the following C code. I am trying to call this function from Python usingctypes:
```
int add ( int arr [])
{
printf("number %d \n",arr[0]);
arr[0]=1;
return arr[0];
}
```
I compiled this by using:
```
gcc -fpic -c test.c
gcc -shared -o test.so test.o
```
then put it in/usr/local/lib.
Python c... |
Instead, try:
```
dll = cdll.LoadLibrary('test.so')
res = dll.add(pointer(c_int(5)))
print res
```
|
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
I have to write a C code that finds the smallest value in an array using recursion. I've ... |
The minimum of a single item array is that single item (base case or the termination condition).The min of an array is the minimum of [the first item, the minimum from the rest (excluding the first item)]
|
I try to compile and execute a c-written program and I get the error message written in the topic.
I am logged in over SSH, go to the directory where my method is, and compile it with:
```
gcc -o exec -c main.c
```
Which generates the "exec" file. Then I put the rights:
```
chmod u+x exec
```
And when I try to ru... |
Gcc with flag-ccompiles to an object, and not to a runnable binary. If you want to binary, omit this flag.
Change to:
```
gcc -o exec main.c
```
|
While studying about video compression encoder I came across float rateRatio=1.0f. I want know where does it make difference I mean 1.0f and 1.0?
|
As other said, one literal is of typefloatand the other is of typedouble.
Here is an example where it makes a difference:
```
#include <stdio.h>
int main(void)
{
int a = 16777217 * 1.0f;
int b = 16777217 * 1.0;
printf("%d %d\n", a, b);
}
```
prints on my machine:
```
16777216 16777217
```
The express... |
I was trying to make a shell interpreter similar to DOS in C language (for fun obviously)
And when i type clear, as shown in the code below it should make it so it clears the screen. But it doesn't.
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
char command[128];
int loop = 0;
voi... |
```
if(command=='clear')
```
it's not valid string comparison. usestrcmpto compare string inC.
It should be
```
if (!strcmp(command, "clear"))
{
printf("Clearing screen");
clrscr();
}
```
|
This question already has answers here:Can a local variable's memory be accessed outside its scope?(21 answers)Closed9 years ago.
```
char *getString()
{
char str[] = "Will I be printed?";
return str;
}
int main()
{
printf("%s", getString());
getchar();
}
```
Shouldn't the output be "Will I be pr... |
```
char str[] = "Will I be printed?";
```
is a local declaration. It is limited with in the functiongetString(). when you leave the function,str[]will be collapsed.
so you are trying to print the data at it. Obviously you will Garbage value!
To avoid this -
```
char *str = "Will I be printed?";
```
Nowstrwill be... |
What are the possible behaviors of the program below?
I have tried to allocate and use memory on stack,
and print the memory block pointed by p, output are characters of '\0'.
I known technically it is not available when the function returns.
However, why not the program crash, or print some random garbage?
```
#... |
As per you already know that memory ofchar mem[10];on stack and it is not available when the function returns. So i only says that it will cause youUndefined Behavior.
|
why can Dangling pointer not store any value and why does it throw 0? As it points to same memory which is freed. why 0 if we try to store some value?
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p;
p=(int*)malloc(sizeof(int)*5);//allocating memory in heap
printf("%p\n",p);
f... |
Accessing the freed memory is undefined behavior. Anything can happen. You got zero this time, and you can get anything next time.
http://en.wikipedia.org/wiki/Undefined_behaviorfor reference
|
I have the following problem:
```
extern void func_name(const char *f);
#define EXPECT(f) func_name(#f)
#define foo bar
void main()
{
EXPECT(foo);
}
```
So, the
```
EXPECT(foo);
```
will be actually evaluated to
```
func_name("foo");
```
What I actually need is to convert 'foo' to 'bar', i.e. t... |
```
#define S(x) #x
#define EXPECT(f) func_name(S(f))
```
|
I have included following headers:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
```
I have also tried to use
```
#define _GNU_SOURCE
```
before#include <unistd.h>, but it also does not help.
I... |
So here's thesolution, thanks toChrono Kitsune:
Put
```
#define _GNU_SOURCE
```
before any includes.
You should also pay attention to Chrono Kitsune's othercomment.
|
I am writing a C code which reads from a file and generates an intermediate.cfile.
To do so I usefprintf()to print into that intermediate file.
How can I print"?
|
You can use escape symbol\"For example
```
puts( "\"This is a sentence in quotes\"" );
```
or
```
printf( "Here is a quote %c", '\"' );
```
or
```
printf( "Here is a quote %c", '"' );
```
|
How can I use a variable to specify the max number of charsscanf()should read in?
For example usingprintf()you can use the * like so
```
#define MAXVAL 5
printf("Print at maximum MAXVAL chars: %.*s\n", MAXVAL, "myStringHere");
```
This will only print 5 chars, how can I makescanfonly read in MAXVAL? MAXVAL must be ... |
You can use the C preprocessor to help you with that.
```
#define STR2(x) #x
#define STR(X) STR2(X)
scanf("%" STR(MAXVAL) "s", string);
```
The processor combines"%" STR(MAXVAL) "s"to"%5s"
|
I have the following C code. I am trying to call this function from Python usingctypes:
```
int add ( int arr [])
{
printf("number %d \n",arr[0]);
arr[0]=1;
return arr[0];
}
```
I compiled this by using:
```
gcc -fpic -c test.c
gcc -shared -o test.so test.o
```
then put it in/usr/local/lib.
Python c... |
Instead, try:
```
dll = cdll.LoadLibrary('test.so')
res = dll.add(pointer(c_int(5)))
print res
```
|
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
I have to write a C code that finds the smallest value in an array using recursion. I've ... |
The minimum of a single item array is that single item (base case or the termination condition).The min of an array is the minimum of [the first item, the minimum from the rest (excluding the first item)]
|
I try to compile and execute a c-written program and I get the error message written in the topic.
I am logged in over SSH, go to the directory where my method is, and compile it with:
```
gcc -o exec -c main.c
```
Which generates the "exec" file. Then I put the rights:
```
chmod u+x exec
```
And when I try to ru... |
Gcc with flag-ccompiles to an object, and not to a runnable binary. If you want to binary, omit this flag.
Change to:
```
gcc -o exec main.c
```
|
While studying about video compression encoder I came across float rateRatio=1.0f. I want know where does it make difference I mean 1.0f and 1.0?
|
As other said, one literal is of typefloatand the other is of typedouble.
Here is an example where it makes a difference:
```
#include <stdio.h>
int main(void)
{
int a = 16777217 * 1.0f;
int b = 16777217 * 1.0;
printf("%d %d\n", a, b);
}
```
prints on my machine:
```
16777216 16777217
```
The express... |
I was trying to make a shell interpreter similar to DOS in C language (for fun obviously)
And when i type clear, as shown in the code below it should make it so it clears the screen. But it doesn't.
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
char command[128];
int loop = 0;
voi... |
```
if(command=='clear')
```
it's not valid string comparison. usestrcmpto compare string inC.
It should be
```
if (!strcmp(command, "clear"))
{
printf("Clearing screen");
clrscr();
}
```
|
This question already has answers here:Can a local variable's memory be accessed outside its scope?(21 answers)Closed9 years ago.
```
char *getString()
{
char str[] = "Will I be printed?";
return str;
}
int main()
{
printf("%s", getString());
getchar();
}
```
Shouldn't the output be "Will I be pr... |
```
char str[] = "Will I be printed?";
```
is a local declaration. It is limited with in the functiongetString(). when you leave the function,str[]will be collapsed.
so you are trying to print the data at it. Obviously you will Garbage value!
To avoid this -
```
char *str = "Will I be printed?";
```
Nowstrwill be... |
What are the possible behaviors of the program below?
I have tried to allocate and use memory on stack,
and print the memory block pointed by p, output are characters of '\0'.
I known technically it is not available when the function returns.
However, why not the program crash, or print some random garbage?
```
#... |
As per you already know that memory ofchar mem[10];on stack and it is not available when the function returns. So i only says that it will cause youUndefined Behavior.
|
why can Dangling pointer not store any value and why does it throw 0? As it points to same memory which is freed. why 0 if we try to store some value?
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p;
p=(int*)malloc(sizeof(int)*5);//allocating memory in heap
printf("%p\n",p);
f... |
Accessing the freed memory is undefined behavior. Anything can happen. You got zero this time, and you can get anything next time.
http://en.wikipedia.org/wiki/Undefined_behaviorfor reference
|
I just wanted to ask that-is it compulsory to useint main()in C language or can we usevoid main()also ? And ,is this condition is compulsory in C++ only ?
|
It is best practice to useint main(void)orint main (int argc, char **argv)because C standard says it here:
C11: 5.1.2.2.1 Program startup:
1 The function called at program startup is namedmain. The implementation declares no
prototype for this function. It shall be defined with a return type ofintand with no
par... |
i have a simple program that compile in c at visual,
but not compile at CSR10 id and I don't know how to do it simple:
it say error: assignment discards qualifiers from pointer target type;
```
char *globalString;
int test(void);
void test()
{
globalString = "ABCD";
return;
}
```
|
global string (char *) will point to a constant (const char *) "ABCD". So, you discard the "const" qualifier. Since GlobalString isn't a constant, it will warn you about that.
|
In C, I have a statement like this:
```
unsigned char const Alpha[6][2] = (unsigned char)({
{ 0x90f }, { 0x92c, 0x940 }, { 0x938, 0x940 },
{ 0x921, 0x940 }, { 0x908 }, { 0x90f, 0x92b }
});
```
But it produces an error asbraced-group within expression allowed only inside a function.
Can anyone sugges... |
You don't need a compound literal and your values are too large for anunsigned char, change to:
```
unsigned short int const Alpha[][2] = {
{ 0x90f }, { 0x92c, 0x940 }, { 0x938, 0x940 },
{ 0x921, 0x940 }, { 0x908 }, { 0x90f, 0x92b }
};
```
|
In C and C++, when using a macro like so:
```
#if ( 1 == __MY_MACRO__ )
// Some code
#endif
```
The compiler will not catch ifMY_MACROis not defined and will consider it 0. This could cause a lot of hidden bugs when the design of the code is intended such that the macro must be defined (non-zero).
Is there away to ... |
Use#if defined(__MY_MACRO__)to test if the macro value is defined.
|
I am using STM32737 MCU and IAR ide.
I have built my own pcb for STM32737 to interface with analog circuit, and Bluetooth module.
I am programming using SMD inst-link v2
When I try to download my program into the mcu, it prompt me an error:
User error: Reset failed
I have tried on 3 pcb, 2 failed and 1 download s... |
Found the stupid problem: schematic design fault.
There is an unwanted component blocking the reset voltage. Remove the component and device is ready to go.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed9 years ago.Improve... |
You cannot provide a second conditional withelseitself, use:
```
else if (num2 > num1)
```
|
Unable to know why output is 6?
In the given C program I am getting output as 6 every time, so I can't say that it is printing Garbage value
```
#include<stdio.h>
void main()
{
int const* a=2;
printf("%d\n",++(a));
}
```
I am unable to determine why this C program gives me this answer.
|
When you increment a pointer, it actually increments by the size of the type that it is pointing to.
Here you initialise a pointer to the value2. You then increment the pointer which, by the above increments the pointer bysizeof(int)or4on your system. You then print out this value - 6.
|
I have a shared library that my application needs (a .so) and I am wondering what is the best way to distribute it?
It's not something that can be apt-get installed and I need it in the LD path's in order to run the application.
|
In the past I've needed to include a separate "launcher script" that the user would click on instead of clicking on the Linux executable directly. The launcher script would set up LD_LIBRARY_PATH to include the directory where the shared library was stored, and then launch the executable. Here's the script, for refe... |
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
How to create GUI using C language in Visual Studio 2012/2013? Which libraries I should u... |
You can use standard WinAPI in windows, it let you create simple graphical user interface for your program (but it can be painful)http://zetcode.com/gui/winapi/(and especially:http://zetcode.com/gui/winapi/dialogs/)
|
Why the code doesn't work unless I remove the comment?
```
#include <stdio.h>
int main(){
int num = 5;
switch(num){
case 5:
//printf("");
int another = 1;
printf("%d", num+another);
break;
}
}
```
gcc returns an error:
```
prog.c: In function ‘mai... |
The reason is outlined here:Why can't variables be declared in a switch statement?
As a workaround, you can do this:
```
#include <stdio.h>
int main(){
int num = 5;
switch(num){
case 5:;
//printf("");
int another = 1;
printf("%d", num+another);
break;
... |
```
#define MAX 10
struct setArray
{
int item[MAX];
int count;
};
typedef struct setArray *BitSet;
```
how should I initialize the elements in the structure?
|
For example
```
struct setArray s = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, MAX };
```
Or
```
struct setArray s;
for ( int i = 0; i < MAX; i++ ) s.item[i] = i;
s.count = MAX;
```
Or
```
BitSet p = malloc( sizeof( *p ) );
for ( int i = 0; i < MAX; i++ ) p->item[i] = i;
p->count = MAX;
```
|
I'm coming back to 'C' after few years. I searched the net for how to use Twitter API in C and I came across this question on stackoverflow.
Question:Accessing the Twitter Streaming API with C
I can't understand the "if" in this code:
```
if(curl) {
```
I can't understand it, what does it do? What is it's function... |
It checks to see if the pointercurlis not null (a null pointer is equivalent to the value0, which is false when considered as a Boolean).
|
If I have the following code, where does the sentence insprintfget stored?
Is it stored in the 100 bytesmallochas provided or is it stored somewhere else and thestorepointer now points to the new location?
```
char *store = malloc(100);
int num = 77;
sprintf(store, "the number was: %d", num);
```
|
sprintfdoes not allocate memory on its own - it just stores its the input on a previously allocated buffer. In your case, this is indeed the buffer you allocated with themalloccall.
|
This question already has answers here:Why is "a" != "a" in C?(11 answers)Closed9 years ago.
I have a code below that asks if the user wants to retry or not. If the user enters no, the program will terminate. My code doesn't work and the loop still runs even if the input is "no"
```
#include<stdio.h>
int main()
{
... |
You should usestrcmp()to compare strings.
```
do { ... } while (strcmp(x, "no") != 0);
```
|
I have recently started using vim and i see my syntax files are located in /usr/share/vim/vim74 (I'm on linux Mint) and my c.vim seems to make the basic things likeintanddoublekeywords however when I edit any c or c++ files none of the types are highlighted however some things likeconstare highlighted. I am not sure w... |
To check whether the syntax parsing works as expected, check (when editing a C / C++ file) with
```
:syntax list
```
that those keywords (likeint) are defined. You'll also get a preview of the highlight coloring there. Alternatively, the colors are shown via
```
:highlight
```
To change those, you have to switch t... |
I just saw a function with the following signature:
```
bool insert( Node** root, int (*M)[COL], int row, int col )
```
What does COL do in this case?
|
That's the array size. COL would have been #defined somewhere in code... Suppose COL is defined as 5, you are expected to provide a pointer to an array of 5 integers. Any other dimension would cause a compiler error.
For example.
```
#define COL 5
...
..
..
bool insert( Node** root, int (*M)[COL], int row, int col ... |
How dofseek(myFILEptr, 0, SEEK_END)andmyifstream.seekg(0, std::ios::end)work?
Do they have to inspect every character and is their time complexity linear with the size of the file? Is it more intelligent than that? What information does a typical filesystem provide to work with?
Which parts of this are addressed by ... |
In practice, language implementations rely on the OS to deal with this (which in turn relies on the filesystem). For example, POSIX provides thelseeksyscall.
Thus they can't make any guarantees about complexity; they're dependent on the OS/hardware implementation.
|
I am trying to write a c code to leave tcpdump running while my program is active and then in real-time getting the tcpdump output into my code for further processing. I am capturing a very specific traffic (I have been able to acheive that in cmd) and I want to get the information of each captured packets in real-tim... |
If you want to analyze captured packets in real-time you should not run and parse tcpdump output, but use the underlying API/library directly: Which is libpcap.
Seehttp://www.tcpdump.org/pcap.html
|
I'm trying to build static library using MinGW dlltool in order too link it in GCC. What I have is only a DLL file. I created a *.def file and now I'm trying to make *.a file. However I can't force MinGW dlltool to create antyhing, it only makes an empty file. Here's the console output:
```
C:\MinGW\bin>dlltool -v -d... |
I had the exact same problem. Adding C:\MinGW\bin (or wherever your as.exe is located) to system PATH solved it for me.
|
Why the code doesn't work unless I remove the comment?
```
#include <stdio.h>
int main(){
int num = 5;
switch(num){
case 5:
//printf("");
int another = 1;
printf("%d", num+another);
break;
}
}
```
gcc returns an error:
```
prog.c: In function ‘mai... |
The reason is outlined here:Why can't variables be declared in a switch statement?
As a workaround, you can do this:
```
#include <stdio.h>
int main(){
int num = 5;
switch(num){
case 5:;
//printf("");
int another = 1;
printf("%d", num+another);
break;
... |
```
#define MAX 10
struct setArray
{
int item[MAX];
int count;
};
typedef struct setArray *BitSet;
```
how should I initialize the elements in the structure?
|
For example
```
struct setArray s = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, MAX };
```
Or
```
struct setArray s;
for ( int i = 0; i < MAX; i++ ) s.item[i] = i;
s.count = MAX;
```
Or
```
BitSet p = malloc( sizeof( *p ) );
for ( int i = 0; i < MAX; i++ ) p->item[i] = i;
p->count = MAX;
```
|
I'm coming back to 'C' after few years. I searched the net for how to use Twitter API in C and I came across this question on stackoverflow.
Question:Accessing the Twitter Streaming API with C
I can't understand the "if" in this code:
```
if(curl) {
```
I can't understand it, what does it do? What is it's function... |
It checks to see if the pointercurlis not null (a null pointer is equivalent to the value0, which is false when considered as a Boolean).
|
If I have the following code, where does the sentence insprintfget stored?
Is it stored in the 100 bytesmallochas provided or is it stored somewhere else and thestorepointer now points to the new location?
```
char *store = malloc(100);
int num = 77;
sprintf(store, "the number was: %d", num);
```
|
sprintfdoes not allocate memory on its own - it just stores its the input on a previously allocated buffer. In your case, this is indeed the buffer you allocated with themalloccall.
|
This question already has answers here:Why is "a" != "a" in C?(11 answers)Closed9 years ago.
I have a code below that asks if the user wants to retry or not. If the user enters no, the program will terminate. My code doesn't work and the loop still runs even if the input is "no"
```
#include<stdio.h>
int main()
{
... |
You should usestrcmp()to compare strings.
```
do { ... } while (strcmp(x, "no") != 0);
```
|
I know this is probably either bad or impossible, but since this isn't a recursive macro I think it should be possible.
```
#define FOO 15
#define MAKE_BAR(x) BAR_##x
#define MY_FOO_BAR MAKE_BAR(FOO)
```
I'd like MY_FOO_BAR to evaluate to BAR_15. Is there a way to tell the preprocessor to evaluate FOO before passing... |
You need another level of macro calls:
```
#define FOO 15
#define MAKE_BAR_INNER(x) BAR_##x
#define MAKE_BAR(x) MAKE_BAR_INNER(x)
#define MY_FOO_BAR MAKE_BAR(FOO)
```
This is because of how parameters are handled during functional macro expansion. The##concatenation operator prevents parameter expansion, so you must... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.