question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
This code produces correct output without scanf line. The function returns different value on using scanf. Why so??
```
int main()
{
int choice;
scanf("%d",&choice);
bool a=admi_login();
if(a==true)
printf("\n hello");
else
printf("Bye");
}
bool admi_login()
{
printf("Enter the Admin Password\n");
char pw[100];
int i;
for(i=0;i<=100;i++)
{
pw[i]=getch();
if(pw[i]=='\r')
break;
printf("*");
}
char pw1[100]="admin\r";
if((strcmp(pw,pw1))==0)
return true;
else
return false;}
```
|
scanf will leave the input stream at the first whitespace it encounters. Your login function stops at the first whitespace, so it will never read the rest of the password.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this question
```
#include <stdio.h>
int main()
{
char str[100];
int l;
gets(str);
printf("%s %n",str,&l);
printf("%d",l-1);
return 0;
}
```
This program is for finding the length of a string.
|
%ssays output the stringstrand%nsays print nothing, rather store the number of characters written so far into the memory address ofl.
for reference on printf and all%specifierssee here
|
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.Closed6 years ago.Improve this question
I just started programming and have a question. I have a example input from command line: "number:10" which is "number:" followed by a number. I want to check if the character after "number:" is a number:
```
int main(int argc, char **argv)
{
if(isdigit(*argv[2]+7)){
printf("correct");
}
return 0;
}
```
It doesn't work. How can I read only the number in the input string?
|
*argv[2]is'n'.*(argv[2]+7)is correct
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this question
```
#include <stdio.h>
int main()
{
char str[100];
int l;
gets(str);
printf("%s %n",str,&l);
printf("%d",l-1);
return 0;
}
```
This program is for finding the length of a string.
|
%ssays output the stringstrand%nsays print nothing, rather store the number of characters written so far into the memory address ofl.
for reference on printf and all%specifierssee here
|
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.Closed6 years ago.Improve this question
I just started programming and have a question. I have a example input from command line: "number:10" which is "number:" followed by a number. I want to check if the character after "number:" is a number:
```
int main(int argc, char **argv)
{
if(isdigit(*argv[2]+7)){
printf("correct");
}
return 0;
}
```
It doesn't work. How can I read only the number in the input string?
|
*argv[2]is'n'.*(argv[2]+7)is correct
|
```
cat file.txt | grep hello
```
The way I see this is thatcat file.txtis executed and whatever is passed to the stdout is passed as input in a pipe togrep hello. Thengrep hellofinds all the occurrences that matchhelloin the given input.
Here is my confusion: doesgrep hellowrite back to the pipe so the parent process outputs whatever is in stdout? Or doesgrep helloput its returned content in stdout? How does it work?
I am asking this question because I am writing a shell in C.
|
cat's stdout is connected togrep's stdin.grep's stdout is connected to the default location, probably the terminal.grepdoesn't feed its output back tocat-- the pipe is unidirectional.
|
This program works as long as the "major" variable is only one word. For example, CIS is a valid input but Computer Information Systems is not. How do I fix this?
```
#include<stdio.h>
int main()
{
char major [51];
int classes;
printf("What is your major? ");
scanf("%50s", major);
printf("How many classes are you taking this semester? ");
scanf("%d", &classes);
printf("Your major is %s and you are taking %d classes this semester.\n", major, classes);
}
```
|
You can use%50[^\n]to match up to 50 characters until a newline is encountered, and store them inmajor[]. The newline will be left behind in the input stream, but the%dconversion specifier automatically skips over leading whitespace characters.
Note that if the user enters more than 50 characters, there will be extra characters in the input stream to discard before callingscanf()to get the number of classes.
|
I'm doing a program in C, the program reads a file, in that file, the program finds X "elements", sometimes they are 3, sometimes 4... For each element it has to create a struct that I'm going to change the values during the program, but I need them to be initialized.
The problem is that I don't know if it's possible to initialize X structs without knowing how many I'm going to need (it depends on the file), and if it's possible I don't know how to do it...
|
If n is the number of structs you need and
```
struct s{
int a;
int b;
};
```
is your struct, then
```
struct s* X = calloc(n, sizeof(struct s));
```
allocates enough memory for n structs.
You can change the k-th entry like this:
```
(X + k)->a = 5;
```
or
```
X[k].a = 5;
```
|
When I write a simple for loop like this
```
for (int i = 0; i < myList.size(); i++){}
```
in Java, C and C++, does it reevaluates myList.size() in each iteration or just for once at the beginning of the loop? If it reevaluates, does preevaluating size, i.e.,
```
int n = myList.size();
for (int i = 0; i < n; i++){}
```
gives us something significant in terms of performance?
|
For Java:
```
for (int i=0; i<myList.size(); i++){}
```
The condition is evaluated duringeachloop iteration; so there is a slight performance gain by moving that call tosize()in front of the loop.
But in Java you should prefer the for-each
```
for (Whatever thingy : list)
```
notation anyway (where possible).
You can read about in the Java language spec, chapter14.14.1.
|
This program works as long as the "major" variable is only one word. For example, CIS is a valid input but Computer Information Systems is not. How do I fix this?
```
#include<stdio.h>
int main()
{
char major [51];
int classes;
printf("What is your major? ");
scanf("%50s", major);
printf("How many classes are you taking this semester? ");
scanf("%d", &classes);
printf("Your major is %s and you are taking %d classes this semester.\n", major, classes);
}
```
|
You can use%50[^\n]to match up to 50 characters until a newline is encountered, and store them inmajor[]. The newline will be left behind in the input stream, but the%dconversion specifier automatically skips over leading whitespace characters.
Note that if the user enters more than 50 characters, there will be extra characters in the input stream to discard before callingscanf()to get the number of classes.
|
I'm doing a program in C, the program reads a file, in that file, the program finds X "elements", sometimes they are 3, sometimes 4... For each element it has to create a struct that I'm going to change the values during the program, but I need them to be initialized.
The problem is that I don't know if it's possible to initialize X structs without knowing how many I'm going to need (it depends on the file), and if it's possible I don't know how to do it...
|
If n is the number of structs you need and
```
struct s{
int a;
int b;
};
```
is your struct, then
```
struct s* X = calloc(n, sizeof(struct s));
```
allocates enough memory for n structs.
You can change the k-th entry like this:
```
(X + k)->a = 5;
```
or
```
X[k].a = 5;
```
|
When I write a simple for loop like this
```
for (int i = 0; i < myList.size(); i++){}
```
in Java, C and C++, does it reevaluates myList.size() in each iteration or just for once at the beginning of the loop? If it reevaluates, does preevaluating size, i.e.,
```
int n = myList.size();
for (int i = 0; i < n; i++){}
```
gives us something significant in terms of performance?
|
For Java:
```
for (int i=0; i<myList.size(); i++){}
```
The condition is evaluated duringeachloop iteration; so there is a slight performance gain by moving that call tosize()in front of the loop.
But in Java you should prefer the for-each
```
for (Whatever thingy : list)
```
notation anyway (where possible).
You can read about in the Java language spec, chapter14.14.1.
|
This question already has answers here:What does string + int perform in C?(3 answers)Closed6 years ago.
Is it possible to create array of char from different data types merging it into one char array.char array[32] = "matrix"+a+b+".txt";E.g:
```
int main(){
int a = 10;
int b = 10;
char array[32] = "matrix"+a+b+".txt";
return 0;
}
```
I have tried different ways. But it didn't helped. Thank you!
|
For C, usesnprintf():
```
int a = 10;
int b = 10;
char array[32];
snprintf(array, sizeof(array), "matrix%d%d.txt", a, b);
```
For C++, use strings instead of character arrays; you can concatenate strings easily since they overload the+operator:
```
int a = 10;
int b = 10;
std::string str{std::string{"matrix"} + std::to_string(a) + std::to_string(b) + ".txt"};
```
|
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.Closed6 years ago.Improve this question
Like what gdb do with watchpoint, I want to put a watchpoint programmatically in C. I heard that is possible with assembly. In the current time I know only for breakpoints like this instruction :
```
int i=0;
while(1){
i++;
if(i >= 10)
asm("int");/*break*/
}
```
After searching, it exist a possibility to display assembly's instruction using TUI mode and reuse it in my program but it doesn't work.
```
gdb -q ./prog -tui
gdb: TUI mode is not supported
```
Thanks for help.
|
On x86, to make a hardware watchpoint, you'll need to program one of the debug registers. You can starthere.
|
this is my code
```
#include <iostream>
#include <string>
#include <ctime>
int main()
{
for (int i=0;i<3;i++) {
if((pid()==fork())==0){
break;
}
}
if(pid==0) {
// son process
srand(time(NULL));
int r = rand()%4+1;
cout<<"pid:"<<getpid() <<"num": "<<r<<endl;
}
else{
//parent process
}
}
```
I have problem trandom number same to all process, how i can reset the rand()?
I have already tried to make different srand() to each process it not works.
|
puttime(NULL)+getpid()to diffrent seed for all rands;http://man7.org/linux/man-pages/man3/pthread_join.3.html
|
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.Closed6 years ago.Improve this question
Like what gdb do with watchpoint, I want to put a watchpoint programmatically in C. I heard that is possible with assembly. In the current time I know only for breakpoints like this instruction :
```
int i=0;
while(1){
i++;
if(i >= 10)
asm("int");/*break*/
}
```
After searching, it exist a possibility to display assembly's instruction using TUI mode and reuse it in my program but it doesn't work.
```
gdb -q ./prog -tui
gdb: TUI mode is not supported
```
Thanks for help.
|
On x86, to make a hardware watchpoint, you'll need to program one of the debug registers. You can starthere.
|
this is my code
```
#include <iostream>
#include <string>
#include <ctime>
int main()
{
for (int i=0;i<3;i++) {
if((pid()==fork())==0){
break;
}
}
if(pid==0) {
// son process
srand(time(NULL));
int r = rand()%4+1;
cout<<"pid:"<<getpid() <<"num": "<<r<<endl;
}
else{
//parent process
}
}
```
I have problem trandom number same to all process, how i can reset the rand()?
I have already tried to make different srand() to each process it not works.
|
puttime(NULL)+getpid()to diffrent seed for all rands;http://man7.org/linux/man-pages/man3/pthread_join.3.html
|
I want to scan a string that a user inputs, then write it into the file (file.txt), but this doesn't seem to work for some reason
```
int main()
{
FILE *stream;
stream = fopen("file.txt", "w");
char str[] = { '\0 ' };
scanf("%s", &str);
fprintf(stream, "%s.\n", str);
fclose(stream);
return(0);
}
```
|
try this, should work just fine.
It did for me so it should for you too.
```
#include <stdio.h>
#include <string.h>
int main()
{
FILE *stream;
stream = fopen("ceva.txt", "w");
if (stream == NULL) {
perror("Failed: ");
return 1;
}
char str[250];
scanf("%249s", str);
fprintf(stream, "%s.\n", str);
fclose(stream);
return 0;}
```
|
I have tried below code foo1.c
```
#include<stdio.h>
void f(void);
int x = 38;
int y = 39;
int main() {
f();
printf("x = %d\n", x);
printf("y = %d\n", y);
return 0;
}
```
foo2.c
```
double x;
void f() {
x = 42.0;
}
```
output:
```
$ gcc -o myprog foo1.c foo2.c
$ ./myprog
x = 0
y = 1078263808
```
i got weird output for this code can some one explain how it will come?
|
In foo1.c you have two variables x and y each having 4 bytes totally 8 bytes. In foo2.c you are having x variable as double.
While execution x in foo1 (4 bytes) is replaced by x in foo2 (8 bytes). Ultimately memory of x & y (totally 8 bytes) in foo1 is overwritten by x in foo2 (8 bytes).
1078263808 value is floating point representation of 42 in double.
NOTE: x & y memories in foo1 are successive.
|
I'm currently testing some inline assembly in C++ on an old compiler (GCC circa 2004) and I wanted to perform the square root function on a floating point number. After trying and searching for a successful method, I came across the following code
```
float r3(float n){
__asm__("fsqrt" : "+t" (n));
return n;
};
```
which worked. The issue is, even though I understand the assembly instructions used, I'm unable to find any particular documentation as to what the"+t"flag means on thenvariable. I'm under the genuine idea that it seems to be a manner by which to treat the variablenas both the input and output variable but I was unable to find any information on it. So, what exactly is the"t"flag and how does it work here?
|
+
Means that this operand is both read and written by the instruction.
(Fromhere)
t
Top of 80387 floating-point stack (%st(0)).
(Fromhere)
|
I have tried below code foo1.c
```
#include<stdio.h>
void f(void);
int x = 38;
int y = 39;
int main() {
f();
printf("x = %d\n", x);
printf("y = %d\n", y);
return 0;
}
```
foo2.c
```
double x;
void f() {
x = 42.0;
}
```
output:
```
$ gcc -o myprog foo1.c foo2.c
$ ./myprog
x = 0
y = 1078263808
```
i got weird output for this code can some one explain how it will come?
|
In foo1.c you have two variables x and y each having 4 bytes totally 8 bytes. In foo2.c you are having x variable as double.
While execution x in foo1 (4 bytes) is replaced by x in foo2 (8 bytes). Ultimately memory of x & y (totally 8 bytes) in foo1 is overwritten by x in foo2 (8 bytes).
1078263808 value is floating point representation of 42 in double.
NOTE: x & y memories in foo1 are successive.
|
I'm currently testing some inline assembly in C++ on an old compiler (GCC circa 2004) and I wanted to perform the square root function on a floating point number. After trying and searching for a successful method, I came across the following code
```
float r3(float n){
__asm__("fsqrt" : "+t" (n));
return n;
};
```
which worked. The issue is, even though I understand the assembly instructions used, I'm unable to find any particular documentation as to what the"+t"flag means on thenvariable. I'm under the genuine idea that it seems to be a manner by which to treat the variablenas both the input and output variable but I was unable to find any information on it. So, what exactly is the"t"flag and how does it work here?
|
+
Means that this operand is both read and written by the instruction.
(Fromhere)
t
Top of 80387 floating-point stack (%st(0)).
(Fromhere)
|
I am currently working through K&R to learn C. The authors made an important distinction that pointers and arrays do behave alike, but they are different because a pointer is a variable and can point to different things while an array does not have this ability.
I understand this, but the following code confuses me a little:
```
int len, nlines;
char *p, line[MAXLINES]; /* Confusing part */
```
I know when you pass an array to a function it decays into a pointer, but here you can declare a character pointer and a character array on the same line even though they are different? Maybe I am confusing myself but this is weird to me. Thanks!
|
That's just declaring multiple variables on the same line and is equivalent to this:
```
char *p; // Pointer
char line[MAXLINES]; // Fixed-sized character array
```
They're not related in any way other than their base type and where they were declared in the source code.
|
I am trying to get FRU inventory device ID list usingfreeipmi api, but I could only findipmi_fru_open_device_idmethod which takes the device's id as an argument.
Also, how do you get the device string name?Eg:
FRU Inventory Device: FRU_RAM (ID 00h)
I was able to get all the information about a device except it's string name(FRU_RAM).
|
FreeIPMI maintainer here. The primary "gotcha" if you're not familiar with the IPMI specification is that FRU device IDs and names are stored inside the SDR (sensor data repository). So you actually want to iterate through the SDR via the FreeIPMI "sdr" API for that information.
I'd recommend going through the source to FreeIPMI's ipmi-fru for guidance. I think most of what you'd want will be in there.
|
I'm currently doing a little university project in C, using allegro5. Part of it is just drawing a person on additional window that comes up and I'm trying to change the background colour of the window. I use
```
GFX_SetBackgroundColour(LIGHTBLUE)
```
as it's the instruction we've got from the classes and the one I keep finding on the allegro websites.
Except, the background stays black. I'm not sure how to proceed from that.
Also, I'm having some bad luck trying to type some text onto the window that comes up. But it might be just me not being sure how to useGFX_DrawText(int x, int y, const char text), what exactly to put as the last variable.
|
You can set the background color in allegro5 isal_clear_to_color.
For example, you could set a red background with:
```
al_clear_to_color(al_map_rgb(255, 0, 0));
```
Typically you would call this at the beginning of the draw loop every frame.
|
How can one increase the maximum size of a stack for C program that has a deep recursive call? Is there any config for the project where one can specify the stack or heap size for executables?
|
I solved the problem by adding following linker flag in project'sCMakeList.txt
```
MATH(EXPR stack_size "16 * 1024 * 1024") # 16 Mb
set(CMAKE_EXE_LINKER_FLAGS "-Wl,--stack,${stack_size}")
```
|
I cannot assign the input value tobj.
For example,when I input756,what I expect to get isUTC at the same time: 2356,however the computer gives meUTC at the same time: 1600.
```
#include <stdio.h>
int main()
{
int bj;
scanf("Input a BJT: %d", &bj);
if(bj>=0&&bj<=2359&&bj%100<60)
{
if(bj<800)
bj+=1600;
else
bj-=800;
printf("UTC at the same time: %d",bj);
}
else
;
return 0;
}
```
|
```
scanf("Input a BJT: %d", &bj);
```
You've mixed up yourprintfandscanffunctions somewhat.scanfspecifies what the input should be so you don't want the output stuff in there as well as it'll end up expecting that in your input.
Split them out like this.
```
printf("Input a BJT:\n");
scanf("%d", &bj);
```
|
I'm studying compilation theory and how to work with flex and i have several issues.
I created a lex file with the following data in it:
```
%%
"hello" printf("GOODBYE");
. ;
%%
```
This is the simplest one I could think of. If I understand correctly, it prints GOODBYE every time it encounters the hello token, and ignores everything else.
I used flex on this lex file to generate a C file, and I should now compile that C code to get the lexical analyzer for this grammar.
The problemis that the generated C code has no entry point. It does not compile. Is my .lex file incorrect? Am I misunderstanding something?
|
You need just declare ownmain()in this file, after second%%or link this .c with other .c file wheremain()declareted.
```
%%
"hello" printf("GOODBYE");
. ;
%%
int main()
{
yylex();
return 0;
}
```
|
How can one increase the maximum size of a stack for C program that has a deep recursive call? Is there any config for the project where one can specify the stack or heap size for executables?
|
I solved the problem by adding following linker flag in project'sCMakeList.txt
```
MATH(EXPR stack_size "16 * 1024 * 1024") # 16 Mb
set(CMAKE_EXE_LINKER_FLAGS "-Wl,--stack,${stack_size}")
```
|
I cannot assign the input value tobj.
For example,when I input756,what I expect to get isUTC at the same time: 2356,however the computer gives meUTC at the same time: 1600.
```
#include <stdio.h>
int main()
{
int bj;
scanf("Input a BJT: %d", &bj);
if(bj>=0&&bj<=2359&&bj%100<60)
{
if(bj<800)
bj+=1600;
else
bj-=800;
printf("UTC at the same time: %d",bj);
}
else
;
return 0;
}
```
|
```
scanf("Input a BJT: %d", &bj);
```
You've mixed up yourprintfandscanffunctions somewhat.scanfspecifies what the input should be so you don't want the output stuff in there as well as it'll end up expecting that in your input.
Split them out like this.
```
printf("Input a BJT:\n");
scanf("%d", &bj);
```
|
I'm studying compilation theory and how to work with flex and i have several issues.
I created a lex file with the following data in it:
```
%%
"hello" printf("GOODBYE");
. ;
%%
```
This is the simplest one I could think of. If I understand correctly, it prints GOODBYE every time it encounters the hello token, and ignores everything else.
I used flex on this lex file to generate a C file, and I should now compile that C code to get the lexical analyzer for this grammar.
The problemis that the generated C code has no entry point. It does not compile. Is my .lex file incorrect? Am I misunderstanding something?
|
You need just declare ownmain()in this file, after second%%or link this .c with other .c file wheremain()declareted.
```
%%
"hello" printf("GOODBYE");
. ;
%%
int main()
{
yylex();
return 0;
}
```
|
I've downloaded VS2017 Community Edition and I'm working through "Programming in C" by Stephen G. Kochan.
I'd like to store all the examples in one project (possibly 1 project per chapter), however I've come across the error about multiple "main" files in one project. Before telling me I can't have multiple main's in a project, could you suggest the best way to organise these small C programs in VS2017.
I love the fact that I don't have to use a terminal compiler and would like to use VS2017 to work my way through the book.
Any suggestions?
|
A typical case of "assignments" in a course. In that case you can create one module (c file) for each assignment and call the current assignment from your main. Now you have all assignments in a single project, so you can easily look them up. Assignments completed you can comment-out.
|
I have tried to multiply to numbers i.e.10000and10000 + 1through C program. But I am not getting the correct output.
```
printf("%lld",(100000)*(100001));
```
I have tried the above code on different compilers but I am getting same1410165408instead of10000100000.
|
Well, let's multiply
```
int64_t a = 100000;
int64_t b = 100001;
int64_t c = a * b;
```
And we'll get (binary)
```
1001010100000011010110101010100000 /* 10000100000 decimal */
```
but if you convert it toint32_t
```
int32_t d = (int32_t) c;
```
you'll get thelast 32 bitsonly (andthrow awaythe top10):
```
01010100000011010110101010100000 /* 1410165408 decimal */
```
A simplest way out, probably, is to declare both constants as64-bitvalues (LLsuffix stands forlong long):
```
printf("%lld",(100000LL)*(100001LL));
```
|
I have this file/folder structure:
```
root
out
test1
test1.exe
test2
test2.exe
test3
test3.exe
bin
run_test.exe
```
I would like to run all the test executables (test1, test2, etc.) which are found in subfolders ofoutfolder consecutively from therun_test.exeexecutable.
In myrun_test.execode, I can get the working directory of the executablerun_test.exeby usingGetModuleFileName()function from Windows API. My question is how can I execute (or trigger) test executables from run_test code? Should I navigate to each executable folder or can I do it using relative directory changes?
|
You could navigate back from your bin directory. Generally everything that can be used in command will work. Try usingdirent.h.There you can get the subfolders of your out folder and loop them, parsing commands for the run of each test using a simple sprintf.
|
When verbose user fault messages are enabled in linux kernel and segmentation fault occurs because of any illegal memory access, program crashes with message like
```
unhandled page fault (11) at 0x0839800, code 0x017
```
code which has value 0x017, printed with this message might have different value with other crashes. But what does the code 0x017 signifies here. Can anyone please explain or provide link for resources explaining about it?
|
This is not thesi_code, but the value of ARM's FSR (Fault Status Register) (source):
```
0x17 = 0b1 0111
```
According toARM manual:
[Bits 7:4]Specifies which of the 16 domains (D15-D0) was being accessed
when a data fault occurred.[Bits 3:0]Type of fault generated
So domain is 1, which isDOMAIN_USERin the kernel(all user memory only). Type of fault is pagetranslation fault, page.
|
When duplicating a file descriptor fd calling dup, and closing the original file descriptors.
Do all the duplicated file descriptors get closed also?
|
No the duplicates won't be closed. Otherwise the main use-case (duplicating intoSTDOUT_FILENOandSTDIN_FILENO) would be pretty useless.
|
This one is simple.
```
printf("%lu\n", (unsigned long)(320 * 200));
```
That line of code prints out "4294965760". That is definitely NOT equal to 360 * 200. What's wrong with it?
I am using Digital Mars C compiler in 16 bit medium memory model.
|
On a 16-bit system, ifsizeof(int) == 2, then320 * 200, which is equal to64000, is too big for a signedint(range ±32,767 — and usually -32,768 too, but in theory it varies by platform). So, you have arithmetic overflow. The cast doesn't affect the multiplication; it only affects what happens to the result of the multiplication.
You'd do better with:
```
printf("%lu\n", 320UL * 200UL);
```
That forces the constants tounsigned long.
|
A file with just a const declaration, like so:
```
const int genericRC = 0;
```
when compiled with the clang C++ front end warns about this unused variable. However, the clang C front end is silent about this:
```
$ cat x.sh
clang -c src/x.c -Wall -std=c11
clang++ -c src/t.cpp -Wall -std=c++11
$ ./x.sh
src/t.cpp:1:11: warning: unused variable 'genericRC' [-Wunused-const-variable]
const int genericRC = 0;
^
1 warning generated.
```
Is there any fundamental difference in C vs. C++ const for const static scoped variables of this sort, or is this just a warning that happens to be implemented in the clang C++ front end, but not in the C front end.
|
In C++ this has internal linkage so the compiler can know it is unused. In C it has external linkage so it might be used from another translation unit, therefore it would be premature to warn.
|
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.Closed6 years ago.Improve this question
Suppose you have the variableint numand the pointerint* cell. Does it make a difference for the values stored incellandnumto writecell = &numor*cell = num?
|
```
cell = &num
```
means that the contents/value of cell will be equal to the address of num.
```
*cell = num
```
means that the content at the address stored in cell, that is the value to which the pointer is pointing to, will be equal to the value of num.
|
I'm making a small program solving basic math operations (*,/,+,-) and I'm usinglong long int(64-bit number) so I can do math operations with big numbers.
But there is a problem. I can check the operands if they are not over or under limit (usingLONG_LONG_MAXandLONG_LONG_MIN).
But when I (for example) multiply two very big numbers (which cause overflow oflong long int) theLONG_LONG_MAXcheck doesn't work. Rather, the result is for -4.
Is there any chance in C/C++ check that? For example some try catch construction?
|
For
x = a*b;
```
if (a != 0 && x / a != b) {
// overflow handling
}
```
refer to this post for more details
multiplication of large numbers, how to catch overflow
|
Sometimes I need to write a loop in C/C++ where there is an initialization followed by a condition.
I like how this looks,
```
for (int i = 0, j = 0; i == 0 && j == 0;) {
// condition fails at some point
}
```
more than this.
```
int i = 0, j = 0;
while (i == 0 && j == 0) {
// condition fails at some point
}
```
Granted that this is personal code so noone can judge me. Will the compiler make it so that they are the same thing?
|
Use theforloop if youdon't needthe variablesiandjafter the loop.
Use thewhileloop if youneedthe variablesiandjafter the loop.
|
```
int a[ ] ={1,3,5,7,9,11,13,15,17,19};
int *pa = &a[4],*pb = &a[1];
```
What is the value ofpa-pb? Ans: 3, but how? Shouldn't it be 12 (like I printedpaandpbtoo, to double check, and got 12)?
|
Pointer arithmetic is very different from normal arithmetic. In pointer arithmetica-1, whereais pointer doesn't mean value ofasubtracted with 1. it means go back by one unit of memory.
In your example,pa-pbdoesn't mean value ofpa-pb. one int variable requires 4 bytes sopa-pbmeans go back by three int's to reachpbfrompa.
Forintone unit of memory is 4 bytes, float 8 bytes, char 1 byte.NOTE:These value changes from system to system, its usually these value.
|
In xv6mmu.hfile, there are these 2 lines of code
```
#define PGROUNDUP(sz) (((sz)+PGSIZE-1) & ~(PGSIZE-1))
#define PGROUNDDOWN(a) (((a)) & ~(PGSIZE-1))
```
What do they do?
|
PGROUNDUPandPGROUNDDOWNare macros to round the address sent to a multiple of thePGSIZE. These are generally used to obtained page aligned address.PGROUNDUPwill round the address to the higher multiple ofPGSIZEwhilePGROUNDDOWNwill round it to the lower multiple ofPGSIZE.
Let us take an example ifPGROUNDUPis called on a system withPGSIZE1KB with the address 620:
PGROUNDUP(620) ==> ((620 + (1024 -1)) & ~(1023)) ==> 1024The address 620 was rounded up to 1024.
Similarly forPGROUNDDOWNconsider:
PGROUNDDOWN(2400) ==> (2400 & ~(1023)) ==> 2048The address 2400 was rounded down to 2048.
|
Suppose I want to use malloc() to allocated some memory in the process
```
for(i = 0; i < SOME_NUM; ++i)
int *x = malloc(sizeof(int *));
```
What is the biggest number that I can set SOME_NUM to?
|
In xv6 the physical memory is limited and you can see the constant PHYSTOP which is224MBfor simplicity reasons. Some of that memory is accommodating kernel code and other stuff, so the rest could be used by a process if needs to consume rest of physical memory.Note: PHYSTOP could be changed, but then you will have to modify the mappages function to map all pages.
Note 2: pages are being allocated, so you could placePHYSTOP\pagesizein loop. Well I'm cheating here because again, kernel data structures and code are already occupying a portion of physical memory.
|
I'm sending a byte to my Raspi 3 and my Arduino via Bluetooth Serial.
e.g.0b00000011(mode),0b01000001(mode),0b10010000(direction)
The LSB indicates if the byte is a direction command or a instruction to switch mode, so I need to extract it in Arduino C and in Python.
Does anyone know how to do this?
Thanks in advance!
|
Use a bit operation:
C code
```
char b = 0x01;
if( b & 0x01 ) {
// LSB is set
}
else {
// LSB is not set
}
```
Python code
```
b = 0x01
if (b&0x01)==0x01 :
# LSB is set
else:
# LSB is not set
```
LSB =LeastSignificantBit (in your case)
|
I am writing a simple x64 program which calls a C program to print a string. I am using Mac OS X
X64:
```
.data
hello_world: .asciz "hello world!\n"
.globl _print_string
.globl _main
_main:
pushq %rbp
movq %rsp, %rbp
leaq hello_world(%rip), %rdi
callq _print_string
movq %rbp, %rsp
popq %rbp
```
C program:
```
#include <stdio.h>
void
print_string(char *str)
{
printf("%s\n", str);
}
```
But why am i getting'./output' terminated by signal SIGBUS (Misaligned address error). Can anyone please explain to me?
|
The first line of your.sfile switches to the data segment, and never switches back. This leaves themainfunction in the data segment, which is not executable.
Switch back to the text segment using.textbefore you start writing any code. (Or switch to the data segment and define your string constant aftermain.)
|
What is the difference in function betweentime()from the standard library andstime()from the POSIX extension?
Ifstime()setssystemtime, then what time doestime()set?
|
POSIX'sstime()always uses the midnight of January first 1970 as the "epoch begin" time and isonlyavailable to a superuser whereas standard library'stime()uses system-defined (usually either 1900 or 1970) epoch and has no access restrictions.
Also thetime()does notseta time, it only reads it back from the system, which is the reason it is not restricted to superuser or similar access.
|
I'm making a small program solving basic math operations (*,/,+,-) and I'm usinglong long int(64-bit number) so I can do math operations with big numbers.
But there is a problem. I can check the operands if they are not over or under limit (usingLONG_LONG_MAXandLONG_LONG_MIN).
But when I (for example) multiply two very big numbers (which cause overflow oflong long int) theLONG_LONG_MAXcheck doesn't work. Rather, the result is for -4.
Is there any chance in C/C++ check that? For example some try catch construction?
|
For
x = a*b;
```
if (a != 0 && x / a != b) {
// overflow handling
}
```
refer to this post for more details
multiplication of large numbers, how to catch overflow
|
Sometimes I need to write a loop in C/C++ where there is an initialization followed by a condition.
I like how this looks,
```
for (int i = 0, j = 0; i == 0 && j == 0;) {
// condition fails at some point
}
```
more than this.
```
int i = 0, j = 0;
while (i == 0 && j == 0) {
// condition fails at some point
}
```
Granted that this is personal code so noone can judge me. Will the compiler make it so that they are the same thing?
|
Use theforloop if youdon't needthe variablesiandjafter the loop.
Use thewhileloop if youneedthe variablesiandjafter the loop.
|
If I use goto instruction inside a recursive function (wanting to exit the function before it finishes naturally) is the stack freed automatically or not?
|
no, and so far as I know most compilers will not goto to exit the current function.
if you must escape directly from deep recursionthrowanexception(c++) or uselongjmp(c) these actions will restore the stack.
|
I'm trying to create and fill an array of array. This is the code I've written:
```
int b[4] = {100, 100, 200, 300};
int a[2][4];
int main(){
memcpy(a[0], b, sizeof(int));
printf("%i", a[0][2]);
```
I shoulde get200, but instead I get0...how can I solve it?
|
You're only copying one int from b. You need to copy all of b to a[0] like this
```
int b[4] = {100, 100, 200, 300};
int a[2][4];
int main(){
memcpy(a[0], b, sizeof(b));
printf("%i", a[0][2]);
}
```
|
Say I declared anarray[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}. Later I want it to bearray[8] = {2, 3, 4, 5, 6, 7, 8, 9}.
Dismiss the first 2 elements. So it would start onarray[2]. Reallocingarraytoarray[2].
I tried:
```
int *array=(int*)malloc(10*sizeof(int));
...//do stuffs
array=(int*)realloc(array[2],8*sizeof(int));
```
It didn't work. Neither using&array[2], *array[2], nor creating an auxiliary array, reallocing Array to AuxArr than free(AuxArr).
Can I get a light?
|
You can only realloc a pointer to a memory block that has already been alloc'ed. So you can realloc(array), but not array[2] since that is a pointer to a location in the middle of a memory block.
You may want to trymemmoveinstead.
Edit:In response to ThingyWotsit's comment, after memomving the data you want to the front of the array, then you can realloc to drop off the tail end.
|
I want to fetch and decode a instruction at address X. After that I want to increment the address by 4 and then execute the decoded instruction. The registers are 32 bit big endian. I am not asking for a solution, more a pointer or tips on how to do this in C, or if any of you know some good guides to follow.
|
You probably want assembly for this, not C. You could link assembly code into a C program, but you shouldn't write that in C.
|
I've started learning C yesterday, and the only other language I know is Python.
I'm having some trouble with arrays, because they are quite different from the Python lists.
I tried to print an array, not an element of it, but the array itself.
```
#include <stdio.h>
int array[3] = {1, 2, 3}
main(){
printf("%i, %i", array[0], array);
}
```
What I got is1(obviously), and4210692, which I can't understand from where it comes.
What I wanted to do first, is to make an array of arrays:
```
float a[1][4];
float b[4];
a[0] = b;
main(){
printf("%f", a[0]);
}
```
but it returns a strange number, and not something likethis is an arrayas Python does.
|
That is the memory address of the array (because ofarray-to-pointer decaying).
To correctly print pointers though, you should use%p.
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed6 years ago.Improve this question
Can someone explain what's happening in this line of code and how it's valid.
```
char output[][32] = {"Not present in trie", "Present in trie"};
```
|
It's declaring an array ofnarrays of typechar[32], wherenis deduced from the number of initializers in the initializer list (in this case 2).
When the variable is initialized, the contents of the provided string literals are copied into the array (string literals can be used to initializechararrays in C and C++).
|
This question already has answers here:returning a local variable from function in C [duplicate](4 answers)Returning an array using C(8 answers)Closed6 years ago.
so I started programming in C. Now I have a problem with pointers:
```
int * diff(){
int array[2] = {1,2};
return array;
}
int main(int argc, char const *argv[]) {
int *p;
p = diff();
printf("%d\n", *(p));
printf("%d\n", *(p));
return 0;
}
```
So after starting the program. My terminal is showing the following:
```
1
0
```
So why is the Value of *p changing ?
|
The behaviour of your program isundefined.
arrayhas automatic storage duration (informally, think of this as a "local variable"), and dereferencing the pointer to it that's returned back tomainis not allowed by the language.
(We call this adangling pointer).
|
Suppose I'm writing a program for an environment that has 32 bits for virtual spaces addresses (4294967296 addresses), what happens if create more than 4294967296 variables, effectively exceeding the number of possible addresses? Or all programs in an environment collectively use over 4294967296 addresses?
|
It depends precisely how you try to do it. It may crash, it may return an error, it may throw an exception.
|
If a pipeline is createdGstElement *pipeline = gst_pipeline_new (session_id);on my server whenever a user visitshttp://myurl.com/new?session_id=123&file_path=/vids/vid.mp4(mp4 videos are streamed to a RTMP server), how can I use the name of the pipeline"123"to set the pipeline state to not playing when the user visitshttp://myurl.com/to_not_playin?session_id=123? Each visit tohttp://myurl.com/newlaunches gstreamer in a new thread (because my webserver is asynchronous and I want multiple users to use the platform) then the different elements/pads are created and linked.
|
There is no way to get a pipeline by name generically in GStreamer, you should store thename -> pipelinemap yourself if you need it.
|
I have a string char * a = '343'. I want to convert it into integer value.
Example.
char *a = "44221"
I want to store that value into into int a;
|
This is is part of most C runtimes:
```
#include <stdlib>
char *a = "1234";
int i = atoi(a);
```
That's theatoifunction. Do read through the various methods available. C's library is pretty lean so it won't take long.
|
I'm writing some kind of protocol to transmit with the NRF24 module so, the procotol is declared like this:
```
unsigned char protocol[16];
```
that protocol have 16bits or 16bytes size?
|
16 bytes. 1 char is generally 1 byte on most systems.
|
I have this source file
```
//src.c
#include "include/headers/my_header.h"
```
And gcc fails with this errorinclude/headers/my_header.h: No such file or directory
```
gcc my_src/src.c -Iinclude/headers
```
However, it works fine if I rewrite the source file like so:
```
//src.c
#include "my_header.h"
```
Now, I'm actually compiling a project I've inherited so I'm not trying to rewrite all of the include statements. What gives?
|
The path after-Icatenated to whatever is in the#includestatement has to match a path in your file system. Try-I., that leads to./include/headers/my_header.h, and presumably will let GCC find your header.
|
This question already has answers here:undefined reference to "only some math.h" functions(4 answers)Closed6 years ago.
I just encountered a strange thing. While testing math.h I tried to use pow() and compile it. I did not have to link math.h .
But when I try the same with something like fmod() I have to link math.h while compiling the programm.
Why do I have to link the library in the second case but not in the first?
|
Your compiler may be replacing some usages ofpowwith a constant. For example, it could replacepow(2.0, 3.0)with8.0. This is a good optimisation and means you no longer need thepowinmath.h.
But your compiler probably can't replacefmod, or all usages of math functions, so it still needs to link to the math library.
|
I want to fetch and decode a instruction at address X. After that I want to increment the address by 4 and then execute the decoded instruction. The registers are 32 bit big endian. I am not asking for a solution, more a pointer or tips on how to do this in C, or if any of you know some good guides to follow.
|
You probably want assembly for this, not C. You could link assembly code into a C program, but you shouldn't write that in C.
|
I've started learning C yesterday, and the only other language I know is Python.
I'm having some trouble with arrays, because they are quite different from the Python lists.
I tried to print an array, not an element of it, but the array itself.
```
#include <stdio.h>
int array[3] = {1, 2, 3}
main(){
printf("%i, %i", array[0], array);
}
```
What I got is1(obviously), and4210692, which I can't understand from where it comes.
What I wanted to do first, is to make an array of arrays:
```
float a[1][4];
float b[4];
a[0] = b;
main(){
printf("%f", a[0]);
}
```
but it returns a strange number, and not something likethis is an arrayas Python does.
|
That is the memory address of the array (because ofarray-to-pointer decaying).
To correctly print pointers though, you should use%p.
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed6 years ago.Improve this question
Can someone explain what's happening in this line of code and how it's valid.
```
char output[][32] = {"Not present in trie", "Present in trie"};
```
|
It's declaring an array ofnarrays of typechar[32], wherenis deduced from the number of initializers in the initializer list (in this case 2).
When the variable is initialized, the contents of the provided string literals are copied into the array (string literals can be used to initializechararrays in C and C++).
|
This question already has answers here:returning a local variable from function in C [duplicate](4 answers)Returning an array using C(8 answers)Closed6 years ago.
so I started programming in C. Now I have a problem with pointers:
```
int * diff(){
int array[2] = {1,2};
return array;
}
int main(int argc, char const *argv[]) {
int *p;
p = diff();
printf("%d\n", *(p));
printf("%d\n", *(p));
return 0;
}
```
So after starting the program. My terminal is showing the following:
```
1
0
```
So why is the Value of *p changing ?
|
The behaviour of your program isundefined.
arrayhas automatic storage duration (informally, think of this as a "local variable"), and dereferencing the pointer to it that's returned back tomainis not allowed by the language.
(We call this adangling pointer).
|
I wrote the following code in order to write some random characters to a text file:
```
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
int input_f = open("./input.txt", O_CREAT | O_APPEND | O_RDWR ,0666);
int i;
for(i=0;i<50;i++)
{
int r = rand()%252;
printf("%d size of r: %d\n",i,sizeof(r));
write(input_f,r,sizeof(r));
printf("%d we just wrote %d which is %c\n",i,r,r);
}
close(input_f);
}
```
I looked for some solutions to do this
Maybe someone here knows how can I fix this?
|
```
write(input_f,r,sizeof(r));
```
should be
```
write(input_f, &r, sizeof(r));
```
The second parameter is the address of the buffer you want to send according to theman page.
Also you should check the return value of the function to be equal tosizeof r.
|
Which is faster in following two code snippets? and Why?
Declared loop index variable outside theforstatement:
```
size_t i = 0;
for (i = 0; i < 10; i++)
{
}
```
and
Declared loop index variable within theforstatement:
```
for (size_t i = 0; i < 10; i++)
{
}
```
|
Neither, they are equivalent and will yield the same machine code.
(The compiler will remove the redundant initialization ofitwice from the first example.)
Where a variable is declared has very little to do with performance and memory use.
for (size_t i = 0; i < 10; i++)is usually considered the most readable.
for (i = 0; i < 10; i++)has the advantage that you can use theivariable after the loop is done - which makes most sense when the number of iterations is variable.
|
I have this code that reads input from the user:
```
unsigned int readInput(char * buffer, unsigned int len){
size_t stringlen = 0;
char c;
while((c = getchar()) != '\n' && c != EOF){
if(stringlen < (len-1)){
buffer[stringlen] = c;
stringlen++;
}
}
buffer[stringlen+1] = '\x00';
return stringlen;
}
```
The size of char * buff is already set to len and has been memset to contain "0"s. Is this code vulnerable to any vulnerability attacks?
|
Depending on the platform,unsigned intmight be too small to hold the number13194139533312. You should always usesize_tfor buffer sizes in C, not doing so might be a vulnerability, yes.
Also, of coursegetchar()doesn't returnchar, so that's broken too.
I'd say "yes", that code is vulnerable.
|
I have an application and would like to find out if I leak file descriptors, when I usevalgrind -track-fds=yes ./app
I get:
```
==18807== FILE DESCRIPTORS: 4 open at exit.
==18807== Open AF_UNIX socket 20: <unknown>
```
Is this considered a file descriptor leak? Should one close socketPair ends when the application terminates or does Linux kernel take care of it?
|
Normally only anunboundedloss of resources is considered a leak.
If you open a file in a loop and never close it, you have a leak. Leaks are bad because your program will run out of whatever resource it's leaking.
If you open a file once, that's not so much a leak, especially if you need it to the very end of the program. It will be closed automatically by the kernel anyway.
It is a good practice to close even such files, if only just to keep your valgrind log clean.
|
I would like to produce pattern like this
n=5
```
xyoyx
xyoy
xyo
xy
X
```
n=6
```
xyoyxy
xyoyx
xyoy
xyo
xy
x
```
Thank you
|
```
#include <stdio.h>
int main(void) {
int i , j ,n;
printf("n=");
scanf("%d",&n);
printf("\n");
for(i = n-1; i >=0 ; i--)
{
for(j = 0; j <= i; j++)
{
if(j%4==0)
printf("x");
else if(j%4==2)
printf("o");
else if(j%2==1)
printf("y");
}
printf("\n");
}
return 0;
}
```
|
I am creating a 'Space invaders' style game where I need to limit my number of bullets to 100. I believe my best option is to Devise some way to indicate if a bullet is "in use" or "available".
When user presses "Launch missile" key, scan the array to find an available bullet.
If there are no available bullets, do nothing.
If there is an available bullet, launch the bullet found, and make it be "in use".
When the bullet flies off the screen, or when it hits a diamond, make it be "available".
How would I go about doing this?
|
I saw your Code, u have a bullet array all you need is a lastUsedIndex for the last used bullet. Initialize this with the last bullet index (Max bullet -1). If the bullet hits, do nothing. If it misses "hide" the bullet and decrement d index. If the index hits -1 Game over.
|
I want to store hard-coded a relation of HEX characters in uint8_t as an array, in php for example a would do something like
```
$relation = [
'uint8here-justasample',
'uint8here-justasample',
'uint8here-justasample',
'uint8here-justasample',
'uint8here-justasample'
];
```
How to do this in Arduino?
This is the uint8_t array that will be stored in the array of uint8
```
uint8_t event[8] = {'0','0','0','0','7','0','1','5'};
```
|
Maybe what you want is:
```
uint8_t const event[][8] =
{ {'0','0','0','0','7','0','1','5'}
, {'0','0','0','0','7','0','1','5'}
, {'0','0','0','0','7','0','1','5'}
};
```
|
I have a cordova project and I added windows platform but when I run the project I have this error:
```
MSBuild v4.0 is not supported, aborting.
Error: AppPackages doesn't exists
```
|
Try to set OS environment variable
VSINSTALLDIR = C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\
which points to your Visual Studio folder with MSBuild directory.
|
I use libcurl for auth in site. I make it with many functions, for example:
```
char *CheckLoginPass(char *login, char *pass)
{
//use curl_easy_setopt for check login/pass
return stdout;
}
char *AuthOnSite() //make auth on site
{
//use curl_easy_setopt for auth by login/pass
return htmlpage;
}
char *TestMyAuth()
{
//use curl_easy_setopt for test auth
return htmlpage;
}
void Test()
{
char *stdout = CheckLoginPass("login", "pass"); // is good
char *htmlpage = AuthOnSite(); // is good
htmlpage = TestMyAuth(); // session is lose and I am not logined on site
}
```
What me do to avoid dropping session?
|
You'll need to configure a "cookie jar" for libcurl to store its session cookie in, see:https://curl.haxx.se/libcurl/c/CURLOPT_COOKIEJAR.htmland refer to that when you make the TestMyAuth call, see:https://curl.haxx.se/libcurl/c/CURLOPT_COOKIEFILE.html
|
I am creating a 'Space invaders' style game where I need to limit my number of bullets to 100. I believe my best option is to Devise some way to indicate if a bullet is "in use" or "available".
When user presses "Launch missile" key, scan the array to find an available bullet.
If there are no available bullets, do nothing.
If there is an available bullet, launch the bullet found, and make it be "in use".
When the bullet flies off the screen, or when it hits a diamond, make it be "available".
How would I go about doing this?
|
I saw your Code, u have a bullet array all you need is a lastUsedIndex for the last used bullet. Initialize this with the last bullet index (Max bullet -1). If the bullet hits, do nothing. If it misses "hide" the bullet and decrement d index. If the index hits -1 Game over.
|
I want to store hard-coded a relation of HEX characters in uint8_t as an array, in php for example a would do something like
```
$relation = [
'uint8here-justasample',
'uint8here-justasample',
'uint8here-justasample',
'uint8here-justasample',
'uint8here-justasample'
];
```
How to do this in Arduino?
This is the uint8_t array that will be stored in the array of uint8
```
uint8_t event[8] = {'0','0','0','0','7','0','1','5'};
```
|
Maybe what you want is:
```
uint8_t const event[][8] =
{ {'0','0','0','0','7','0','1','5'}
, {'0','0','0','0','7','0','1','5'}
, {'0','0','0','0','7','0','1','5'}
};
```
|
I have a cordova project and I added windows platform but when I run the project I have this error:
```
MSBuild v4.0 is not supported, aborting.
Error: AppPackages doesn't exists
```
|
Try to set OS environment variable
VSINSTALLDIR = C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\
which points to your Visual Studio folder with MSBuild directory.
|
I use libcurl for auth in site. I make it with many functions, for example:
```
char *CheckLoginPass(char *login, char *pass)
{
//use curl_easy_setopt for check login/pass
return stdout;
}
char *AuthOnSite() //make auth on site
{
//use curl_easy_setopt for auth by login/pass
return htmlpage;
}
char *TestMyAuth()
{
//use curl_easy_setopt for test auth
return htmlpage;
}
void Test()
{
char *stdout = CheckLoginPass("login", "pass"); // is good
char *htmlpage = AuthOnSite(); // is good
htmlpage = TestMyAuth(); // session is lose and I am not logined on site
}
```
What me do to avoid dropping session?
|
You'll need to configure a "cookie jar" for libcurl to store its session cookie in, see:https://curl.haxx.se/libcurl/c/CURLOPT_COOKIEJAR.htmland refer to that when you make the TestMyAuth call, see:https://curl.haxx.se/libcurl/c/CURLOPT_COOKIEFILE.html
|
I have a cordova project and I added windows platform but when I run the project I have this error:
```
MSBuild v4.0 is not supported, aborting.
Error: AppPackages doesn't exists
```
|
Try to set OS environment variable
VSINSTALLDIR = C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\
which points to your Visual Studio folder with MSBuild directory.
|
I use libcurl for auth in site. I make it with many functions, for example:
```
char *CheckLoginPass(char *login, char *pass)
{
//use curl_easy_setopt for check login/pass
return stdout;
}
char *AuthOnSite() //make auth on site
{
//use curl_easy_setopt for auth by login/pass
return htmlpage;
}
char *TestMyAuth()
{
//use curl_easy_setopt for test auth
return htmlpage;
}
void Test()
{
char *stdout = CheckLoginPass("login", "pass"); // is good
char *htmlpage = AuthOnSite(); // is good
htmlpage = TestMyAuth(); // session is lose and I am not logined on site
}
```
What me do to avoid dropping session?
|
You'll need to configure a "cookie jar" for libcurl to store its session cookie in, see:https://curl.haxx.se/libcurl/c/CURLOPT_COOKIEJAR.htmland refer to that when you make the TestMyAuth call, see:https://curl.haxx.se/libcurl/c/CURLOPT_COOKIEFILE.html
|
I'm looking for a way to connect elements like a graph but with linked lists.
As far as I know this is how work a simple linked listenter image description here
But only one element is connected to another one. I know there is the double linked list but there is 2 connections.
How is it possible to connect element to others ?
I saw the concept of graph but I don't have a clue on how to do it.enter image description hereHere's an example of graph I would like to realise.
Thanks for the help.
|
You will need what is called anadjacency list.
It may consist in a linked list ofint*in which each element represents an array of adjacencies(i.e other vertices that are linked to this one) of a vertex in the graph. It should be something like this:
```
list *adj // Of course it depends on how you implemented the list
```
For this, i'm assuming that each vertex has its own index.
|
I am learning the use of function pointer from a programming book. There i've found the use of bsearch() and qsort(). The two functions has a parameter of function pointer cmpfunc.
In qsort() cmpfunc is needed to compare two elements.
I don't understand why there is a need for cmpfunc in bsearch() and how it works.
Please help me. Thanks in advance.
|
According tothisdocumentation, thebsearchcomparator function, similar to the one used theqsortfunction, is needed to evaluate the desired candidate to the elements in the array. This is neede to terminate the search if the desired element is contained or discarding half of the search space in every iteration; the role is the same as in theqsortfunction.
|
I have define below array in int data types with hexa decimal data.
```
volatile int Send_Data[3] = {0x0H11, 0xAAAC, 0x0DD0};
```
How can I initialize hex array with int data type in c language?
|
Hex array does not exist. Hex is only representation for numbers in computer language (used for programmers).
```
volatile int Send_Data[3] = {1, 2, 3};
```
|
The following program crashes. What am I doing wrong?
```
#include <stdio.h>
#include <process.h>
int main() {
puts("Hello!");
return spawnlp(0, "notepad.exe", "notepad.exe", "test.txt");
}
```
|
You're missing the terminating NULL to be passed as part of argument list.
Without that terminator, the end of the argument list will not be known, system will continue reading which causesundefined behaviordue to access of invalid memory locations.
|
Lets say I have the following code:
```
char *array[] = {"one", "two", "three"};
char *(*arrayPtr)[] = &array;
```
How do I iterate over array? I've tried doing this but doesn't work:
```
for(int i = 0; i < sizeof(array)/sizeof(array[0]); i++) {
printf("%s\n", (*arrayPtr + i));
}
```
|
The scheme you have is missing a derference.*arrayPtr + iis the address of the i-th element of the array. Meaning it's achar**. You need to at least dereference that:
```
printf("%s\n", *(*arrayPtr + i));
```
However, that isn't valid C you have there, since you omitted the array size when defining the pointer. I hope it's not the actual code you wrote.
Also, note that you can use the subscript operator asBlagovest Buyuklievpointed out, but be weary of operator precedence. It's(*arrayPtr)[i]and not*arrayPtr[i].
|
This question already has answers here:How to view C preprocessor output?(7 answers)Closed6 years ago.
I came across this option of -E while navigating and searching for where the file descriptors of stdio.h is stored in the machine? But I am not sure what exactly this command gcc -E do? Can it be used to view the file descriptor of the stdio.h fie stored in /usr/include/ directory?
|
It tells GCC to stop after the preprocessing stage. Details in the link.
https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#Overall-Options
|
I have the task of finding out if one of the many strings in my array contains an@character.
Example -
```
I am @HOME or @SCHOOL
```
If the string does contain the@i want to print out the string.
arris declared as follows
```
char* arr[10][100];
```
I thought of using this
```
if(strstr(arr[j], "@") != NULL);
{
printf("hey\n");
}
```
but it prints out every single string whether or not they have the @.
|
Remove semicolon after theifcondition. Like
```
if(strstr(outputArr[j], "@") != NULL)
```
Because
```
if(strstr(outputArr[j], "@") != NULL);
```
is equivalent to
```
if(strstr(outputArr[j], "@") != NULL)
{
}
```
C99-6.8.3 paragraph 3:
A null statement (consisting of just a semicolon) performs no operations.
|
I'm writing in C langage a program that contain these lines:
```
void main(int argc, char *argv[]) {
char* file=argv[1];
char* arguments[] = { "sh", argv[2], argv[3], argv[4], file, NULL };
execv("/bin/sh", arguments);
}
```
The file isprog.shwhich contain a simple sum of arguments:
```
expr $1 + $2 + $3
```
When I run the program by./main prog.sh 1 2 3I obtain an error which is
```
/bin/sh: 0: Can't open 1
```
While I expect the output 6 (sum of 1 2 3)
|
Look at your arguments:
```
char* arguments[] = { "sh", argv[2],argv[3],argv[4],file, NULL };
```
When you run./main prog.sh 1 2 3, you end up calling:
```
sh 1 2 3 prog.sh
```
You should instead make the script the first argument:
```
char* arguments[] = { "sh", file, argv[2],argv[3],argv[4], NULL };
```
thereby calling
```
sh prog.sh 1 2 3
```
|
I'm trying to debug a C program using Visual Studio Code in Ubuntu.
I set
"program": "${workspaceRoot}/sample"
in the launch.json where "sample" is the name of my program. Then I simply put a breakpoint in code and click the debug arrow. However, the debugger does not hit the breakpoint, a terminal simply flashes and closes.
When I hover over my breakpoint it says:
Module containing this breakpoint has not yet loaded or the breakpoint
adress could not be obtained.
Is there an additional setting that I must configure ?
|
The problem had nothing to do with VS code. I was simply missing the -g tag when compiling the program.
|
Which strings ought I to free in C on my own, usingfree()¹?
My state of knowledge:
char a[256];: nochar *a = "abcdefg";: nochar *a = malloc(15L);: yesa string returned bygetenv():nostrings returned by Windows functions²: ???
¹ orLocalFree()/GlobalFree()/VirtualFree()² in particular byGetCommandLineW()
|
This will always be mentioned in the documentation for any API you use that returns strings (or other data larger than a single simple value such as an integer).
Yes, this means you have to read the documentation thoroughly for all such API functions, in order to keep track and not leak memory.
|
glib a providesg_atomic_int_getfunction to atomically read a standard Cinttype. Isn't reading 32-bit integers from memory into registers not already guaranteed to be an atomic operation by the processor (e.g.mov <reg32>, <mem>)?
If yes, then what's the purpose of glib'sg_atomic_int_getfunction?
|
Some processors allow reading unaligned data, but that may take more than a single cycle. I.e. it's no longer atomic. On others it might not be an atomic operation at all to begin with.
|
I used something like this:
```
struct Node
{
char name[50];
Node *left,*right;
};
int main()
{
char cmd[10];
Node* p=NULL;
scanf("%s",&cmd);
if (p == NULL)
{
// do something
// THIS NEVER GETS EXECUTED
// WHYYYYY????
//THIS IS STRANGE
}
}
```
So basically, the pointerpchanges its value after I read into thecmdvariable. I tried to commented out thescanfcode, and then everything works. Very strange.
|
You have a buffer overflow.
The memory looks like this:
```
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
^ ^
cmd[10] p
```
If scanf reads more than 10 bytes, it will overflow top. Any non-zero value will fail the NULL check, even if it is not a valid pointer.
|
I used something like this:
```
struct Node
{
char name[50];
Node *left,*right;
};
int main()
{
char cmd[10];
Node* p=NULL;
scanf("%s",&cmd);
if (p == NULL)
{
// do something
// THIS NEVER GETS EXECUTED
// WHYYYYY????
//THIS IS STRANGE
}
}
```
So basically, the pointerpchanges its value after I read into thecmdvariable. I tried to commented out thescanfcode, and then everything works. Very strange.
|
You have a buffer overflow.
The memory looks like this:
```
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
^ ^
cmd[10] p
```
If scanf reads more than 10 bytes, it will overflow top. Any non-zero value will fail the NULL check, even if it is not a valid pointer.
|
I'm trying to create a dynamic array of 1000 character long strings using calloc:
```
int i;
char** strarr =(char**)calloc(argc,sizeof(char)*1000);
if(strarr == NULL)
return 0;
strarr[0][0] ='a';
printf("%c\n",strarr[0][0]);
```
Every time i try to run this code i get segmentation fault on the printf line, i don't get why does this happen (you can assume that argc is bigger than 0)
Thanks
P.s. im sorry that the code is in text format but im using a mobile so i dont have the code feature
|
Try this:
```
const int num_of_strings = 255; //argc ?
const int num_of_chars = 1000;
int i;
char** strarr =(char**)malloc(sizeof(char*)*num_of_strings);
if(strarr == NULL)
return 0;
for (i = 0; i < num_of_strings; i++) strarr[i] = (char*)malloc(sizeof(char)*num_of_chars);
```
|
I have an unsigned int where I am using each of the 32 bits to store a specific piece of information..
```
function( void * a);
unsigned int val = 0xFFFFFFFF;
function( (void *) (long) val );
```
Within the function, I want to modify the unsigned int.. I can't figure out how to uncast it without losing precision or any of the bits. Is tjere a correct way to do this.. can't seem to figure it out..
|
You should pass the address of val to the function by casting in to a void* like this:
```
function((void*)&val);
```
and design your function like:
```
void function(void* ptr) {
unsigned int *p = (unsigned int*)ptr;
(*p)++; //example of a change
}
```
|
I'm having issues with a c program that I want to debug.
I would like to know how to get a file that contains every lines of my executable, so I can later set breakpoints with gdb in it.
Thanks :)
|
For GCC specify-gwhen compiling.
More here:https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html
|
```
#include<stdio.h>
int main(void)
{
double c;
scanf("%f", &c);
printf("%f", c);
}
```
This is an exerpt from a program I'm attempting to write, but I get the same issue with something this simple. when I run this, and enter "1.0", it prints out "0.007812". I've looked at several previous questions that were similar to mine and could not find an appropriate answer.
|
You need to use"%lf"for double.
This is the warning from clang compiler.
warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat]
scanf("%f", &c);
Here is thescanf reference. It's format is%[*][width][length]specifier. The specifier for 'floating point number' isf. So we use%fto readfloat x. To readdouble x, we need to specify the length asl. Combined the format is%lf.
|
Making a simple program where the user inputs different classes, times and dates, and a timetable is generated (like a timetable with university classes). I've worked with Windows API for basic applications however I cannot find a way to display all the information in a timetable chart.
Something like this:
Is there a function that can be used in Windows API for displaying a timetable, or will I have to work with graphics to generate an image of a timetable (using OpenGL for instance)?
|
If you are programming in Win32 mode, to use ListView control is a better choice. You could get references from msdn:ListView ControlYou can also use the TextOut api to print information onto your Window form.
|
I have an unsigned int where I am using each of the 32 bits to store a specific piece of information..
```
function( void * a);
unsigned int val = 0xFFFFFFFF;
function( (void *) (long) val );
```
Within the function, I want to modify the unsigned int.. I can't figure out how to uncast it without losing precision or any of the bits. Is tjere a correct way to do this.. can't seem to figure it out..
|
You should pass the address of val to the function by casting in to a void* like this:
```
function((void*)&val);
```
and design your function like:
```
void function(void* ptr) {
unsigned int *p = (unsigned int*)ptr;
(*p)++; //example of a change
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.