question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I get a segmentation fault when trying to run the code below
```
#include <stdio.h>
int main(){
int* tes1;
int* tes2;
*tes1=55;
*tes2=88;
printf("int1 %p int2 %p \n",tes1,tes2);
return 0;
}
```
why is that?
|
You need to allocate the pointers, otherwise they point to garbage memory:
```
int* tes1; //random initial value
int* tes2; //random initial value
```
In order to make them point to assignable memory, use themallocfunction:
```
int* tes1 = malloc(sizeof(int)); //amount of memory to allocate (in bytes)
int* tes2 = m... |
I am trying to write a program using openmp in which the structure block is a while loop.
```
#pragma omp parallel num_threads(x)
while(condition){
}
```
I have to decide upon the way to code the condition on which any thread would stop. I need to know if it is proper to have a break statement in the while loop.
|
I think that is it better to use omp cancellation.
The code would look similar to this one.
```
#pragma omp parallel
{
while(true) {
#pragma omp cancellation point parallel
// Do the heavy work
if(condition==false) {
#pragma omp cancel parallel
}
}
}
```
|
Here is my code example:
```
int main(int argc, char* argv[])
{
char* fileName = "%appdata%\\log.log";
FILE *file;
file = fopen(fileName, "a+");
time_t startTime = time(0);
fputs("Started logging at: ", file);
fputs(ctime(&startTime), file);
fclose(file);
printf("%s", fileName);
re... |
thefopencall has no idea what%appdata%is, as it can't magically convert that into a path. You have to expand the path yourself using theExpandEnvironmentStringsfunction. e.g. (untested):
```
char dest[MAX_PATH];
ExpandEnvironmentStrings(fileName, dest, MAX_PATH);
file = fopen(dest, "a+");
```
|
I am doing a program for my class, and I need to set all the values of the array 'decade' into -1 before I begin. I tried this (And the version in a for loop) and it just puts me in an infinite loop! Can someone explain why this is happening, and how I can fix it?
Code:
```
int decade[9][9], i = 0, k = 0;
while (i... |
When you declare an array of size9it has the indexes from0to8. You go to9which will overwrite the memory. This isundefined behaviorand can cause any number of subtle but faulty behavior.
|
I have this code :
```
#include <stdio.h>
int main()
{
char vc[5]={1,1,1,1,0};
int vi[4]={0,0,0,0};
printf("Reading characters...\n");
for(int i = 0 ; i < 4 ; i++)
scanf("%c",&vc[i]);
printf("Reading numbers...\n");
for(int i = 0 ; i < 4 ; i++)
scanf("%d",&vi[i]);
for(in... |
It's because%cdoesn't ignore whitespace and you're probably hitting return. Try:
```
scanf(" %c",&vc[i]);
^
```
The space makesscanfignore any whitespace.
|
I wrote a signal handler that prints a line from buffer, it first removes the previous prompt, print a line and prints the prompt again at the end of the screen. here is my handler.
```
void print(int param)
{
int c;
signal(SIGALRM, print);
printf("\b\b\b\b\b\b\b\b\b\b\033[0K");
print_line();
printf("\033[7... |
Standard output is usually line buffered. End with a\ncharacter, or flush explicitly like this:
```
fflush(stdout);
```
|
I really don't know what's the mistake. It seems to be right, doesn't it?
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char op;
printf("Type in operator (+,-,/,*):");
scanf("%i",&op);
if(op == '+')
{
printf("You entered a plus");
}
system("pause");
r... |
Theifcondition is fine. The problem is thescanf()format, which should be
```
scanf("%c",&op);
```
(%ireads an integer whereas%creads achar.)
|
How can I achieve the same result in C with OpenSSL as the getEncoded() Method produces?
It is required for a Diffie-Hellman Key Agreement and I have to send my public key to a java server (But I think the getEncoded() Method not only encodes the Public Key but also the parameters which should be also required for my... |
If encoded DH object means DER encoded, then i2d_DHParams can help you. It is givenhere.
|
```
#include<stdio.h>
int main()
{
FILE* f;
f=fopen("book.txt","w");
char* sentence="0123456789";
fprintf(f,"%s\n",sentence);
fseek(f,0,SEEK_END);
int a=ftell(f);
printf("%d\n",a);
fclose(f);
return 0;
}
```
I have the code above which prints out 12 when I run it. why is it not 11... |
On Windows systems, the newline is actuallytwocharacters: Carriage-return and the newline characters ("\r\n").
So you have your ten characters from the string you write out, plus the two for the newline.
|
What is the difference between the devices "default" vs "hw:0,0" ? Are they the same ?
(Background: I faced some trouble to play audio when I configured hw:0,0 , but "default" worked. Could not find what caused this)
Thanks
|
Thedefaultdevice uses theplugplugin to automatically convert sample formats and rates, and typically alsa uses thedmixplugin to allow multiple applications to access the device at the same time.
|
I'm having problems with argv in an if statement in one of my C programs. I know I must be missing something simple and stupid (it's been a while since I've done anything in C). Problem is, it won't doOtherStuff() if I specify nothing else on the command line. Even if I do ./a.out -i it still runs doStuff(). Does anyo... |
If you want to compare strings in C you have to use methods like strcmp:http://www.cplusplus.com/reference/cstring/strcmp/
In C a string is actually an array of characters, so you are comparing the memory address of the 2 arrays (which will be different of course since they are different arrays).
|
This question already has answers here:A sign in C++ I've never seen before: |=(5 answers)Closed10 years ago.
I am trying to understand |= in c++, I have sample code
```
int x = 0 ;
x |= 3;
std::cout<<x <<std::endl;
x |= 6;
std::cout<<x <<std::endl;
```
output is :
```
3
7
```
how is this possible, is it re... |
It is a bitwise or and assignment. It is the same as x = x | 3.
In binary bitwise or is equivalent to "if it's a 1 in either number it will be a 1 in the result". So x |= 3 makes 3. Then x is 11 in binary and 6 is 110 in binary so 11 | 101 = 111 (binary) = 7 (decimal).
|
This code gives me a segmentation fault:
```
char *s1 = "String 1", *s2 = "String 2";
void swap(char **, char **);
int main(void) {
swap(&s1, &s2);
return 0;
}
void swap(char **p, char **q) {
char **tmp;
*tmp = *p;
*p = *q;
*q = *tmp;
}
```
But if I change the body of the last function to ... |
Yourtmppointer is uninitialized and you dereference it in the very next line. That's undefined behaviour, which includes the possibility of a segfault.
|
What is the difference between the devices "default" vs "hw:0,0" ? Are they the same ?
(Background: I faced some trouble to play audio when I configured hw:0,0 , but "default" worked. Could not find what caused this)
Thanks
|
Thedefaultdevice uses theplugplugin to automatically convert sample formats and rates, and typically alsa uses thedmixplugin to allow multiple applications to access the device at the same time.
|
I'm having problems with argv in an if statement in one of my C programs. I know I must be missing something simple and stupid (it's been a while since I've done anything in C). Problem is, it won't doOtherStuff() if I specify nothing else on the command line. Even if I do ./a.out -i it still runs doStuff(). Does anyo... |
If you want to compare strings in C you have to use methods like strcmp:http://www.cplusplus.com/reference/cstring/strcmp/
In C a string is actually an array of characters, so you are comparing the memory address of the 2 arrays (which will be different of course since they are different arrays).
|
This question already has answers here:A sign in C++ I've never seen before: |=(5 answers)Closed10 years ago.
I am trying to understand |= in c++, I have sample code
```
int x = 0 ;
x |= 3;
std::cout<<x <<std::endl;
x |= 6;
std::cout<<x <<std::endl;
```
output is :
```
3
7
```
how is this possible, is it re... |
It is a bitwise or and assignment. It is the same as x = x | 3.
In binary bitwise or is equivalent to "if it's a 1 in either number it will be a 1 in the result". So x |= 3 makes 3. Then x is 11 in binary and 6 is 110 in binary so 11 | 101 = 111 (binary) = 7 (decimal).
|
This code gives me a segmentation fault:
```
char *s1 = "String 1", *s2 = "String 2";
void swap(char **, char **);
int main(void) {
swap(&s1, &s2);
return 0;
}
void swap(char **p, char **q) {
char **tmp;
*tmp = *p;
*p = *q;
*q = *tmp;
}
```
But if I change the body of the last function to ... |
Yourtmppointer is uninitialized and you dereference it in the very next line. That's undefined behaviour, which includes the possibility of a segfault.
|
I am trying to learn about recursion. I dont understand why the following piece of code runs in an infinite loop?
```
void myFunc(int n)
{
if(n==0)
return;
else
{
printf("%d\n",n);
myFunc(n--); //if I put n=n-1 before this line then it is running fine and will exit from the f... |
--is a post-decrement operator as you are using it and only takes effect aftermyFuncis called with the value ofn, so you will be callingmyFuncwith the same value over and over again.
Using it as a pre-decrement operator would fix your particular use case:myFunc(--n)would have a similar effect to puttingn=n-1on the li... |
Does anyone know of a C/C++ hash table/map implementation thatdoes notdynamically allocate memory? I'm working on an embedded system that has no standard library & no heap (unless I want to write/port one).
|
The terms you're looking for are "Open addressing" or "closed hashing".
Seehttp://en.wikibooks.org/wiki/Data_Structures/Hash_Tables#Open_addressingandhttp://en.wikipedia.org/wiki/Open_addressing
Don't know a specific implementation, though. Sorry.
|
Given an array of integers, i have to find out the maximum difference between any two elements such that larger number is appearing after the smaller number in the array.I used a simple approach and took the difference with the minimum number encountered so far by keeping the track of 2 things
1.Maximum difference
2... |
As it stands, your algorithm is optimal, up to a constant factor.
Reading an array ofnintegers takesΩ(n). Your algorithm isO(n), so you're good.
|
This question already has answers here:Extracting C / C++ function prototypes(11 answers)Closed10 years ago.
Is there any kind of tool that only shows the function prototypes of a given source file?
I know Doxygen is doing such a thing, but what I find is a simple Linux command such as
```
$ filter-function-prototyp... |
Apparentlyctagscan do that!
```
ctags -x --c-kinds=f main.c
```
There's some extra stuff in output but it can be handled withsedorawk.
Orcut
```
ctags -x --c-kinds=f cards.c | cut -c 51-
```
|
I have the following C code implemented by referencing to a header file already generated with JNI:
```
#include <jni.h>
#include <stdio.h>
#include "HelloWorld.h"
JNIEXPORT void JNICALL
Java_HelloWorld_print(JNIEnv *env, jobject obj)
{
printf("Hello World!\n");
return;
}
```
When I try to compile it (to... |
you have to add the-sharedlinker option
First create the object file:
```
cc -c HelloWorld.c
```
Then create the so
```
cc -shared -o libHelloWorld.so HelloWorld.o
```
|
I am reading a text file and trying to display its contents on the console. Here is my code:
```
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <fstream>
int main()
{
FILE* fp=NULL;
char buff[100];
fp=fopen("myfile.txt","r");
if(fp==NULL)
{
printf("Couldn't Open the F... |
You forgot to reset the file pointer to start after doing this.
```
fseek(fp, 0, SEEK_END);
```
Do this after finding size (file_size).
```
rewind (fp);
```
|
I am trying to make a condition for a for loop where i have to say(c<wordlength)but im not sure how to find the length of the word.
so lets say i have an arrary called...
```
char shopping[10][10]={"BAGELS","HAM","EGGS"};
```
what is the right syntax to find that shopping[0] has 6 letters?
|
The right syntax is
```
strlen(shopping[0])
```
This returns a value of typesize_tthat does not include the NUL terminator.
Seeman strlenfor details.
If you are usingstrlen(unchanging_string)as the terminal condition of a loop, it is prudent to call it once before the loop instead of calling it on every iteration.... |
My project contains c++ files and c files and I want to build my project with autotools.
So I create theMakefile.am. and I m wondering if it's possible to put bothcppfiles andcfiles together into the_SOURCEvariable
```
myprogram_SOURCES = \
file1.c \
file2.c \
file3.cpp
```
|
Yes, you can add C and C++ files to_SOURCES.
|
As the question said. In Xcode 4.6.
Want to print ints, chars, arrays, custom structs etc etc.
Possible?
With Objective-C I could do something like:
int three = 3;
po [NSString stringWithFormat:@"%i", three];
Thanks.
|
postands for Print Object, which essentially calls thedescriptionmethod on the object.
Usepto print an integer. For example:
```
p three
```
|
This code:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr[3][3] = {
1,2,3,
4,5,6,
7,8,9
};
int *arry = (int*)malloc(3 * sizeof(int));
*arry = memcpy(arry, arr[1], 3 *sizeof(int));
int t;
for(t = 0 ; t < 3 ; t++)
{
... |
It is copying the first value correctly, but
```
*arry = memcpy(arry, arr[1], 3 *sizeof(int));
```
you are overwriting it with the return value ofmemcpy.
Just call
```
memcpy(arry, arr[1], 3 *sizeof(int));
```
or assign the return value to a different variable if you want to check it (pointless, sincememcpyreturn... |
This question already has answers here:Modifying a C string: access violation [duplicate](3 answers)Closed10 years ago.
I'm a little perplexed why the following blows up:
```
char* c = "Hello World!";
*c = 'h';
```
When I allocate the string on the heap it works. So I'm just curious what wrong with my initial versi... |
char* c = "Hello World!";is a pointer to a string literal which is typically stored in a read-only memory segment. Attempting to modify it is undefined behaviour. Pointers to string literals such as this should more properly be defined as
```
const char *c = "Hello World!";
```
but theconstis often omitted (in C, at... |
I have a file which has 5 million rows and 4 columns. As usual, I try to read the data in a 5million by 4 array.
```
long M = 5000000;
double *coordinates[M];
for (i = 0; i < M; i++){
coordinates[i] = (double *) calloc(3, sizeof(double));
}
```
But when I run this code, it has segment fault. After searching the ... |
Do you really need the extra layer of pointers?
```
size_t M = 4321098;
double (*coordinates)[4] = calloc(M, sizeof *coordinates);
```
and you're done.coordinates[234329][3]=3.1415926535;everything works.
|
```
strftime('%s', 'now', 'start of month') AND strftime('%s', 'now', 'start of month', '+1 month', '-1 day')
```
this gives me range between first and last day of current month. How can I get range of current week?
This
```
strftime('%s', 'now', 'weekday 0')
```
gives seems to give last day of current week(Sunday... |
Try this:
```
strftime('%s', 'now', 'weekday 0', '-1 week', '+1 day')
strftime('%s', 'now', 'weekday 0', '-1 day')
```
weekdaymodifier advances the date forward to the next date where the weekday number is N. Sunday is 0, ...
|
I have the following code:
```
typedef struct {
double x, y;
} point_t ;
typedef struct {
point_t a, b, c;
} triangle_t;
int read_point(point_t * const point) {
int status = scanf(" (&lf,&lf)", &point_t.x, &point_t.y);
return(status);
}
```
I'm trying to read an x and y coordinate that the user ent... |
Change it to:
```
int status = scanf(" (%lf,%lf)", &(point->x), &(point->y));
```
Remember to use the variable namepoint, not the type namepoint_t. It also important to note that you must use the operator->on pointer types (it is equivalent to dereferencing it and then using the member operator [p->x == (*p).x]).
|
I have some pseudocode that finds the first all-zero row in an nxm matrix:
```
int first_zero_row = -1; /* none */
int i, j;
for(i=0; i<n; i++) {
for (j=0; j<n; j++) {
if (A[i][j]) goto next;
}
first_zero_row = i;
break;
next: ;
}
```
While this should work, I don't think using a goto statemen... |
Just setfirst_zero_rowonly when the inner loop ran to completion,
```
int first_zero_row = -1; /* none */
int i, j;
for(i=0; i<n; i++) {
for (j=0; j<n; j++) {
if (A[i][j]) break;
}
if (j == n) {
first_zero_row = i;
break;
}
}
```
if you want to avoid thegoto.
|
```
client removeClient (client cList,int pos)
{
int i,data;
data=cList[0]; **
pos=pos-1;
for (i=0;i<pos;i++)
{
cList[i]=cList[i+1]; **
}
return data;
}/* end module*/
```
Having a bit of trouble with this section of my code.
**-> at these lines I'm getting the error that says... subscripted value is neither ar... |
You are passing a scalar value, passing a pointer will help
```
client removeClient (client* cList,int pos){ }
```
This way you can pass an array to your function.
Call the function using
```
client result = removeClient(clientQueue, index);
```
|
[linux 3.2] I am wondering if it is possible to find out the memory location of a file opened in a program.
Suppose I have the code below in a.cpp which compiles to a.out:
```
FILE *f = fopen("myfile", "r");
```
Will the content be mapped into the memory space of a.out? If so, how could I find it(the pages? the rang... |
The structure to which the FILE* points holds some information about the state of the file. The contents are not mapped into program's memory space.
If you want to map file contents into the memory space you have to use mmap() function. This will give you a pointer to a memory region in the process's logical memory s... |
```
Console* initConsole(Controller* ctrl){
if (ctrl == NULL)
return NULL;
Console* c = (Console*)malloc(sizeof(Console));
c->ctrl = ctrl;
return c;
}
```
expected '=', ',', ';', 'asm' or 'attribute' before '{' token
This error appears in one of my modules.For some functions the "{" wasn't on... |
I most often get this if I forget to put a semi-colon after a forward declaration (possibly in an included header)
|
I am trying to make a condition for a for loop where i have to say(c<wordlength)but im not sure how to find the length of the word.
so lets say i have an arrary called...
```
char shopping[10][10]={"BAGELS","HAM","EGGS"};
```
what is the right syntax to find that shopping[0] has 6 letters?
|
The right syntax is
```
strlen(shopping[0])
```
This returns a value of typesize_tthat does not include the NUL terminator.
Seeman strlenfor details.
If you are usingstrlen(unchanging_string)as the terminal condition of a loop, it is prudent to call it once before the loop instead of calling it on every iteration.... |
My project contains c++ files and c files and I want to build my project with autotools.
So I create theMakefile.am. and I m wondering if it's possible to put bothcppfiles andcfiles together into the_SOURCEvariable
```
myprogram_SOURCES = \
file1.c \
file2.c \
file3.cpp
```
|
Yes, you can add C and C++ files to_SOURCES.
|
I have an old program that I want to read the mesh data from, is there a way I can access all the faces/triangle strips that any program(not just the one doing the reading) is sending to OpenGL's buffer.
|
Check outglintercept
```
GLIntercept is a OpenGL function call interceptor for Windows that will intercept and log all OpenGL calls.
```
|
Why is dynamic allocation not required in this code?
```
int knapSack(int W, int wt[], int val[], int n)
{
int i, w;
int K[n+1][W+1];
// Build table K[][] in bottom up manner
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i==0 || w==0)
K[i][w] = 0;
... |
That is a C99 feature. It is dynamically allocating on the stack for you.
Here's an explanation of variable-length arrays work in GCC:http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
|
Given the following code:
```
int x=4;
int g=2;
int z=x/g;
```
as far as I know, the value '4' is stored in the memory in a place belong toxand '2' is stored ing's place in the memory.
Now, when the CPU gets thez=x/gcommand, first of all he gets the value ofxandgfrom the memory, then he calculates the result, and st... |
You could illuminate yourself by coding this and looking at the disassembly. Regardless - the 2 is stored in a register, as well as the 4. Then the operation is performed.
|
Why do I getformat '%s' expects argument of type 'char*'? How should I fix the problem?
Here are my codes:
```
char UserName[] = "iluvcake";
scanf("%s", &UserName);
printf("Please enter your password: \n");
char PassWord[] = "Chocolate";
scanf("%s", &PassWord);
//if...else statement to test if the input is the c... |
&UserName is a pointer to an array of char (i.e., a char**). You should use
```
scanf( "%s", UserName );
```
|
I have the following function for generating a symmetric matrix:
```
void genMatrix(int n, double A[n][n])
{
int i,j;
int count=0;
for (i=0; i<n; i++)
for (j=i+1; j<n; j++)
{
count++;
A[i][j]=count;
A[j][i]=count;
}
}
```
When i call the function with these parameters:
```
int n = 10000;
dou... |
You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.
If you allocate the array on the heap you should be fine, assuming your machine has enough memory.
|
For example, is
```
static int a[1+1];
```
valid standard C? For some or all versions of the standard?
I'm not interested in whether compilers can handle it, but whether it is part of standard C.
|
C11, §6.6:
A constant expression can be evaluated during translation rather than runtime, and accordingly may be used in any place that a constant may be.
So yes, simple constant folding is mandatory and this snippet is valid standard C.
|
I have a C code that I'm analizing and there is something like this:
```
variable = (unsigned long)rx;
```
Ifrxis an array of hex numbers and variable is ofunsigned long, what will variable hold? The first element inunsigned longformat?
|
Remember that arrays decays to pointers. So what will happen is that the cast will convert the pointer (i.e. memory address) to anunsigned longand assign that tovariable.
|
On Windows, you can get the mouse position from an application running in the Terminal (or command prompt, as it's called there) by usingGetCursorPos(), and even simulate mouse clicks and movements usingmouse_event()andSetCursorPos()respectively. These functions can be found inwindows.h.
I'm looking for the same func... |
Yes you can use thencurseslibrary. See thismanpage.
|
Given an (i,j) element in a matrix what is the symmetrical correspondent in the matrix. I am trying to create a function that generates a symmetrical matrix in c. Thanks a lot.
Also would it be wise to create a matrix "by hand" using the rand() functionality or read from file, if I am dealing with large matrixes?
|
Given an (i,j) element in a matrix what is the symmetrical correspondent in the matrix
In a symmetric matrixA,A(i, j) == A(j, i).
Also would it be wise to create a matrix "by hand" using the rand() functionality or read from file, if I am dealing with large matrixes?
This is impossible to answer without some contex... |
i want to call "function2();" only for single time when recurfunc() was called for the first time.
```
recurfunc()
{
function2(); //to be called first time only in a recursive function
static int i= 0;
i++;
if(i>20)
return;
else
recurfunc();
}
```
|
A trivial change to your code:
```
void recurfunc() // * Remember to specify return type *
{
static int i= 0;
if (i==0)
function2(); // called only the first time.
i++;
if(i>20)
return;
else
recurfunc();
}
```
|
The following line
```
FILE *fp=popen("ls -h --full-time | awk '{printf \" %-70s%-10s%-20s%-30s\n \", $9,$5,$6,$7}' ","r");
```
gives the error
awk: Line 1 : runaway string constant "%-70s%-10....
I also tried
```
FILE *fp=popen("ls -h --full-time | awk \'{printf \" %-70s%-10s%-20s%-30s\n \", $9,$5,$6,$7}\' ","r"... |
You meant forawkto interpret your\n, but in fact it's being interpreted by your C compiler as a literal newline. That's why awk sees a runaway string -- because by the time you've gotten there it's a literal newline.
You should use\\nin your original string.
|
How can I programmatically check whether my machine has internet access or not using C/C++, is it just a matter of pinging an IP? How does NIC do it ? I mean something like:
I am using Windows 7.
|
If you work on Windows, just try this
```
#include <iostream>
#include <windows.h>
#include <wininet.h>
using namespace std;
int main(){
if(InternetCheckConnection(L"http://www.google.com",FLAG_ICC_FORCE_CONNECTION,0))
{
cout << "connected to internet";
}
return 0;
}
```
|
In the code below, why doesintwork but notfloat? Results are below.
voidptr.c :
```
#include <stdio.h>
typedef void* (*Fn) ();
int Fun()
{
return 5;
}
float fFun()
{
return 5.0;
}
void callfun(Fn f)
{
printf ("%d \n", f());
}
void callffun(Fn f)
{
printf ("%f \n", f());
}
int main()
{
c... |
You're lying to the compiler. The results are unpredictable.
|
Simply i check and get data send to my microplaze by cheking payload of my pbuff at recieve callback function , and it works where i can see that microplaze echoes back my messages but when i tried to print them fro mmicroplaze to terminal(using printf() in c code) something strange happened here is the print out :
... |
That happens because Characters are not terminated
|
This question already has answers here:C if statement with && - Which function will execute first?(7 answers)Closed10 years ago.
I am looking at a piece of code which calls two functions func1(struct *ps) and func2(struct ps). func1() returns the results in struct pointed by ps which is then used to call func2(). Thi... |
The order here is defined asfunc1(&ps)executes beforefunc2(ps). The&&operator has a property known as short circuiting. If the left side executes to 0 then the right side will never execute. Hence you are guaranteed thatfunc1(&ps)executes beforefunc2(ps)
|
I need to allocate dynamically some portions of memory, each with some protection - either RW or RX.
I tried to allocate memory bymalloc, butmprotectalways returns-1 Invalid argument.
My sample code:
```
void *x = malloc(getpagesize());
mprotect(x, getpagesize(), PROT_READ); // returns -1, it;s sample, so only R, n... |
If you want to allocate a page of memory, the correct choice is probably to usemmap()
```
void *x = mmap(NULL, getpagesize(), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
```
Note that since you pass the permissions into the call, you really don't need to usemprotect()afterward. You can use it, howeve... |
There is a string with a line of text. Let's say:
```
char * line = "Foo|bar|Baz|23|25|27";
```
I would have to find the numbers.
I was thinking of something like this:
If the given char is a number, let's put it into a temporary char array. (buffer)If the next character is NOT a number, let's make the buffer a ne... |
I would approach as the following:
Considering '|' as the separator, tokenize the line of text, i.e. split the line into multiple fields.For each token:If the token is numeric:Convert the token to a number
Some library functions that might be useful arestrtok,isdigit,atoi.
|
Was hoping someone could help me decipher this C snippet:
```
typedef int (DEFCALL *getFieldVal)(int key, int fieldSelect, char *name)
```
DEFCALL is defined earlier in the code, but only as
```
#define DEFCALL
```
So, I thinkDEFCALLis just a blank, and I am effectively looking at
```
typedef int (*getFieldVal)(i... |
The macro leaves room for adding a calling convention to the function type.
|
I'm reading a book on algorithms and the author defines doubly linked list with this code:
```
void dlist_init(DList *list, void (*destroy)(void *data));
```
What is the use of function pointer to destroy function here?
Can't we just later call the destroy() function on any list?
Why pass pointer to it during initi... |
The function pointer is passed to the initialization function so that the list functions will know how to destroy list entries. The list functions are designed to operate on all kinds of entries, so they need to be "told" how to destroy the particular entries this list will have.
|
I am writing a c program for my microblaze on the fpga now i want to check if i recieved the message ok but strncmp and strcmp are not working the only way that is working is this way :
```
char*as=malloc(sizeof(int));
as=p->payload;
if (*(as)=='o') {//first letter o
if (*(as+1)=='k') {//second l... |
Fromhttp://www.cplusplus.com/reference/cstring/strncmp/:
```
int strncmp(const char * str1, const char * str2, size_t num);
```
Did you perhaps forget to supplynum, the maximum number of characters to compare?
The functionstrncmpuses it, butstrcmpdoes not! If comparing whole strings, the latter one is probably what... |
I was able to run code that uses the randomize function without including the time.h library. is it automatically included with some other libraries i might have already included in my code? Below is a list of the libraries I included:
```
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h... |
This is very very specific to the version and implementation of your library. The standard doesn't force any header to includetime.h1so you cannot rely on that.
In your case, it could be that one ofdos.h,io.h,conio.hfor example has includedtime.h(or any other of the headers there for all it's worth).
1At least not... |
I have compilation problem as follows. Header fileabc.his included byabc.c.
In the header file, i have this
```
extern char **foo;
```
in the source file, i have this
```
char *foo[] = { ".mp3", ".mp4" };
```
Yet i get a compilation error from GCC:
```
abc.c:23:7: error: conflicting types for ‘foo’
In file inclu... |
One is an array of pointers while the other is a pointer to a pointer. Very different objects. Try declaring it as an array:
```
extern char *foo[];
```
|
I want to convert a hex number from a file to an int.The string looks like this:\0\0\x05\xa0This should be 1440. If I try:int i = '\x05'I get5.
But if I do the same with\xa0I get-96.Any ideas how to convert the string correctly?
|
That looks like abig-endiannumber.
Assuming you have the four (not 12 as if the bytes you showed are a string; I'm assuming they're binary bytes) bytes in an array ofunsigned char data[4], you should be able to convert like so:
```
const unsigned int x = (data[0] << 24) | (data[1] << 16) |
(da... |
I am aware that putting any number of0's before the width of the placeholder implements zero-padding. For example,printf("%02d", 6);prints06.
But what does putting a single0before the precision of the placeholder do? For example, for bothprintf("%0.2lf", 0.123);andprintf("%.2lf", 0.123);, the output is0.12.
If it do... |
%3.2f //(print as a floating point at least 3 wide and a precision of 2)%0.2lf //(print as a floating point at least 0 wide and a precision of 2)%.2lf //(print as a floating point at least 0(default) wide and a precision of 2)
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
~0x10gives you a bitwise not of0x10i.e.0xEF
0x10as binary is00010000. A bitwise not of this gives you11101111-0xEFin hex
If you assigned0x10to a type that was larger than one byte, inverting its bits would set its least significant byte to0xEFand others to0xFF.
|
I would like to get shared libs for dynamic linking.
I have object files and static files, but no shared lib files.
Can I convert somehow them to create shared lib?
|
Seehttp://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html.
Basically, you create a shared library like this:
```
gcc -shared -Wl,-soname,libfoo.so.1 -o libfoo.so.1.0.1 file1.o file2.o file3.o ...
```
The generated file will be namedlibfoo.so.1.0.1. However, you have to make sure that the*.ofiles were cre... |
I have a command that execute well in the normal terminal on Linux:
```
xterm -e bash -c "some commands"
```
I want to execute the above command using c program execXX system calls. I try to use the following codes but it gives me a normal xterm window.
```
execl("/usr/bin/xterm", "/usr/bin/xterm -e bash -c \"some ... |
You need to call it like:
```
execl("/usr/bin/xterm", "/usr/bin/xterm", "-e", "bash", "-c", "some commands", (void*)NULL);
```
The convention is to let the first argument be the same as the path to the program. If you have spaces in the arguments, it will be the same effect as callingxterm 'something with spaces'ins... |
I am trying to use gcc's -Wpadded option to know if gcc can help me in finding out whether a structure is padded or not. This is the following code.
```
#include<stdio.h>
struct my {
char *name;
int age;
} my_details;
int main() {
struct my person1;
return 0;
}
```
I complied the code using the fol... |
Seems that pack struct default is - 4. (gcc -fpack-struct=4)If it so - than this structure is already aligned.Because
```
char* - 4 or 8 bytes
int - 4 bytes
```
If you run this, you will have warning:
```
azat:~$ gcc -Wpadded -fpack-struct=8 -o test /tmp/test.c
/tmp/test.c:6:1: warning: padding struct size to align... |
This question already has answers here:C if statement with && - Which function will execute first?(7 answers)Closed10 years ago.
I am looking at a piece of code which calls two functions func1(struct *ps) and func2(struct ps). func1() returns the results in struct pointed by ps which is then used to call func2(). Thi... |
The order here is defined asfunc1(&ps)executes beforefunc2(ps). The&&operator has a property known as short circuiting. If the left side executes to 0 then the right side will never execute. Hence you are guaranteed thatfunc1(&ps)executes beforefunc2(ps)
|
I need to allocate dynamically some portions of memory, each with some protection - either RW or RX.
I tried to allocate memory bymalloc, butmprotectalways returns-1 Invalid argument.
My sample code:
```
void *x = malloc(getpagesize());
mprotect(x, getpagesize(), PROT_READ); // returns -1, it;s sample, so only R, n... |
If you want to allocate a page of memory, the correct choice is probably to usemmap()
```
void *x = mmap(NULL, getpagesize(), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
```
Note that since you pass the permissions into the call, you really don't need to usemprotect()afterward. You can use it, howeve... |
There is a string with a line of text. Let's say:
```
char * line = "Foo|bar|Baz|23|25|27";
```
I would have to find the numbers.
I was thinking of something like this:
If the given char is a number, let's put it into a temporary char array. (buffer)If the next character is NOT a number, let's make the buffer a ne... |
I would approach as the following:
Considering '|' as the separator, tokenize the line of text, i.e. split the line into multiple fields.For each token:If the token is numeric:Convert the token to a number
Some library functions that might be useful arestrtok,isdigit,atoi.
|
Was hoping someone could help me decipher this C snippet:
```
typedef int (DEFCALL *getFieldVal)(int key, int fieldSelect, char *name)
```
DEFCALL is defined earlier in the code, but only as
```
#define DEFCALL
```
So, I thinkDEFCALLis just a blank, and I am effectively looking at
```
typedef int (*getFieldVal)(i... |
The macro leaves room for adding a calling convention to the function type.
|
I'm reading a book on algorithms and the author defines doubly linked list with this code:
```
void dlist_init(DList *list, void (*destroy)(void *data));
```
What is the use of function pointer to destroy function here?
Can't we just later call the destroy() function on any list?
Why pass pointer to it during initi... |
The function pointer is passed to the initialization function so that the list functions will know how to destroy list entries. The list functions are designed to operate on all kinds of entries, so they need to be "told" how to destroy the particular entries this list will have.
|
I am writing a c program for my microblaze on the fpga now i want to check if i recieved the message ok but strncmp and strcmp are not working the only way that is working is this way :
```
char*as=malloc(sizeof(int));
as=p->payload;
if (*(as)=='o') {//first letter o
if (*(as+1)=='k') {//second l... |
Fromhttp://www.cplusplus.com/reference/cstring/strncmp/:
```
int strncmp(const char * str1, const char * str2, size_t num);
```
Did you perhaps forget to supplynum, the maximum number of characters to compare?
The functionstrncmpuses it, butstrcmpdoes not! If comparing whole strings, the latter one is probably what... |
I was able to run code that uses the randomize function without including the time.h library. is it automatically included with some other libraries i might have already included in my code? Below is a list of the libraries I included:
```
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h... |
This is very very specific to the version and implementation of your library. The standard doesn't force any header to includetime.h1so you cannot rely on that.
In your case, it could be that one ofdos.h,io.h,conio.hfor example has includedtime.h(or any other of the headers there for all it's worth).
1At least not... |
I have compilation problem as follows. Header fileabc.his included byabc.c.
In the header file, i have this
```
extern char **foo;
```
in the source file, i have this
```
char *foo[] = { ".mp3", ".mp4" };
```
Yet i get a compilation error from GCC:
```
abc.c:23:7: error: conflicting types for ‘foo’
In file inclu... |
One is an array of pointers while the other is a pointer to a pointer. Very different objects. Try declaring it as an array:
```
extern char *foo[];
```
|
```
#include <stdio.h>
int main(void)
{
int* a;
*a=20;
printf("%i\n",*a);
return 0;
}
```
I have the code above. when the code in runtime, I always get the error message "filename.exe has stop working". Why?
|
You did not allocate any memory for the pointer to point at. You can do so like this:
```
int *a = malloc(sizeof(*a));
```
or like this:
```
int value;
int *a = &value;
```
If you allocate withmallocthen you'll want to callfreeon the pointer when you are finished using it.
Accessing an uninitialized pointer leads... |
I have a javascript application which will be running on an embedded platform. It has to call some c APIs which are already implemented in the platform. This is a proprietary application and is meant to run only on selected devices.I am running this application on webkit. There is no JVM available.I am thinking of som... |
Your 2nd suggestion is pretty close to what you need to do. When you compile the browser (you don't need to compile webkit yourself) you can register functions and objects.
If you are using Qt, you should probably starthere.
If you are using GTK, the registration is different,hereis a nice example.
|
This is my code snippet in C:
```
char *str = NULL;
int len = -1;
// Get length
len = snprintf(NULL, 0, "[%d]", 2);
// Allocate str
str = (char *)malloc(len + 1);
// Assign str
snprintf(str, len, "[%d]", 2);
assert(len == 3);
// Display str
puts(str);
`... |
The length of the buffer islen+1, but you only passlentosnprintf, try this:
```
snprintf(str, len + 1, "[%d]", 2);
```
fromcplusplus.com:
If the resulting string would be longer than n-1 characters, the
remaining characters are discarded and not stored, but counted for the
value returned by the function.A termi... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
I allocated an array usingmallocand... |
When you domyArray++you lose the original pointer to the allocated memory.
Instead you should probably do:
```
*(myArray + i) = i;
```
Or even just use normal array indexing:
```
myArray[i] = i;
```
|
This is my program in C:
```
#include <stdio.h>
char const* voice(void){
return "hey!";
}
int main(){
const char* (*pointer)(void);
pointer = &voice;
printf ("%s\n", *pointer); // check down *
return 0;
}
```
*with this i'm trying to print what is returning from pointer but it seems like not working.
What am ... |
You need to call the function pointers, ie use parenthesis:
```
#include <stdio.h>
char const* voice(void){
return "hey!";
}
int main(){
const char* (*pointer)(void);
pointer = &voice;
printf ("%s\n", pointer());
// ^^^^^^^^^
return 0;
}
```
*isn't needed for function pointers. (neither is&)
|
My question is about file allocation methods on NTFS Fs.
I have two main questions -
When i create a file on NTFS, is it stored contiguously on the physical hard disk?if not - is there a way to create a file such that when i write to it the data is stored contiguously (on the hard disk) in it? Something like extent... |
According tothis superuser answer, you cancallSetEndOfFileto provide the system with a file size hint, which will allow NTFS to allocate contiguous storage for the entire file.
|
I have a CSV file that is extremely large, roughly 50k+ lines. I use CHCSVParser to parse it all line by line which works fine.
I would like to display some type of progress to the user as the data is parsed and added into CoreData. If I know the number of lines I can just show numLinesParsed/totalLines. I was wonder... |
Why don't you get thesize of the filein bytes and either divide it by the chars per line (if each line has same amount of characters) or divide it by the number of processed characters to get percentage?
ups: Jorge Nunez said it already...
|
The code below is used for programming microcontrollers. I want to know what the code below is doing. I know that '|' is OR and '&' AND but what is the whole line doing?
```
lcd_port = (((dat >> 4) & 0x0F)|LCD_EN|LCD_RS);
```
|
It's hard to put into context since we don't know whatdatcontains, but we can see that:
The data is right-shifted by 4 bits, so11111111becomes00001111, for instance.That value is AND'ed with 0x0F. This is a common trick to remove unwanted bits, sinceb & 1 = 1andb & 0 = 0. Think of your number as a sequence of bits, h... |
I am trying to use the posix functionisatty()in my C code, to tell if the output is being redirected. However, to do this I need a file descriptor, and from my research it looks likefileno()is no longer included withstdio.h. Are there any alternative methods of getting a file descriptor?
|
It's still there, but you may have to explicitly turn on POSIX features. In particular, under Linux,filenois only available if POSIX or XOPEN features are enabled. From thefileno(3)manpage:
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):fileno(): _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POS... |
This question already has answers here:How do pointer-to-pointers work in C? (and when might you use them?)(14 answers)Closed10 years ago.
I am reading a c++ code and came across this line:
```
mem_cMemRow ** ppMemory = (mem_cMemRow **)malloc(//size of some structs);
```
It seems to me that ** reserves some amount ... |
```
mem_cMemRow ** ppMemory = (mem_cMemRow **)malloc(//size of some structs)
```
is trying to allocate memory forppMemry, which is a pointer to pointer type ofmem_cMemRowobjects. It (ppMemory) is a 2D dynamic array.
|
Like in google chrome, when you download something you can click "open in explorer" or something and it will open exlplorer with that file highlighted.
I am going to write a program (probably a c cmd program) that searches for a file in a giver location, then I want to be able to click and open the file right from the... |
To open a folderand select one or more items within the folder, theSHOpenFolderAndSelectItemsfunction is what you're looking for.
|
I want to know if there is some open source projects (I prefer C projects) that use the cppUnit for the unit tests.
|
Xnor midi,tadaandnkbaseuse CppUnit. I believegnuradioalso uses CppUnit.
A quick search on github goes a long way.
|
I have a CSV file that is extremely large, roughly 50k+ lines. I use CHCSVParser to parse it all line by line which works fine.
I would like to display some type of progress to the user as the data is parsed and added into CoreData. If I know the number of lines I can just show numLinesParsed/totalLines. I was wonder... |
Why don't you get thesize of the filein bytes and either divide it by the chars per line (if each line has same amount of characters) or divide it by the number of processed characters to get percentage?
ups: Jorge Nunez said it already...
|
The code below is used for programming microcontrollers. I want to know what the code below is doing. I know that '|' is OR and '&' AND but what is the whole line doing?
```
lcd_port = (((dat >> 4) & 0x0F)|LCD_EN|LCD_RS);
```
|
It's hard to put into context since we don't know whatdatcontains, but we can see that:
The data is right-shifted by 4 bits, so11111111becomes00001111, for instance.That value is AND'ed with 0x0F. This is a common trick to remove unwanted bits, sinceb & 1 = 1andb & 0 = 0. Think of your number as a sequence of bits, h... |
I am trying to use the posix functionisatty()in my C code, to tell if the output is being redirected. However, to do this I need a file descriptor, and from my research it looks likefileno()is no longer included withstdio.h. Are there any alternative methods of getting a file descriptor?
|
It's still there, but you may have to explicitly turn on POSIX features. In particular, under Linux,filenois only available if POSIX or XOPEN features are enabled. From thefileno(3)manpage:
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):fileno(): _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POS... |
This question already has answers here:How do pointer-to-pointers work in C? (and when might you use them?)(14 answers)Closed10 years ago.
I am reading a c++ code and came across this line:
```
mem_cMemRow ** ppMemory = (mem_cMemRow **)malloc(//size of some structs);
```
It seems to me that ** reserves some amount ... |
```
mem_cMemRow ** ppMemory = (mem_cMemRow **)malloc(//size of some structs)
```
is trying to allocate memory forppMemry, which is a pointer to pointer type ofmem_cMemRowobjects. It (ppMemory) is a 2D dynamic array.
|
Like in google chrome, when you download something you can click "open in explorer" or something and it will open exlplorer with that file highlighted.
I am going to write a program (probably a c cmd program) that searches for a file in a giver location, then I want to be able to click and open the file right from the... |
To open a folderand select one or more items within the folder, theSHOpenFolderAndSelectItemsfunction is what you're looking for.
|
I want to know if there is some open source projects (I prefer C projects) that use the cppUnit for the unit tests.
|
Xnor midi,tadaandnkbaseuse CppUnit. I believegnuradioalso uses CppUnit.
A quick search on github goes a long way.
|
I'm with this doubt: how to get the size of a char array in this case:
```
#include<stdio.h>
void f(char * x)
{
printf("Size %d\n", sizeof(x)/sizeof(char));
}
main()
{
char x[5] = {'a', 'e', 'i', 'o', 'u'};
f(&x[0]);
}
```
Contrary to my expectations, I'm receiving 8 rather than 5 or even 6. What is wrong here?
T... |
sizeof(x)in your code will return the size of pointerchar *xand not the size of the char array thatxis pointing on
and the size of pointer in your 64-bits system is 8. and for 32-bits system the size of pointer is 4
|
I wish to upload my text data from client application to server database. Right now, i'm usingODBCto communicate withPostgreSQL. I useODBCbecause there is a need to connect to multiple type of databases.
My issue here is,PostgreSQLusesPQgetCopyDatato obtain the stdout data when usingCOPYOUT. So, is there any workarou... |
Basically you have two options. The first is to use the oldCOPYcommand (borrowed from Quel interestingly enough). The second is to use a CSV parsing library of your choice and generate INSERT statements.
The tradeoff is thatCOPYwill work MUCH faster, whineINSERTwill work on other databases too.
|
Title says it all.
I am trying to use some of the libraries from cygwin's gcc with visual studio's C++ compiler but the following code fromC:\cygwin\usr\include\sys\_types.hdoes not compile:
```
#ifndef __mbstate_t_defined
/* Conversion state information. */
typedef struct
{
int __count;
union
{
wint_t __... |
Is__valuea gcc extension, and if so, what does it do? Does it have a VC++ equivalent?
It's the other way around. It's akeyword in VC++but not ingcc.
Ingcc, it's just an identifier.
|
Can someone possibly explain (within the size of a stackoverflow answer) the code required in order to emulate a network interface? I just know that there is virtualization software out there like Qemu that does this specific type of hardware emulation, but have no idea how this would work. Lots of books will show you... |
VirtualBox is open source. As a VM, with networking support, it should be sufficient to demonstrate to you what to do, along with a working implementation.https://www.virtualbox.org/wiki/Downloads
|
The problem is that I cannot see0in an array.
I run my program and see 2D array. But instead of0(the first element) I see nothing.
Here is the code:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
int *Ptr;
scanf("%d%d", &M, &N); /* Size of array. */
Ptr = malloc(M*N*sizeof(int));
... |
The number after the dot is the precision. If the precision is 0 (or does not exist) then printf does not print out0. In your case you do not need the dot:
```
printf("%2d ", ...)
```
|
I have defined two macros
```
#define the_begin begin = 0
#define the_size n - begin
```
I'd like to check ifthe_sizemacro is not been used withoutthe_beginsince it depends onthe_begin.
Is it possible to check such dependence?
|
The dependency is already implicitly introduced by using thebeginvariable. If you give it a more unique name, you can mostly be sure that they won't be misused.
You can't be 100% sure, of course, because macros expand to regular text. Specially crafted text will always be able to imitate the effect of a macro, becaus... |
My program spawns a child thread with execvp to run another program in xterm:
```
char *argv[] = {"xterm",
"-e",
"./anotherProgram",
0
};
execvp("xterm", argv);
```
I know anotherProgram is running but in gdb, "info thread" doesn't show it. How can I attach the child thread and debug... |
Maybe it's sufficient for you to just find the process id of the child usingps aux | grep anotherProgramand then attach to it using a new gdb instance like this?gdb ./anotherProgram <pid>
If not, you could just patch the source code like this and recompile:
```
char *argv[] = {"xterm",
"-e",
... |
Is there a way to keep the offsets of all functions and variables as they were, everytime I'm compiling the program?
|
No. This is not a limitation of the compiler per se, but a "logical" limitation. Imagine you have a box that is full of stuff. Now you want to add stuff on box A but you don't want a new box. Well, you can't, it's a physical limitation.
Or talking more"computerish":
Functiona()occupies from address 0 to 0xA00 (size ... |
How to create multiple a text file in strcat
In my case, for example i input three name
./test paul tony john , so i use strcat to add ".dat"
but i cannot set three name is paul.dat tony.dat john.dat
the result is paul.dat.dat.dat dat.dat.dat .dat.dat
```
int main(int argc, char *argv[]){
int pid, myid ,cid;
in... |
When you call strcat(), you need to make sure there is enough space in the buffer allocated for the first argument for the string you are trying to add.
You can't add things directly to the elements of argv[] with strcat().
Allocate a new buffer that is large enough for both strings (including a nul character at the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.