question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
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.Closed7 years ago.Improve this question
A variable is located in memory at address 0x10000. How can I define a macro such that writing to that macro writes to that memory location?
|
The de facto standard way of declaring a writeable memory location in C is this:
```
#define REGISTER (*(volatile uint8_t*)0x10000)
```
whereuint8_tshould correspond to the size of the contents at that memory location.
And thenREGISTER = something;writes to that memory location, just as if REGISTER was a variable.
It is important to use thevolatilekeyword, to prevent optimization bugs and ensuring that reads of the location are always up to date.
|
So I'm doing communication between server and client in C. I'm having issues with searching for it on the web how to do the following.
```
./server -p 1234
./client -p 1234 -h asdffdsasdf
```
Can someone describe the basics of doing it inside the project or is it included in the Makefile??(Using Putty terminal).
Or show me a website where it is explained very well, because I dont know what to google for this.
Thanks a lot!
|
You need to use program startup arguments; seeStandard 5.1.2.2.1.
For example
```
#include <string.h>
int main(int argc, char **argv) {
if (argc >= 2) {
if (strcmp(argv[1], "-p") == 0) /* -p detected */;
}
return 0;
}
```
TLDR: just read the title
|
I'm trying to get the runtime of a given process in kernel space or user space.
Anyway here is what i'm trying to do...
```
//suppose struct task_struct *task has a direct link to pid 1
cputime_t ktime = task->cputime_expires.stime;
cputime_t utime = task->cputime_expires.utime;
cputime_t total = ktime + utime;
printk(KERN_INFO "TOTAL [%lu]",total); // 0
```
why the output is zero ?
|
We'll get process runtime fromtask->utime,task->stime, etc.
Check functionaccount_process_tick()source.
The one you have mentioned i.etask->cputime_expiresis used fortimer_settime()system call to arm a POSIX per-process timer.
|
I recently built a project on VisualStudio. I got an executable in the bin folder and I put all the dependencies x64 DLL inC:\Windows\System32and all the x32 DLL inC:\Windows\SysWOW64
When I execute my executable, I get an error messageThis program can't start because foo.dll is missing from your computer.
I tried to get the dependencies withldd.exeon Cygwin, but I don't see any references tofoo.dll. I also tried to execute from PowerShellStart-Process -PassThru sample.exe, but I still get the same error message.
Where does Windows executables look for DLLs?
I've read that a Windows executable will look for its dependencies in a certain order:
In the local folderIn System32In the %PATH%
I also read that I may need to useregsvr32.exeto register my DLL if it is located into System32.
What is the actual reality of this story?
|
Alternatively, you can simply add the DLL files to the bin folder as well.
|
I'm coding in C with microcontrollers as part of degree and am struggling to find the base address of different components. The microcontroller I am using is the MSP430FR413x and I am currently trying to figure out the base address of the LCD screen so that I can display some text. Could anyone help me either with how to find the base address or what this base address is. Thanks!
|
In the datasheet (http://www.ti.com/lit/ds/symlink/msp430fr4133.pdf) on page 70 they say, that the LCD driver's registers are at0x600. Is that what You are looking for?
|
I am trying to open an absolute path of a PCI device in C code
```
fd = open("/sys/bus/pci/devices/0000:00:01.0/resource", O_RDWR);
if (fd < 0) {
printf("Not found %s\n", path);
return -1;
}
```
But it gives me an error saying Not found /sys/bus/pci/devices/0000:00:01.0/resource
Can anyone please point me out what I am doing here?
|
You are trying to open the path for read/write, but it is only readable (that's what the-r--r--r--inls -loutput means). You'll need to changeO_RDWRtoO_RDONLY.
|
I start working with the termcaps and i saw this kind of operation.
term.c_lflag &= ~(ICANON);
I know&=is abinary AND, and i am not very confortable with it.
Why didn't simply use=or make a#define, and what the&= ~do ?
|
AssumingICANONis a bit-mask, i.e. an integer with bits set to represent some feature, that statement will make sure those bits arenotset inc_lflag.
This is often called "masking off" those bits.
The operation is a bitwise AND with the bitwise inverse (~is bitwise inverse).
So, if the value ofc_lflagis 3 (binary 112) before the operation, andICANONhas the value 2 (binary 102), it will become 1 since it's bitwise-AND:ed with the value~2which has all bits set except bit number 1 (binary ...111012).
It could also be written more verbosely as
```
term.c_lflag = term.c_lflag & ~ICANON;
```
The parentheses aroundICANONshould not be needed.
|
For a student course in c,I want to know if it is possible to use the max width flag identifiers
as an integer you get from the user
example :first iteration of the loop :
```
printf("%7d\n",Number)
```
second iteration of the loop :
```
printf("%6d\n",Number)
```
Third iteration of the loop :
```
printf("%5d\n",Number)
```
and so on... I want to know if it is possible to use something like this:
```
int i;
int userWidthInput=10;
for(i=userWidthInput; i>1;i--)
{
printf("%userWidthInputd\n",Number);
}
```
|
Why not, use like
```
printf("%*d\n",width, Number);
```
So, your code might looks as follow:
```
int i;
int userWidthInput=10;
int Number = 10;
for(i=userWidthInput; i>1;i--)
{
printf("%*d\n",i , Number);
}
```
|
I came accros this line of code:
```
#define BWAKUP ('w' << 8)
```
What does it do? Its the same as:
```
#define BWAKUP (167000)
```
In addition, another definition as :
```
#define CWAKUP (1 + BWAKUP)
```
is equivalent to :
```
#define CWAKUP (356000)
```
Right ?
|
This line define a macroBWAKUPwhich expands to the expression('w' << 8). That expression has, assuming your platform uses ASCII, the value 119 · 256 = 30464 which is not equal to167000.Similarly,CWAKUPexpands to(1 + ('w' << 8))with the numeric value 30465, again assuming your system uses ASCII.
Without more context I can't tell you what the meaning of these macros is.
|
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.Closed7 years ago.Improve this question
A variable is located in memory at address 0x10000. How can I define a macro such that writing to that macro writes to that memory location?
|
The de facto standard way of declaring a writeable memory location in C is this:
```
#define REGISTER (*(volatile uint8_t*)0x10000)
```
whereuint8_tshould correspond to the size of the contents at that memory location.
And thenREGISTER = something;writes to that memory location, just as if REGISTER was a variable.
It is important to use thevolatilekeyword, to prevent optimization bugs and ensuring that reads of the location are always up to date.
|
how to automate gdb execution with "continue command" for multiple signal events?.I have multiple signal exceptions occurring in the code and i have written signal handlers for all the signal exceptions.
when i run the program using gdb i need to each time manually enter "continue" whenever it gets signal event.after I enter continue it continues and catches next signal event and so on , till the end of the program.
i wanted to automate this program execution in gdbinit and get all the data required for debugging for all the signal events.
if there is any method to do this.Please suggest.
Thanks
|
Tocontinuethrough signals, use the following command in your.gdbinitfile for EACH signal of interest:
```
handle SIGNAL_OF_INTEREST nostop
```
To print a message when a signal occurs, use the following command:
```
handle SIGNAL_OF_INTEREST print
```
For more information, see theGDB manual.
|
I'm trying to create a simple program that will allow to execute basic
shell commands. Problem is execve just hangs everytime.
Heres the code:
```
char* arglist[]={"ls","-l",NULL};
char* env[]={NULL};
int status;
while (1)
{
if (fork() != 0)
{
waitpid(-1, &status, 0);
}
else
{
execve(arglist[0],arglist,env);
}
}
return 0;
}
```
|
The first arguments should be a full path to the binary you execute:
```
char* arglist[]={"/bin/ls", "-l", NULL};
```
|
I'm looking into writing a program that takes a text, some wildcard patterns and then shows me the words that match those wildcards. The wildcard pattern contains only., which represents only one character, or*, which can be anything (including a white space, a new line or?!,./\etc.).
Until now, I managed to dynamically read the text and I'm thinking into creating a list with all the words with strtok. Only with., it'd be easy, but I have no idea how to work with*. And expressions, of course, can be a combination of.and*, like this:h.*.(which can be a match forharryfor example).
I'd like you to share some ideas with me. I'm not asking for explicit full code, but for ideas to implement it myself.
|
There's a2001 IOCCC one-liner(schweikh, ahem) that does globbing with*for "zero or more characters" and?for "exactly one character".
Figuring out how that one works is probably enlightening and gives you plenty of ideas.
|
I'm trying to run the code from this topic (first answer):getting mouseclick coordinates with Xliband it gives me some errors.
Output:
```
$ ./a.out
X Error of failed request: BadAccess (attempt to access private resource denied)
Major opcode of failed request: 2 (X_ChangeWindowAttributes)
Serial number of failed request: 8
Current serial number in output stream: 8
```
|
Should use:gcc c.cc -lX11And change one string to:XSelectInput(display, root, ButtonReleaseMask);
|
i try to compile lagecy code in visual studio 2013
in some part of the code i have this section which gives me compilation error which i dont understand :
```
{
const char* str ="111";
const char* str1 = "TTTTTT";
str -= str1;
...
...
}
\example\example.c(170): error C2297: '-=' : illegal, right operand has type 'const char *'
\example\example.c(170): error C2114: '-=' : pointer on left; needs integral value on right
```
what is wrong here ?
|
This code looks terrible. It's not valid C or C++. We can only guess what it meant to do. Perhaps you could replace the last line with the following:
```
str = (void*)(str - str1);
```
but there's no guarantee it will work correctly.
|
How to debug the modules in Linux? As their will be no executable file for the modules? What does ELF will do ? Only the Makefile i have complied and given me object file and various other files.
|
As their will be no executable file for the modules?
There is no executable (likea.out), but there is kernel object file*.ko. Kernel object files areadded toorremoved fromthe kernel viainsmodandrmmod.
So at minimum, you need to be able to do the following to debug a kernel module:
Locate the module itself (*.cfile and corresponding*.kokernel object).Add (a lot of)printkRebuild the kernel.rmmodthe old module,insmodthe new version.Watch out debug logs, normally viadmesg.
|
The code is to check if there is a blank line. I thought when I enter some text, it will keep doing the printf(), because it is stuck in the loop. But in fact, it just does the printf() once, and waits for another line of text. Why? Is it because the input will be wiped after the gets() function?
Here is the code
```
int main(){
char input[257];
char *ptr;
puts("Enter text a line at a time, then press Enter");
puts("Enter a blank line when done");
while( *(ptr= gets(input)) != NULL){
printf("You've entered: %s\n", input);
}
puts("Thank you and goodbye\n");
return 0;
}
```
|
this while should do the trick
```
while( (ptr= gets(input)) != NULL && input[0]!='\0')
```
|
Going through the K&R ansi C programming language book (second version), on page 82 an example is given for a programming files/folders layout.
What I don't understand is, whilecalc.hgets included inmain(use of functions),getop.c(definition of getop) andstack.c(definition of push and pop), it does not get included intogetch.c, even thoughgetchandungetchare defined there.
|
Although it's a good idea to include the header file it's not required asgetch.cdoesn't actuallyusethe function declared incalc.h, it could even get by if it only used those already defined ingetch.c.
The reason it's a good idea to include the header file anyway is because it would provide some safety if you use modern style prototypes and definitions. The compiler should namely complain if for examplegetopisn't defined ingetop.cwith the same signature as incalc.h.
|
I'm looking into writing a program that takes a text, some wildcard patterns and then shows me the words that match those wildcards. The wildcard pattern contains only., which represents only one character, or*, which can be anything (including a white space, a new line or?!,./\etc.).
Until now, I managed to dynamically read the text and I'm thinking into creating a list with all the words with strtok. Only with., it'd be easy, but I have no idea how to work with*. And expressions, of course, can be a combination of.and*, like this:h.*.(which can be a match forharryfor example).
I'd like you to share some ideas with me. I'm not asking for explicit full code, but for ideas to implement it myself.
|
There's a2001 IOCCC one-liner(schweikh, ahem) that does globbing with*for "zero or more characters" and?for "exactly one character".
Figuring out how that one works is probably enlightening and gives you plenty of ideas.
|
I'm trying to run the code from this topic (first answer):getting mouseclick coordinates with Xliband it gives me some errors.
Output:
```
$ ./a.out
X Error of failed request: BadAccess (attempt to access private resource denied)
Major opcode of failed request: 2 (X_ChangeWindowAttributes)
Serial number of failed request: 8
Current serial number in output stream: 8
```
|
Should use:gcc c.cc -lX11And change one string to:XSelectInput(display, root, ButtonReleaseMask);
|
i try to compile lagecy code in visual studio 2013
in some part of the code i have this section which gives me compilation error which i dont understand :
```
{
const char* str ="111";
const char* str1 = "TTTTTT";
str -= str1;
...
...
}
\example\example.c(170): error C2297: '-=' : illegal, right operand has type 'const char *'
\example\example.c(170): error C2114: '-=' : pointer on left; needs integral value on right
```
what is wrong here ?
|
This code looks terrible. It's not valid C or C++. We can only guess what it meant to do. Perhaps you could replace the last line with the following:
```
str = (void*)(str - str1);
```
but there's no guarantee it will work correctly.
|
How to debug the modules in Linux? As their will be no executable file for the modules? What does ELF will do ? Only the Makefile i have complied and given me object file and various other files.
|
As their will be no executable file for the modules?
There is no executable (likea.out), but there is kernel object file*.ko. Kernel object files areadded toorremoved fromthe kernel viainsmodandrmmod.
So at minimum, you need to be able to do the following to debug a kernel module:
Locate the module itself (*.cfile and corresponding*.kokernel object).Add (a lot of)printkRebuild the kernel.rmmodthe old module,insmodthe new version.Watch out debug logs, normally viadmesg.
|
The code is to check if there is a blank line. I thought when I enter some text, it will keep doing the printf(), because it is stuck in the loop. But in fact, it just does the printf() once, and waits for another line of text. Why? Is it because the input will be wiped after the gets() function?
Here is the code
```
int main(){
char input[257];
char *ptr;
puts("Enter text a line at a time, then press Enter");
puts("Enter a blank line when done");
while( *(ptr= gets(input)) != NULL){
printf("You've entered: %s\n", input);
}
puts("Thank you and goodbye\n");
return 0;
}
```
|
this while should do the trick
```
while( (ptr= gets(input)) != NULL && input[0]!='\0')
```
|
Going through the K&R ansi C programming language book (second version), on page 82 an example is given for a programming files/folders layout.
What I don't understand is, whilecalc.hgets included inmain(use of functions),getop.c(definition of getop) andstack.c(definition of push and pop), it does not get included intogetch.c, even thoughgetchandungetchare defined there.
|
Although it's a good idea to include the header file it's not required asgetch.cdoesn't actuallyusethe function declared incalc.h, it could even get by if it only used those already defined ingetch.c.
The reason it's a good idea to include the header file anyway is because it would provide some safety if you use modern style prototypes and definitions. The compiler should namely complain if for examplegetopisn't defined ingetop.cwith the same signature as incalc.h.
|
Here is the string format I am trying to print:
values: "The harmonic sum of %ld terms is %1.18lf, which is 0x%016lx"
Here is the code in assembly:
```
mov qword rax, 2
mov rdi, values
mov rsi, r15
call printf
```
Basically it is outputting the first two values correctly, but the third prints as "0x0000000000000000" which is not correct. The thing is that if I change "%016lx" to something else like "%a" or %1.18lf" it appears to be receiving the correct value so I have no idea why the conversion isn't working for the "%lx" format in particular.
The lower half of xmm0 and xmm1 both contain the desired value I wish to print.
|
%lxreads along int. Integer values are stored in the integer registers, whichxmm1is not. The value should be stored in the next integer register (which isrdxaccording to Jester's comment).
|
Please view this block of code:
```
typedef struct node
{
int data;
struct node *next;
}
Node;
```
In this code, isNodesynonymous tostruct node, as defined by typedef, or isnodesynonymous to struct? If the latter is the case, then isstruct node *next;equivalent tostruct struct *next;?
Am I overcomplicating things?
|
When you usetypedefyou create analiasof some type.
So yes,Nodeis an alias forstruct node.
Also, the code you have is equivalent to
```
struct node
{
int data;
struct node *next;
};
typedef struct node Node;
```
Thetypedefis not part of the structure definition, it part of theNodedefinition.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve this question
```
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main() {
int size_to_alloc = sizeof(char*) * 1;
char** p = (char**) malloc(size_to_alloc);
p[0] = (char*) malloc (sizeof(char) * 10);
strcpy("hello", p[0]);
printf("%s\n", p[0]);
}
```
I am obviously missing something very basic but can't figure out what.
|
strcpy()function has argument mismatch.
usage of string copy as per theman pagechar *strcpy(char *dest, const char *src);
So yourstrcpy()call has to bestrcpy(p[0], "hello");
|
```
char **commands = parse_line( input, ';' );
int i = 0;
while ( commands[i]) {
/* Runs some functions, commands[i] not affected */
i++;
}
```
Header forparse_line
```
char **parse_line(char *line)
```
In the while loop, cancommand[i]actually ever be true?
char *linewould be something along the lines ofls -l\n.
NOTE:\nis included due to user having to pressRETURNafter entering a terminal command.
|
Sincecommand[i]refers to achar *, it is considered1if non-null and0if null.
|
```
asm("lidt (%0)" : : "p"(&idtr));
```
The above statement will be used to define an IDTR in my IA-32 operating system. For some reason though, the compiler chokes on it:
```
kernel/kernel.c:52:2: error: invalid 'asm': invalid expression as operand
asm("lidt (%0)" : : "p"(&idtr));
^
```
Does anyone know what I'm doing wrong here? If you need any more context to answer my question, please say so and I will gladly provide it.
|
Apart from the instruction, you got every possible thing wrong.
The correct way:
```
asm("lidt %0" : : "m"(idtr));
```
|
How to get input from a c program to a batch file as return value to access menu by selecting a number among 1 - 4 . The numbers are given as user input in c file.
For example:
```
:START
start cChoice.exe
IF ERRORLEVEL 1 GOTO ONE
IF ERRORLEVEL 2 GOTO TWO
IF ERRORLEVEL 3 GOTO THREE
IF ERRORLEVEL 4 GOTO FOUR
:ONE ECHO ONE Start notepad %1 exit /b %ERRORLEVEL%
:TWO ........
```
Help Plz. I am new in Batch..
|
The return value frommain()is the value of ERRORLEVEL. Alternatively the value passed to theexit()function.
However thestartcommand causes the process to run concurrently to the batch file in a different cmd instance, so the batch file will not receive the errorlevel. You should have:
```
:START
cChoice.exe
IF ERRORLEVEL 1 GOTO ONE
```
|
I do not understand why the following code:
```
char** receive_message(char** ret)
{
char* temp = "text";
strcpy(&ret, temp);
return ret;
}
```
gives this error:
```
warning: passing argument 1 of ‘strcpy’ from incompatible pointer type [enabled by default]
strcpy(&ret, temp);
```
I'm trying to copy a message that is generated inside a function to a char* array that is allocated outside the function.
|
Use
```
strcpy(*ret, temp);
```
Instead of
```
strcpy(&ret, temp);
```
You need to deference char ** instead of taking a reference of it.
|
I have a client-server program in c.
I'm using select to ensure that the client is ready to accept data, (i.e. - client_fd is in write_fds returned by select).
If the client is indeed ready to accept data, can I be sure that if I send to this client (using the c method 'send', and number of bytes to be sent is > 0), the number of bytes actually sent (==returned by 'send') is at least 1 byte? or 0 is still possible?
thanks
*note that the client is connected to only one server and nothing else.
|
Zero is never possible. It will either transfer at least one byte and return the cost, or return -1 witherrno == EAGAIN/EWOULDBLOCKif the buffer is full in non-blocking mode, or -1 with some othererrnoif there is a bad error. It shouldn't give-1/EAGAIN/EWOULDBLOCKifselect()has indicated otherwise, except in the presence of multithreaded writing to the socket.
|
I'm playing around with all sorts of small hardware. In an attempt to learn it. I would like to run mruby. I've compiled for my hardware. And have the framework as well as the include MIRB and MRUBY bins.
But I would potentially like the code my own IRB. I am a programmer by trade, but have never dealt in anything this low level since college.
Where do i begin in the process, my google-foo is not cutting it.
|
Once you can execute ruby code on the platform you are running on, it's just a matter of gluing up togetherevalandreadline. For something more advanced, I advice you to take a look at theruby source code, you will find the complete irb sources inbin/irb.rb,lib/irb.rband thelib/irbdirecotry. Have fun!
|
I want to generate a random float value between 0 and 1 excluding 1, I.e.[0, 1). I've searched a lot but I couldn't find an answer of this. I've tried the following trick however it generates a negative values
```
(double)rand()/(double)RAND_MAX-1;
```
|
You need parentheses to force the right order:
```
(double)rand()/((double)RAND_MAX + 1);
```
Also note, that you need +1, not -1.
|
I have a char array calledtempsthat is passed to a function. The format will always be like this:
1 1.1
I want to split it up and save these two numbers. These is a space between them but after researchingstrtok(), I have no idea how it works.
```
void seperate(char *tempformat){
char s1[10];
char s2[10];
s1 = strtok();
s2 = strtok();
}
```
|
You can do it as :
```
char *result;
char s=" "; //space(delimiter)
char str[];
result = strtok(tempformat, s);
void seperate(char *tempformat){
while( result != NULL ) {
printf( " %s\n", result ); //You can save the result into a array of characters as well.
result = strtok(NULL, s);
}
}
```
|
So I have a homework thing that asks me "How do you convert an int to a float?".
Google searches gives me alot of different results, the most promising being Type Casting.
But what I'm unsure of is how I make thevariableitself a float from an int.
I.e, i haveint n=5, and want to later convert it so that it is treated as a float until the code specifies otherwise. How can I do that?
Can i just do:n = (float)n?
Thanks in advance!
|
you can convert int type var to float type val by type casting and also float to int. it is the best way to convert data type.
for int to float =>
```
int a = 6;
float b = (float)a;
```
and for float to int =>
```
float a = 6.0;
int b = (int)a;
```
|
I had a homework saying that i should
create a program which takes a string and remove all successive
repetitions in it.
i don't know why it doesn't work,
this is my code :
```
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
int main()
{
char ch[50];
gets(ch);
int i;
for (i=0;i<strlen(ch)-1;i++);
{
while (ch[i] == ch[i+1])
strcpy(ch+i,ch+i+1);
}
puts(ch);
return 0;
}
```
|
Remove the ; after for loop because it terminates the loop and is wrong.
|
there is a code snippet:
```
#include<stdio.h>
int main(void){
char c;
while( (c=getchar()) != EOF){
putchar(c);
}
}
```
these code coming from chapterI/Oof a book namedUnix Advanced Programming,and it says the code will work not well in some machines,I tried the code in my mac,and it will work well,then anyone can tell me what's problem will have when run above code and why it occurs,thanks!
Update:
the code come from chapter I/O,so I think it will relevant to I/O operation.
|
Storeing results ofgetchar()to variables havingchartype is a bad practice becauseEOFwon't fit inchartype. Usingintis good.Not returning any values from main functon usingreturnstatement in old C may confuse some system such as online judge and treat the code as made Runtime Error. You should writereturn 0;at the end of function.
|
I want to convertchararray filled by user (likepart1in code below) to hexadecimal. In fact, convert twocharto one hexadecimalchar.
```
char part1[2];
char ans;
part1[0]='f';
part1[1]='2';
```
Now I can putpart1hex to charanslike this:
```
ans=0xf2;
```
|
Step 1: Parse each textual character as a number:
```
unsigned int parse_char(char c)
{
if ('0' <= c && c <= '9') return c - '0';
if ('a' <= c && c <= 'f') return 10 + c - 'a';
if ('A' <= c && c <= 'F') return 10 + c - 'A';
abort();
}
```
Step 2: Use mathematics to assemble the result, following the rules of the place-value notation:
```
unsigned char ans = parse_char(part1[0]) * 0x10 + parse_char(part1[1]);
```
|
I had too many problems with compiling different libraries for json and finally I got an already compiled library of json which is cJSON to be linked with my project but when I downloaded it, and linked it with a test c file like:
```
//file1.c
#include "cJSON.h"
...
...
...
```
then I compiled it through gcc using command:
```
gcc file1.c -lcJSON
```
it returns:
```
file1.c:7:19: fatal error: cJSON.h: No such file or directory
#include "cJSON.h"
```
|
Well, finally after several tries I succeed to figure out the problem and fix it. since cJSON is a static library so I can not perform dynamic linking like:-lcJSON, the perfect way to compile file1.c and link cJSON lib to it, is by:
Add cJSON.c and cJSON.h files to the same directory of file1.c.Include "cJSON.h" in file1.c .execute the commandgcc cJSON.c file1.c -lm.
Finally compilation success.
|
I'm on an Assignment.
The Assignment is making virtual Real Time Operating System on Linux System(on Ubuntu).
My problem is SIGALRM and it's handler for Scheduler.
```
void scheduler(int signo) {
/*variables */
printf("Scheduler awake!!\n");
/* Do
Schedule */
}
int RunScheduler(void) {
signal(SIGALRM, scheduler);
alarm(1);
while(1)
pause();
return 0;
}
int main() {
RunScheduler();
}
```
The function scheduler(handler) does not work. alarm(1) works, but just paused after alarm(1).
Is there any reason signal handler does not work??
|
The very same code works correctly on my machine.
I have used the gcc compiler that comes bundled with Ubuntu. Are you using the same compiler?
|
So I have a homework thing that asks me "How do you convert an int to a float?".
Google searches gives me alot of different results, the most promising being Type Casting.
But what I'm unsure of is how I make thevariableitself a float from an int.
I.e, i haveint n=5, and want to later convert it so that it is treated as a float until the code specifies otherwise. How can I do that?
Can i just do:n = (float)n?
Thanks in advance!
|
you can convert int type var to float type val by type casting and also float to int. it is the best way to convert data type.
for int to float =>
```
int a = 6;
float b = (float)a;
```
and for float to int =>
```
float a = 6.0;
int b = (int)a;
```
|
I had a homework saying that i should
create a program which takes a string and remove all successive
repetitions in it.
i don't know why it doesn't work,
this is my code :
```
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
int main()
{
char ch[50];
gets(ch);
int i;
for (i=0;i<strlen(ch)-1;i++);
{
while (ch[i] == ch[i+1])
strcpy(ch+i,ch+i+1);
}
puts(ch);
return 0;
}
```
|
Remove the ; after for loop because it terminates the loop and is wrong.
|
there is a code snippet:
```
#include<stdio.h>
int main(void){
char c;
while( (c=getchar()) != EOF){
putchar(c);
}
}
```
these code coming from chapterI/Oof a book namedUnix Advanced Programming,and it says the code will work not well in some machines,I tried the code in my mac,and it will work well,then anyone can tell me what's problem will have when run above code and why it occurs,thanks!
Update:
the code come from chapter I/O,so I think it will relevant to I/O operation.
|
Storeing results ofgetchar()to variables havingchartype is a bad practice becauseEOFwon't fit inchartype. Usingintis good.Not returning any values from main functon usingreturnstatement in old C may confuse some system such as online judge and treat the code as made Runtime Error. You should writereturn 0;at the end of function.
|
I want to convertchararray filled by user (likepart1in code below) to hexadecimal. In fact, convert twocharto one hexadecimalchar.
```
char part1[2];
char ans;
part1[0]='f';
part1[1]='2';
```
Now I can putpart1hex to charanslike this:
```
ans=0xf2;
```
|
Step 1: Parse each textual character as a number:
```
unsigned int parse_char(char c)
{
if ('0' <= c && c <= '9') return c - '0';
if ('a' <= c && c <= 'f') return 10 + c - 'a';
if ('A' <= c && c <= 'F') return 10 + c - 'A';
abort();
}
```
Step 2: Use mathematics to assemble the result, following the rules of the place-value notation:
```
unsigned char ans = parse_char(part1[0]) * 0x10 + parse_char(part1[1]);
```
|
Can i create my own properties with:
```
XChangeProperty(display, w, property, type, format, mode, data, nelements)
```
or can i only use the properties shown in
standards.freedesktop.org?
|
You can create any property you want.
Just doXInternAtomwith your unique atom name, and you have apropertyof your own. Same fortype.
|
This question already has answers here:How much memory would be freed if pointer is changed in C?(3 answers)Closed7 years ago.
Let's say I have allocated a big enoughchar**array.
Why can I dofree(arr)but notfree(arr + 5)?
Please notice that I'm not speaking aboutarr[0]orarr[5].
|
You always callfree()with the pointer that was returned bymalloc(),realloc()orcalloc(). You must not pass any other pointers.
From thefree()manual:
The free() function frees the memory space pointed to by ptr, which
must have been returned by a previous call to malloc(), calloc(), or
realloc(). Otherwise, or if free(ptr) has already been called
before, undefined behavior occurs. If ptr is NULL, no operation is
performed.
|
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.Closed7 years ago.Improve this question
I've newly started learningSystem Programming. I got confused with these two functions. could any one tell me what are the differences between these Functions
inportb()andinport()
outportb()andoutport()??
|
inportb()andoutportb()are macros. Plus,outportb()accepts anint portand achar bytewhereasoutport()hasint portandint wordas parameters.
Please seethis linkfor some more details.
|
Hello I have this code that fills the array with a pointer and print it with a pointer as well. The result is faulse. Here is my code:
```
#include<stdio.h>
#include<stdlib.h>
int main(){
int p;
char po[8];
char *i;
i=po;
for(p=0; p<8; p++){
scanf("%c\n", i++);
}
for(p=0; p<8; p++){
printf("%c\n", *(i++));
}
return 0;
}
```
where is my fault?
|
There can be good reasons for increasing pointers. Simply do not forget to reset them to their initial value before reusing them!
Your code should be:
```
i=po;
for(p=0; p<8; p++){
scanf("%c\n", i++);
} /* i is now po + 8 ... */
i = po;
for(p=0; p<8; p++){
printf("%c\n", *(i++));
}
```
Now you should learn not to write such code:
blocks are not indented => harder to readvalue of scanf is never tested: what happens on end of file (Ctrl-D on Unix-like, Ctrl-Z on Windows)?not even one single comment...
|
I am trying to use a variable I have already declared on a .h file on a .c file and i gives me a compile error:
undefined reference tovar
this is the mach.c content:
```
#include "machheader.h"
int
main( void )
{
var = 1;
printf("Variable %d\n", var);
}
```
And my machheader.h contains only this:
extern int var;
Any idea?
|
In your case,
```
extern int var;
```
is adeclaration, not a definition. You need to have a definition ofvarin your code.
|
First of all, sorry if someone already asked about this question.
I did search about this first, but couldn't find one.
I used to see some people doing something like this:
```
if ( // a certain conditions here ) {
error("ERROR: not bla bla bla")
}
```
what iserror(....)? What is the difference withprintf()?
Why they aren't usingprintf("ERROR: not bla bla bla")instead?
Thank you.
|
As i know, c language has no function name "error". I think that is a function or a macro is coded or defined by user.
To handle error in c, you can read this link. It has some different points with printf function.http://www.tutorialspoint.com/cprogramming/c_error_handling.htm
|
I have a question: how do I make thelua_tostringfunction limit the amount of entries.
For example 8 characters limit:
```
poppy_name = "command"; // OK, within the limit;
poppy_name = "commander"; // Fail, Is out of range, show a message the permitted limit.
```
I searched I couldn't find anymore, is there a way to limit thelua_tostring?
|
Uselua_tolstringto obtain the string length, then uselua_errororluaL_errorif the string is too long.
```
size_t arg_len;
lua_tolstring(L, 1, &arg_len);
if (arg_len > 8) return luaL_error(L, "argument too long");
```
|
Can i create my own properties with:
```
XChangeProperty(display, w, property, type, format, mode, data, nelements)
```
or can i only use the properties shown in
standards.freedesktop.org?
|
You can create any property you want.
Just doXInternAtomwith your unique atom name, and you have apropertyof your own. Same fortype.
|
This question already has answers here:How much memory would be freed if pointer is changed in C?(3 answers)Closed7 years ago.
Let's say I have allocated a big enoughchar**array.
Why can I dofree(arr)but notfree(arr + 5)?
Please notice that I'm not speaking aboutarr[0]orarr[5].
|
You always callfree()with the pointer that was returned bymalloc(),realloc()orcalloc(). You must not pass any other pointers.
From thefree()manual:
The free() function frees the memory space pointed to by ptr, which
must have been returned by a previous call to malloc(), calloc(), or
realloc(). Otherwise, or if free(ptr) has already been called
before, undefined behavior occurs. If ptr is NULL, no operation is
performed.
|
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.Closed7 years ago.Improve this question
I've newly started learningSystem Programming. I got confused with these two functions. could any one tell me what are the differences between these Functions
inportb()andinport()
outportb()andoutport()??
|
inportb()andoutportb()are macros. Plus,outportb()accepts anint portand achar bytewhereasoutport()hasint portandint wordas parameters.
Please seethis linkfor some more details.
|
Hello I have this code that fills the array with a pointer and print it with a pointer as well. The result is faulse. Here is my code:
```
#include<stdio.h>
#include<stdlib.h>
int main(){
int p;
char po[8];
char *i;
i=po;
for(p=0; p<8; p++){
scanf("%c\n", i++);
}
for(p=0; p<8; p++){
printf("%c\n", *(i++));
}
return 0;
}
```
where is my fault?
|
There can be good reasons for increasing pointers. Simply do not forget to reset them to their initial value before reusing them!
Your code should be:
```
i=po;
for(p=0; p<8; p++){
scanf("%c\n", i++);
} /* i is now po + 8 ... */
i = po;
for(p=0; p<8; p++){
printf("%c\n", *(i++));
}
```
Now you should learn not to write such code:
blocks are not indented => harder to readvalue of scanf is never tested: what happens on end of file (Ctrl-D on Unix-like, Ctrl-Z on Windows)?not even one single comment...
|
I am trying to use a variable I have already declared on a .h file on a .c file and i gives me a compile error:
undefined reference tovar
this is the mach.c content:
```
#include "machheader.h"
int
main( void )
{
var = 1;
printf("Variable %d\n", var);
}
```
And my machheader.h contains only this:
extern int var;
Any idea?
|
In your case,
```
extern int var;
```
is adeclaration, not a definition. You need to have a definition ofvarin your code.
|
First of all, sorry if someone already asked about this question.
I did search about this first, but couldn't find one.
I used to see some people doing something like this:
```
if ( // a certain conditions here ) {
error("ERROR: not bla bla bla")
}
```
what iserror(....)? What is the difference withprintf()?
Why they aren't usingprintf("ERROR: not bla bla bla")instead?
Thank you.
|
As i know, c language has no function name "error". I think that is a function or a macro is coded or defined by user.
To handle error in c, you can read this link. It has some different points with printf function.http://www.tutorialspoint.com/cprogramming/c_error_handling.htm
|
The child thread in this code blocks the shell, even after the main process exits. How do I make it run in the background and not block the shell? I see it is possible withfork(), but I do not want to create a whole new process.
Thank you.
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void * myThreadFun (void *vargp)
{
while (1)
{
//Do useful work continuously
sleep (1);
}
}
int
main ()
{
pthread_t tid;
pthread_create (&tid, NULL, myThreadFun, NULL);
pthread_detach (tid);
printf ("After Thread\n");
pthread_exit (0);
}
```
|
In a multi-threaded program, there is no way for the main thread to actually exit and leave spawned threads running. If you need this program to continue running when you execute it from a shell but immediately return to a shell prompt, i.e., run in the background, you will have to use fork().
|
This is my implementation to detect if an unsigned int overflow has occurred when trying to add two numbers.
The max value of unsigned int (UINT_MAX) on my system is 4294967295.
```
int check_addition_overflow(unsigned int a, unsigned int b) {
if (a > 0 && b > (UINT_MAX - a)) {
printf("overflow has occured\n");
}
return 0;
}
```
This seems to work with the values I've tried.
Any rogue cases? What do you think are the pros and cons?
|
You could use
```
if((a + b) < a)
```
The point is that ifa + bis overflowing, the result will be trimmed and must be lower thena.
Consider the case with hypothetical bound range of 0 -> 9 (overflows at 10):
bcan be 9 at the most. For any valueasuch thata + b >= 10,(a + 9) % 10 < a.For any valuesa,bsuch thata + b < 10, sincebis not negative,a + b >= a.
|
I know how to replacemallocwithLD_PRELOAD; library that preloaded gets priority, so if we preloadjemalloc, executable gets itsmallocversion.
However, when we build application with-ljemalloc, we also link it againstglibc. How Linux knows that it has to usejemallocmallocand notglibcone? What if I will link bothjemallocandtcmalloc, we'll have 3mallocnow, what and why Linux (or may be the linker, I am not sure) will select?
|
You can check the order of libraries being loaded by running:
strace -ff -s 999 YOUR_BINARY 2>&1 | grep -e 'library1' -e 'library2'
The order should match the output fromldd YOUR_BINARY.
And yes, as already noted, the first library will get priority.
|
I recently came across a golf coding†question in which I thought of writing a function of typeintinmainitself, which could access all variables inside main. But to reduce the number of characters, I thought of writing a function alongside a variable. Something like this :
```
int i,f(){/*function code*/};
```
Can I do this? If Yes/No, then why?
†Code Golf is a form of recreational programming in which a given challenge must be solved with the shortest possible program. Reducing the number of characters in the source code is the primary objective, maintainability and readability is unimportant. Please consider this objective before commenting.
|
```
int i,f(){/*function code*/};
```
In C, no you cannot it is not a valid syntax.
What you can do is this:
```
int i, f(); /* declare an int i and a function f that returns an int */
```
which is probably not what you want.
|
This is my implementation to detect if an unsigned int overflow has occurred when trying to add two numbers.
The max value of unsigned int (UINT_MAX) on my system is 4294967295.
```
int check_addition_overflow(unsigned int a, unsigned int b) {
if (a > 0 && b > (UINT_MAX - a)) {
printf("overflow has occured\n");
}
return 0;
}
```
This seems to work with the values I've tried.
Any rogue cases? What do you think are the pros and cons?
|
You could use
```
if((a + b) < a)
```
The point is that ifa + bis overflowing, the result will be trimmed and must be lower thena.
Consider the case with hypothetical bound range of 0 -> 9 (overflows at 10):
bcan be 9 at the most. For any valueasuch thata + b >= 10,(a + 9) % 10 < a.For any valuesa,bsuch thata + b < 10, sincebis not negative,a + b >= a.
|
I know how to replacemallocwithLD_PRELOAD; library that preloaded gets priority, so if we preloadjemalloc, executable gets itsmallocversion.
However, when we build application with-ljemalloc, we also link it againstglibc. How Linux knows that it has to usejemallocmallocand notglibcone? What if I will link bothjemallocandtcmalloc, we'll have 3mallocnow, what and why Linux (or may be the linker, I am not sure) will select?
|
You can check the order of libraries being loaded by running:
strace -ff -s 999 YOUR_BINARY 2>&1 | grep -e 'library1' -e 'library2'
The order should match the output fromldd YOUR_BINARY.
And yes, as already noted, the first library will get priority.
|
I recently came across a golf coding†question in which I thought of writing a function of typeintinmainitself, which could access all variables inside main. But to reduce the number of characters, I thought of writing a function alongside a variable. Something like this :
```
int i,f(){/*function code*/};
```
Can I do this? If Yes/No, then why?
†Code Golf is a form of recreational programming in which a given challenge must be solved with the shortest possible program. Reducing the number of characters in the source code is the primary objective, maintainability and readability is unimportant. Please consider this objective before commenting.
|
```
int i,f(){/*function code*/};
```
In C, no you cannot it is not a valid syntax.
What you can do is this:
```
int i, f(); /* declare an int i and a function f that returns an int */
```
which is probably not what you want.
|
I know how to replacemallocwithLD_PRELOAD; library that preloaded gets priority, so if we preloadjemalloc, executable gets itsmallocversion.
However, when we build application with-ljemalloc, we also link it againstglibc. How Linux knows that it has to usejemallocmallocand notglibcone? What if I will link bothjemallocandtcmalloc, we'll have 3mallocnow, what and why Linux (or may be the linker, I am not sure) will select?
|
You can check the order of libraries being loaded by running:
strace -ff -s 999 YOUR_BINARY 2>&1 | grep -e 'library1' -e 'library2'
The order should match the output fromldd YOUR_BINARY.
And yes, as already noted, the first library will get priority.
|
I recently came across a golf coding†question in which I thought of writing a function of typeintinmainitself, which could access all variables inside main. But to reduce the number of characters, I thought of writing a function alongside a variable. Something like this :
```
int i,f(){/*function code*/};
```
Can I do this? If Yes/No, then why?
†Code Golf is a form of recreational programming in which a given challenge must be solved with the shortest possible program. Reducing the number of characters in the source code is the primary objective, maintainability and readability is unimportant. Please consider this objective before commenting.
|
```
int i,f(){/*function code*/};
```
In C, no you cannot it is not a valid syntax.
What you can do is this:
```
int i, f(); /* declare an int i and a function f that returns an int */
```
which is probably not what you want.
|
I'm trying to send a string with a null terminating character inside of it to another connection.
Now I'm not dumb, I know a string will stop at that character, but is there any possible way to send a string to a socket like this, "Test\x00AFTERNULL\x00\r\n".
I was thinking maybe there's a way to convert it from one encoding to another or something. I'm not exactly smart in this area. Thanks for any help/input.
|
Sending over socket is not related to having null in middle of string or not, becausesend()will send a buffer with specific size.
This buffer can have any amount of zeroes in middle of it. You probably have usedstrlen()to get size of string and used it insend()which result in incorrect buffer length and missing some part of data.
You can do it like this for example (very simple one):
```
char buf[] = "Test\0AFTERNULL\0\r\n";
//'s' is socket descriptor
send(s, buf, sizeof(buf), 0);
```
|
On the command line prompt, is it possible to pass a parameter to the hwut command, e.g. in order to use that parameter as an identifier to open a particular serial port ?
|
I guess, the easiest way is to use environment variables. Let's say your test is written in "C", then do
```
set MY_VARIABLE=4711 # DOS
export MY_VARIABLE=4711 # Unix & Co
hwut my-test.exe
```
where the file "my-test.c" is the source of "my-test.exe" and contains
```
#include <stdlib.h>
...
int main(int argc, char** argv)
{
...
const char* MyVariable_str = getenv("MY_VARIABLE");
int my_variable;
my_variable = MyVariable_str ? atoi(MyVariable_str) : -1;
...
}
```
The propper solution, of course, is to have some configuration file which is
configured globally and parsed by the test applications. The overhead for that, however, might not always be justified.
|
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.Closed7 years ago.Improve this question
```
void fade(ImagenBMP *imagen1, ImagenBMP *imagen2, int f) {
float v = (float)f/255;
for (int i = 0; i < imagen1->tamanyo; i++) {
imagen1->datos[i] = (imagen1->datos[i] - imagen2->datos[i])*v + imagen2->datos[i];
}}; //end of fade
```
It's supose to fade two images into a single one.
|
If you rewrite the equation, you will end up with:
```
imagen1->datos[i] = v*imagen1->datos[i] + (1-v)*imagen2->datos[i];
```
This is how the blend works. You are specifying how much of the first image (out of 255 parts) should be included in the function parameterf,255-fparts will be included from the second image.
|
Assumesizeof(int).
Then, what's the total size of bytes that will be allocated on the dynamic heap?
And can you please explain why?
```
#include<stdio.h>
#include<stdlib.h>
#define MAXROW 8
#define MAXCOL 27
int main()
{
int (*p)[MAXCOL];
p = (int (*) [MAXCOL])malloc(MAXROW *sizeof(*p));
return0;
}
```
|
Assume "sizeof(int) is "(what?)... I guess you meant 4.
In the first line you declare p to be a pointer to an array of 27 integers.
In the second line you allocate memory in the heap for size of dereferenced p - which is 27 integers times 8 - that's 27*4*8 so the number of bytes allocated is 864.
|
I have this code:
```
char *name = malloc(strlen(args[1]) + 6);
strncpy(name, args[1], strlen(args[1]));
printf("%d\n", strlen(name));
```
Let's sayargs[1]is "hello" and sostrlen(args[1])is 5.
After malloccing 11 bytes, I then copy 5 bytes of "Hello" (meaning I want to exclude the null terminating byte) to name.
Butstrlen(name)isn't 5. I get 8. Shouldn't it be 5 since you that's what you copied over?
|
This code usesstrncpyincorrectly. Thestrncpyfunction is an unsafe version ofstrcpyand should be avoided; using it correctly requires writing unnecessarily complicated code.
Instead you can write:
```
char *name = malloc(strlen(args[1]) + 6);
strcpy(name, args[1]);
printf("%zu\n", strlen(name);
```
|
```
int num4[10] = {3,4,8,9};
int num2[10] = {3,8,6,8};
compare2 = memcmp(num4, num2, 4);
```
Why is the value of compare2 zero even though the arrays are not equal?
|
The third argument tomemcmpis the number of bytes, not the number of elements.
You meant:
```
memcmp(num4, num2, 4 * sizeof num4[0]);
```
Your existing code only compares the first four bytes. If your system has 4-byte ints (which is common) then you only compared the first int.
I usedsizeof num4[0]instead ofsizeof(int)so that the code still works even if you later changenum4andnum2to be a different type of array.
|
```
FILE *test;
student st;
int i = 0;
test = fopen("example.bin", "rb");
while (feof(test))
{
fread(&st, sizeof(st),1,test);
Class[i] = st;
i++;
}
fclose(test);
```
So my question is how to read it, put the data in my structure and stop the loop?
|
Seewhy is while(feof) always wrong.
Instead, you should loop until you fail to read a student:
```
while (1 == fread(&st, sizeof st, 1, test))
{
Class[i++] = st;
}
```
Also it would be good to make sure you don't overflow the buffer ofClass, so put in a check foritoo, e.g.:
```
for (i = 0; i < MAX_CLASS && 1 == fread(&st, sizeof st, 1, test); ++i)
{
Class[i] = st;
}
```
|
This question already has answers here:Bitwise '&' operator(6 answers)Closed7 years ago.
i have this code :
```
#include<stdio.h>
int main(void)
{
if (-8 & 7)
{
printf("Math is good -8 and 7 are both not zero\n");
}
else
{
printf("Everything we know is a lie!\n");
}
system("PAUSE");
return (0);
}
```
I'm new to C and my trying to figure out what this & operator does, can someone explain this to me?
|
Contrary to your question, the program prints
```
Everything we know is a lie!
```
The bitwise operation of&is this
```
dec binary
-8 111111111111111111111000
7 000000000000000000000111
------------------------
& 000000000000000000000000
```
However, the first statement
```
Math is good -8 and 7 are both not zero
```
would print if you used the logical operator&&because both-8and7aretrue.
|
To be more concrete, I have a C executable and I want to know in my bash script the execution time of a function from that C. I also want to know if I can find out what is the value of a certain variable from that file .
PS: I don't want to output on the console the things I need from the C file and then to read that output in the script
|
Short answer is no.
Longer answer is no, but have a look atprofilersto measure the execution time of a program (e.g.gprof) anddebuggersto inspect value of variables during runtime (e.g.gdb).
|
```
struct MemPidsData
{
int PID[7];
}
struct MemInfoData
{
int heater;
int pump;
int fan;
int temperature;
int valve;
}
#define MEMORY_NAME_INFO "InfoMem" /* Common Memmory */
#define MEMORY_SIZE_INFO sizeof(struct MemData)
#define MEMORY_SIZE_PIDS sizeof(struct MemData)
#define MEMORY_NAME_PIDS "CommonMem" /* Common Memmory */
```
I am getting an error that semicolon is missing on the line where struct MemInfoData is defined... Please help..
|
You actually havetwomissing semicolons - it should be:
```
struct MemPidsData
{
int PID[7];
}; // <<<
struct MemInfoData
{
int heater;
int pump;
int fan;
int temperature;
int valve;
}; // <<<
```
|
I have installed minGW, and I have a file "test.c".
I typedgcc test.c -o demoat the command prompt, while in the directory where I saved the "test.c" file. But it didn't work; I got this message:
gcc is not recognized as internal or external command, operable program or batch file
How do I make thegcccommand work on Windows with minGW?
|
You are missing onPath Variablesettings. Refer the 'Environment Settings' section on this page :
http://www.mingw.org/wiki/Getting_Started
|
I'm trying to make a function calculating x to the power n (where x could be a double, n must be anint). A recursive algorithm would bethis one, but implementing it in C gave me the stack-overflow error.
I tried finding my answer here, but the closest I found wasthis, which didn't satisfy my needs.
Here is my code:
```
double power_adapted(double x, int n) {
if (n == 0)
return 1;
else if (n == 1)
return x;
else if (n % 2 == 0)
return power_adapted(power_adapted(x, n / 2), 2);
else
return x * power_adapted(power_adapted(x, (n - 1) / 2), 2);
}
```
|
The recursive calls always pass 2 as n, so they will always trigger another recursive call.
I think you misinterpreted the formula. I would interpret it as:
```
else if (n % 2 == 0) {
double v = power_adapted(x, n / 2);
return v * v;
}
else {
double v = power_adapted(x, (n - 1) / 2);
return x * (v * v);
}
```
|
I help teach an intro to computer science course in a university, and the professor I help gives me tests before the students, to make sure that I don't think the questions are too hard or confusing. He gave me one problem with the following code:
```
#include<stdio.h>
#include<stdlib.h>
int main(){
int x = 5;
switch(x){
case 3: x += 1;
case 4: x += 2;
case 5: x += 3;
case 6: x++;
case 7: x += 2;
case 8: x--;
case 9: x++;
}
}
```
Now when I run it, I thought the output should be 10. However, when run, it outputs 11. I put print statements after each case, and the output looked like this:
```
8
9
11
10
11
11
```
So my question is, can someone explain this? I feel like it's some simple thing but I cannot figure it out for the life of me.
|
Theswitchstarts atcase 5and falls through (because the lack of thebreak-keyword) until the end. So: 5 + 3 + 1 + 2 - 1 + 1 = 11
|
I have a byte declared asunsigned int 0b11010101how can I write this to a binary file as 1 byte? I know fwrite takes typeconst void *as a buffer but I don't know how to write my byte if it's represented as an unsigned int.
|
Perhaps like this, you better not write one byte of anintbecause of endianness. Convert tounsigned charfirst.
```
unsigned int intval = 0b11010101; // assuming compiler likes it
unsigned char charval = intval;
fwrite (&charval, 1, 1, stream);
```
|
On thisbeginner tutorialat TutorialsPoint, it says to save the code as test.c and compile it using "$gcc test.c -o demo" command at CMD.
But I don't have $gcc. What is it?
|
Let's split this into parts:
$is a character indicating that the shell is ready to receive a command. It isnotpart of the command.gccis an executable executing the GNU C compiler from the GCC toolchain.test.c -o demoare arguments supplied togcc.
The GCC toolchain is only available natively for GNU systems such as Linux. UsingMinGWorCygWinyou can ape its functionality, though.
Notes:
A nice comment, which I second, to your question by @iharob:Don't usegcc test.c -o demospecially if you are a beginner, usegcc -Wall -Wextra -Werror test.c -o demo.The additional switches make the compiler point out more warnings.
|
```
#include "stdio.h"
#include "string.h"
int main(){
int counter;
char *token;
char s[]={"I am John"};
char con[256];
token = strtok(s," ");
while(token != NULL){
if (counter==0){
strcat(con,token);
token = strtok(NULL," ");
counter++;
}else{
strcat(con,token);
token = strtok(NULL," ");
strcat(con," ");
}
}
printf("%s\n",con);
return 0;
}`
```
printf()'s output is "I am John"
I would like the output to be "am John"
|
strcatexpects the first argument to be null-terminated, which isn't guaranteed by declaringcon, since its uninitialized. so the invocation ofstrcatisundefined behavior. Therefore your program is undefined behavior. Docon[0] = '\0';to resolve this issue.counteris uninitialized. Using it in an expression is undefined behavior too.
|
For instance I call the functionround()in C the manual says it returns a value of typedouble. I made anintvariable in which I'm storing the result of this function. Everything seems to work perfectly fine, so my question is what happened here?
```
int rounded = round(cents);
```
Why does C even allow me to store the returned value ofrounds()in a variable that is not of the same return type?
|
C will automatically attempt a conversion from the return value ofround(which is adouble) to anint.
Itmightget converted.
Bear in mind that if thedoublereturned is larger or smaller than that which can be held in anint, then the program behaviour is undefined.
You ought to compare withINT_MAXandINT_MINbefore attempting the conversion.
Hopefully you can see now whydoubleis, in fact, a sensible return type forround.
|
I am wondering whether it is safe to provide the same buffer as plaintext and ciphertext forcrypto_stream_salsa20_xor. I have tried to look into source files.crypto_stream_salsa20_xorusescrypto_core_salsa20, but this function appears only in a header file:
```
grep -r "int crypto_core_salsa" libsodium-1.0.5
libsodium-1.0.5/src/libsodium/include/sodium/crypto_core_salsa2012.h:int crypto_core_salsa2012(unsigned char *out, const unsigned char *in,
libsodium-1.0.5/src/libsodium/include/sodium/crypto_core_salsa208.h:int crypto_core_salsa208(unsigned char *out, const unsigned char *in,
libsodium-1.0.5/src/libsodium/include/sodium/crypto_core_salsa20.h:int crypto_core_salsa20(unsigned char *out, const unsigned char *in,
```
|
Yes, it is safe to do so. This also applies to other ciphers provided by the library. Input and output buffers can be identical.
|
I've looked at many of the questions asked here before, and I've decided to go withunistd.hforgetopt.
However I have a need that a certain option depends on a previous option, as in
```
exe -a a_opt -b b_bopt
```
where the-bwill dob_opt/a_opt
So it follows that-amust be parsed before-b.
Is there a way to implement this?
Thanks
EDIT: The simple way is to create a flag and check it at the end, however i'm trying to see if there is a more elegant solution.
|
No there's really no such way to enforce argument order using onlygetopt.
What youcando is to set a flag whengetoptreturns the-aoption to you, and check that flag when you get the-boption.
|
I am using ncurses and I want to know , is there anyway to control cursor movement , as in setting the leftmost , rightmost cell it can reach in a particular window .
For bottomost I am using scrollok() so that the text doesnt overflow , is there anyway for left and right ?
|
X/Open Curses (e.g., ncurses) provides two groups of functions for adding text to the screen:
those that wrap at the right marginthose that do not wrap at the right margin
addstr,addwstrand similar functions ultimately calladdchoradd_wch, respectively, whichwrap.
addchstr,add_wchstrand similar functions donotwrap. You probably want these.
|
I have to code my own shell in C, and I'm currently dealing with the> < >> <<operators. I handle the|(pipe) but i can't understand all the priority for splitting my line.
For something likels -la | cat -e ; psi'll do thels -la | cat -eand then theps, nothing difficult.
With the redirection< > << >>operators what is the order of precedence?
|
The shell handle the redirection operators in order of their appearance (or from beginning to the end of command, of from left to right).
This behavior wasspecified by POSIX:
If more than one redirection operator is specified with a command, the
order of evaluation is from beginning to end.
|
I have a problem regarding calling functions in C from main,I think I have this problem because I still don't get used to the procedural language but I can't figure this out at all.The error is "number undeclared(first use in this function)" and "number2 undeclared(first use in this function)".
Code:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int add(int number,int number2){
int answer;
answer = number + number2;
printf("Enter a number\n");
scanf("%d",&number);
printf("Enter another number\n");
scanf("%d",&number2);
printf("The result of those numbers are %d\n",answer);
}
int main()
{
add(number,number2);
return 0;
}
```
|
Change your main function to declare the variables there, like this:
```
int main()
{
int number = 1, number2 = 2;
add(number,number2);
return 0;
}
```
|
The following example shows how the c program can do the equivalent to the Lua code:
```
a = f(t)
```
Here it is in C:
```
lua_getglobal(L, "f"); // function to be called
lua_getglobal(L, "t"); // 1 argument
lua_call(L, 1, 1); // call "f" with 1 argument and 1 result
lua_setglobal(L, "a"); // set "a"
```
So, what is the equivalent C code of the following Lua code?
```
a = t + 1
```
Since we have no information aboutt, we should call the underlying+operator in c code, but HOW?
|
```
lua_getglobal(L, "t");
lua_pushinteger(L, 1);
lua_arith(L, LUA_OPADD);
lua_setglobal(L, "a");
```
|
When i studied about Linux interprocess Communications, i have known there were some method as: pipe, message queue, socket, signal, shared memory, semaphore and there is no method named Dbus.
But today, when i research about Dbus, i read that: "D-Bus is a system for interprocess communication (IPC)" (See that link:https://en.wikipedia.org/wiki/D-Bus)
So my question is:
What is the different between DBus and other IPC methods?
|
There is no technical, but historical difference.
D-Bus didn't used to be a Linux (i.e. kernel) IPC, but an additional middleware IPC. But in the course of introduction ofsystemd, D-Bus became for several Linux distributions a part of the basic system.
|
all,I want to implement array_map function using c language .
how can i do this?
```
void * x_array_map(void * func, Array * arr){
//TODO
}
```
Thx!
|
Here is some reference about function as parameter,
How do you pass a function as a parameter in C?
Here is my code:
```
#include <stdio.h>
#include <stdlib.h>
#define param_type int
// prototype
param_type* array_map (param_type (*f)(param_type), param_type* arr, int n);
// dummy function
int cube(int x) {
return x*x*x;
}
int main (){
int a[3] = {1, 2, 3};
int* b = array_map(cube, a, 3);
for (int i = 0; i < 3; ++i) {
printf("%d\n", b[i]);
}
return 0;
}
param_type* array_map (param_type (*f)(param_type), param_type* arr, int n) {
param_type* result = (param_type*) malloc(n*sizeof(param_type));
for (int i = 0; i < n; ++i)
result[i] = f(arr[i]);
return result;
}
```
|
I have astructI am making for a case to model a simple semaphore, the code is as follows
```
struct semaphore{
int count = 1;
struct PCB *Sem_Queue;
};
```
When I try to compile I get the error
Expected ':', ',' etc before '=' token int count = 1;
Can anyone point out to me why this error is occurring?
|
In C, you're not allowed to give initial values to elements instructs. If you'd like to create asemaphorestruct where every newsemaphore'scountfield is set to 1, you can do so by creating a helper function like
```
struct semaphore* semaphore_new()
```
that returns a newly-allocatedsemaphore*and sets thecountfield before returning it.
|
The following example shows how the c program can do the equivalent to the Lua code:
```
a = f(t)
```
Here it is in C:
```
lua_getglobal(L, "f"); // function to be called
lua_getglobal(L, "t"); // 1 argument
lua_call(L, 1, 1); // call "f" with 1 argument and 1 result
lua_setglobal(L, "a"); // set "a"
```
So, what is the equivalent C code of the following Lua code?
```
a = t + 1
```
Since we have no information aboutt, we should call the underlying+operator in c code, but HOW?
|
```
lua_getglobal(L, "t");
lua_pushinteger(L, 1);
lua_arith(L, LUA_OPADD);
lua_setglobal(L, "a");
```
|
When i studied about Linux interprocess Communications, i have known there were some method as: pipe, message queue, socket, signal, shared memory, semaphore and there is no method named Dbus.
But today, when i research about Dbus, i read that: "D-Bus is a system for interprocess communication (IPC)" (See that link:https://en.wikipedia.org/wiki/D-Bus)
So my question is:
What is the different between DBus and other IPC methods?
|
There is no technical, but historical difference.
D-Bus didn't used to be a Linux (i.e. kernel) IPC, but an additional middleware IPC. But in the course of introduction ofsystemd, D-Bus became for several Linux distributions a part of the basic system.
|
all,I want to implement array_map function using c language .
how can i do this?
```
void * x_array_map(void * func, Array * arr){
//TODO
}
```
Thx!
|
Here is some reference about function as parameter,
How do you pass a function as a parameter in C?
Here is my code:
```
#include <stdio.h>
#include <stdlib.h>
#define param_type int
// prototype
param_type* array_map (param_type (*f)(param_type), param_type* arr, int n);
// dummy function
int cube(int x) {
return x*x*x;
}
int main (){
int a[3] = {1, 2, 3};
int* b = array_map(cube, a, 3);
for (int i = 0; i < 3; ++i) {
printf("%d\n", b[i]);
}
return 0;
}
param_type* array_map (param_type (*f)(param_type), param_type* arr, int n) {
param_type* result = (param_type*) malloc(n*sizeof(param_type));
for (int i = 0; i < n; ++i)
result[i] = f(arr[i]);
return result;
}
```
|
I have astructI am making for a case to model a simple semaphore, the code is as follows
```
struct semaphore{
int count = 1;
struct PCB *Sem_Queue;
};
```
When I try to compile I get the error
Expected ':', ',' etc before '=' token int count = 1;
Can anyone point out to me why this error is occurring?
|
In C, you're not allowed to give initial values to elements instructs. If you'd like to create asemaphorestruct where every newsemaphore'scountfield is set to 1, you can do so by creating a helper function like
```
struct semaphore* semaphore_new()
```
that returns a newly-allocatedsemaphore*and sets thecountfield before returning it.
|
I have a struct
```
typedef struct a_struct{
int id;
rlnode anode;
}AS;
AS new;
AS old;
```
if I do this:new.anode = old.anodeisnew.idis going to have the same value withold.id?
rlnodeis a type ofnodenothing more.
thanks
|
In this statement
```
new.anode = old.anode;
```
data memberanodeof objectnewgets the value of data memberanodeof objectold.
If you want to assignoldtonewthen you should write
```
new = old;
```
In this case all data members ofoldwill be assigned to corresponding data members ofnew.
|
I am new to C and am having a problem reading this matrix declaration in a function.
void foo(int (*array)[][3], int row, int col)
and in the function how do I access an array element - say to print it's value.
|
```
int (*array)[][3]
```
declaresarrayto be a pointer to a 2D array whose second dimension is3. Example usage:
```
#include <stdio.h>
void foo(int (*array)[][3], int row, int col)
{
printf("%d\n", (*array)[row][col]);
}
int main()
{
int array[10][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
foo(&array, 2, 2);
return 0;
}
```
Output:
```
9
```
|
I've tried to invert an array element today and it didn't work. Is there a reason that e.g.
```
uint8_t array[2] = {0xFF,0x0A};
...
if( 0xF5 == ~(array[1]){
// never got here
}
```
Doesn't work? Compiler didn't show any errors.
|
C promotes integer types toint(or larger) when performing integer arithmetic. To get the value you desire, you can cast the result of the bitwise complement back down touint8_tbefore comparing, as follows:
```
if (0xF5 == (uint8_t) ~array[1]) {
...
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.