question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
This question already has answers here:Why do programs sometimes "skip over" printfs?(4 answers)Closed7 years ago.
This C program printsDone, then enters an infinite loop.
```
#include <stdio.h>
int main(int argc, char const *argv[])
{
printf("Done");
while (1) {}
return 0;
}
```
But when I run it, this code doesnotprintDone. Why is that?
|
It needs to flush the buffer. Usually console output doesn't flush until it receives a'\n'.
There's a little-used function for this,fflush().
```
#include <stdio.h>
int main(int argc, char const *argv[])
{
printf("Done");
fflush(stdout);
while (1) {}
return 0;
}
```
That should print for you.
|
Can you find the length of a string by doing subtraction on an array of pointers to strings?
For example if I have the code below
```
char *pStrings[4] = {
"First string",
"Hello",
"Afternoon",
"Ab"
};
int firstStrLen = pStrings[1] - pStrings[0] - 1; //Will I get the length of the first string by doing this?
```
WillfirstStrLenbe the length of the first string?
|
No, this is undefined behavior.
You are allowed to subtract pointers only when they are pointing to memory from the same contiguous memory block. In your examplepStrings[1]andpStrings[0]are not pointing to a contiguous block of memory, so the result ofpStrings[1] - pStrings[0]is undefined.
6.5.6.9: When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.
|
main.c
```
List L;
Initialize(&L);
printf("%d\n", Size(&L));
```
list.c
```
void Initialize (List *L) {
L = malloc(sizeof(List));
if (L == NULL) {
perror("Unable to create memory for list. Exiting.");
exit(1);
}
L->size = 0;
}
int Size (List *L) {
return L->size;
}
```
What I want outputted would be a size of '0', however what I am getting is the max int sizeof '2673724'. I am kind of confused at this point what is wrong with my code. Looking with gdb it looks like the Initialize() function is not actually modifying the List's size as it remains the same before and after entering the function.
Did I do something wrong?
|
ThisInitializefunction ignore the argument, allocate a buffer, write something to it, throw it away and cause memory leak.
Try this simple function using the same way asSize:
```
void Initialize (List *L) {
L->size = 0;
}
```
|
This question already has answers here:Why do programs sometimes "skip over" printfs?(4 answers)Closed7 years ago.
This C program printsDone, then enters an infinite loop.
```
#include <stdio.h>
int main(int argc, char const *argv[])
{
printf("Done");
while (1) {}
return 0;
}
```
But when I run it, this code doesnotprintDone. Why is that?
|
It needs to flush the buffer. Usually console output doesn't flush until it receives a'\n'.
There's a little-used function for this,fflush().
```
#include <stdio.h>
int main(int argc, char const *argv[])
{
printf("Done");
fflush(stdout);
while (1) {}
return 0;
}
```
That should print for you.
|
Can you find the length of a string by doing subtraction on an array of pointers to strings?
For example if I have the code below
```
char *pStrings[4] = {
"First string",
"Hello",
"Afternoon",
"Ab"
};
int firstStrLen = pStrings[1] - pStrings[0] - 1; //Will I get the length of the first string by doing this?
```
WillfirstStrLenbe the length of the first string?
|
No, this is undefined behavior.
You are allowed to subtract pointers only when they are pointing to memory from the same contiguous memory block. In your examplepStrings[1]andpStrings[0]are not pointing to a contiguous block of memory, so the result ofpStrings[1] - pStrings[0]is undefined.
6.5.6.9: When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.
|
This question already has answers here:Why do programs sometimes "skip over" printfs?(4 answers)Closed7 years ago.
This C program printsDone, then enters an infinite loop.
```
#include <stdio.h>
int main(int argc, char const *argv[])
{
printf("Done");
while (1) {}
return 0;
}
```
But when I run it, this code doesnotprintDone. Why is that?
|
It needs to flush the buffer. Usually console output doesn't flush until it receives a'\n'.
There's a little-used function for this,fflush().
```
#include <stdio.h>
int main(int argc, char const *argv[])
{
printf("Done");
fflush(stdout);
while (1) {}
return 0;
}
```
That should print for you.
|
Can you find the length of a string by doing subtraction on an array of pointers to strings?
For example if I have the code below
```
char *pStrings[4] = {
"First string",
"Hello",
"Afternoon",
"Ab"
};
int firstStrLen = pStrings[1] - pStrings[0] - 1; //Will I get the length of the first string by doing this?
```
WillfirstStrLenbe the length of the first string?
|
No, this is undefined behavior.
You are allowed to subtract pointers only when they are pointing to memory from the same contiguous memory block. In your examplepStrings[1]andpStrings[0]are not pointing to a contiguous block of memory, so the result ofpStrings[1] - pStrings[0]is undefined.
6.5.6.9: When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.
|
I'm a newbie to the go world, so maybe this is obvious.
I have a Go function which I'm exposing to C with thego build -buildmode=c-sharedand corresponding//export funcNamecomment.
(You can see it here:https://github.com/udl/bmatch/blob/master/ext/levenshtein.go#L42)
My conversion currently works like this:
```
func distance(s1in, s2in *C.char) int {
s1 := C.GoString(s1in)
s2 := C.GoString(s2in)
```
How would I handle UTF-8 input here?
I've seen there is a UTF-8 package but I don't quite get how it works.https://golang.org/pkg/unicode/utf8/
Thank you!
|
You don't need to do anything special. UTF-8 is Go's "native" character encoding, so you can use the functions from theutf8package you mentioned, e.g.utf8.RuneCountInStringto get the number of Unicode runes in a string. Keep in mind thatlen(s)will still return the number of bytes in the string.
Seethis post in the official blogorthis articlefor some details.
|
I am working with Mathworks Polyspace for my CODE analysis. I have a hardware register where I write a KEY+MODE and read the register to check the value in the register is equal to MODE.
The problem is, Polyspace considers this as 'always fail' as I am writing and reading different values in consecutive steps.
Is there any option in Polyspace to handle this issue.?
|
Since KEY+MODE is different from MODE, Polyspace will logically consider the testyour_hardware_register == MODEas failed (fortunatly).
It seems that KEY and MODE are bit flags for your register.
So I see two options:
Use the bitwise AND operator to test the register :if (your_hardware_register & MODE)make the register volatile (by adding the qualifier volatile to the declaration of your register) so Polyspace will consider that it can take any value (including MODE).
|
I'm chinese.I'm reading syslog.h,and i find a term "0-big number" which i can't understand.I can understand the hole paragraph meaning,but i'm still curious about the term "0-big number",could anybody explain the term?
```
/*
* priorities/facilities are encoded into a single 32-bit quantity, where the
* bottom 3 bits are the priority (0-7) and the top 28 bits are the facility
* (0-big number). Both the priorities and the facilities map roughly
* one-to-one to strings in the syslogd(8) source code. This mapping is
* included in this file.
/* facility codes */
#define LOG_KERN (0<<3) /* kernel messages */
#define LOG_USER (1<<3) /* random user-level messages */
....
*/
```
|
The author just decided to call 28 set bits (2^28 - 1) abig numberinstead of writing it out. So it's not a term but meanszerotobig number.
|
So My code runs differently when I have:
*ptr++;
and
++*ptr
I know the part about the ++ being in front you add first and when its in the back you add at the end. But this pointer increment is at the end of a method.
To clarify I'm just trying to move the pointer to the next character. This is a character type pointer.
|
*ptr++is processed as*(ptr++); it incrementsptrbut returns the original value, which is then dereferenced.
++*ptris processed as++(*ptr)which dereferences the pointer, then increments thevalue it points to(notthe pointer).
To preincrement the pointer, then get the value at the incremented location, you want*++ptr, which increments the pointer, then dereferences at the new location.
|
I'm curious why the following code returns negative numbers even though every single variable and fuction initialization in this program is an unsigned int. I thought they always were supposed to be positive?.
```
#include <stdio.h>
unsigned int main ()
{
unsigned int ch = 0;
unsigned int asteriskValue = 0;
while(ch!=27)
{
ch = getch();
if (ch == 224)
{
increaseDecrease(&asteriskValue);
}
printf("%d",asteriskValue);
}
}
void increaseDecrease(unsigned int *value)
{
unsigned int upOrDown;
upOrDown = getch ();
if(upOrDown == 72)
(*value)--;
else if(upOrDown == 80)
(*value)++;
}
```
|
I think your results is really a positive value, but printing it with a "%d" flag, tells printf to interpret it as a signed value, as if you were casting on the fly the type: (signed)asteriskValue
Try printing it with a "%u" formatting instead of "%d".
|
So My code runs differently when I have:
*ptr++;
and
++*ptr
I know the part about the ++ being in front you add first and when its in the back you add at the end. But this pointer increment is at the end of a method.
To clarify I'm just trying to move the pointer to the next character. This is a character type pointer.
|
*ptr++is processed as*(ptr++); it incrementsptrbut returns the original value, which is then dereferenced.
++*ptris processed as++(*ptr)which dereferences the pointer, then increments thevalue it points to(notthe pointer).
To preincrement the pointer, then get the value at the incremented location, you want*++ptr, which increments the pointer, then dereferences at the new location.
|
I'm curious why the following code returns negative numbers even though every single variable and fuction initialization in this program is an unsigned int. I thought they always were supposed to be positive?.
```
#include <stdio.h>
unsigned int main ()
{
unsigned int ch = 0;
unsigned int asteriskValue = 0;
while(ch!=27)
{
ch = getch();
if (ch == 224)
{
increaseDecrease(&asteriskValue);
}
printf("%d",asteriskValue);
}
}
void increaseDecrease(unsigned int *value)
{
unsigned int upOrDown;
upOrDown = getch ();
if(upOrDown == 72)
(*value)--;
else if(upOrDown == 80)
(*value)++;
}
```
|
I think your results is really a positive value, but printing it with a "%d" flag, tells printf to interpret it as a signed value, as if you were casting on the fly the type: (signed)asteriskValue
Try printing it with a "%u" formatting instead of "%d".
|
I want a code in one line only. I haven't found something usefull for the moment.
Exemple, I have:
```
#include <unistd.h>
int function(){write(1,"abcdefghijkmnopqrstuvwxyz\n",27);return(0);}
```
And I'm searching something like:
```
#include <unistd.h>;int function(){write(1,"abcdefghijkmnopqrstuvwxyz\n",27);return(0);}
```
|
You can't. The#includepreprocessing directive must be followed by a newline. It's part of the syntax (6.10.1 in the C standardhttp://open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf).
It's generally okay to omit headers from your one-liner, although even better to make the code compile without headers. If someone is going to plug your one-liner into a compiler, they'll know enough to fix a missing header or two.
|
I have an function address stored in anunsigned int, and a function pointer.
Now i want thatfunction_pointerwill contain the value offunction_address
```
unsigned int function_address = 0xdeadbeef;
void(*function_pointer)(void) = function_address; // not valid
```
how to do that in C ?
|
Perform an explicit cast.
```
void(*function_pointer)(void) = (void (*)(void))function_address;
```
|
I have an Xcode project for iOS in Xcode 7.0 that contains Objective-C, C++, and C code. Xcode tries to compile the C++ header files with the extension .h (not .hpp) as C header files which generates errors.
How do I fix this? There should be a setting for which files should be compiled as which language.
|
Individually header files doesn't compiled. Compiled source files where they included. If you include them in .c they will be compiled like C, if in .m - like Objective-c, if in .cpp - like C++, if in .mm - like Objective-C++.
It doesn't matter how you name them .h or .hpp.
If you have some portion of C++ code in h-file- you should put it in
```
#ifdef __cplusplus
#endif
```
If you have some portion of Objective-C code in h-file you should put it in
```
#ifdef __OBJC__
#endif
```
This will make code inside this statement invisible for other languages.
You can find this statement in Xcode's generated pch-file.
|
Is there any doc i can read about this kind of function?
```
// return the capital of char c
char a(char c){
return c >= 'a' && c<='z' ?
c +'A' - 'a':c;
}
```
|
Read up on the ternary operator. :) And then it will be clear the code is doing:
```
if (c >= 'a' && c<='z') {
return(c +'A' - 'a');
} else {
return c;
}
```
So basically it is capitalizing the Latin alphabet in ASCII.
|
This question already has answers here:Type of #define variables(7 answers)Closed7 years ago.
When I define a numerical constant with#define(e.g.#define pi 3.141593) is it anint,float,doubleor what?
|
Neither. It is a lexicographical replacement, that is, it will replacepiwith3.141593wherever it shows up.
|
I must start out by saying that I am extremely new to C!
I have been through theQuestions that may already have your answerand tried the suggestions however those do not solve the error message that I am receiving.
I am receiving an error message with the below code:
```
int autoop_check(aClient *cptr, aClient *sptr, aChannel *chptr, char *parv[])
{
if (IsOper(cptr))
char *parv[] = {
"+o",
sptr->name,
NULL
};
(void)do_mode(chptr, sptr, sptr, 2, parv, 0, 0);
}
```
Here is the error message:
```
module.c:32:9: error: expected expression before ‘char’
char *parv[] = {
^
```
|
You are missing braces for the body of theifstatement.
```
if (IsOper(cptr)) {
char *parv[] = {
"+o",
sptr->name,
NULL
};
(void)do_mode(chptr, sptr, sptr, 2, parv, 0, 0);
}
```
|
How can I check if my code is getting recompiled by GCC or not. For example if I type:
```
g++ -c test.cpp
```
is there a way that GCC tells you that the code is being recompiled in to a new object file because test.cpp has changed. I know I can check the object file's timestamp in terminal but is there an option in GCC which tells you that? Thanks.
|
gcc will always build if you tell it to build. Like robert said in the comments it is up to your build system to figure out if the file needs updating.
In make you could just print an info if your target is being hit or you could do a checksum (md5sum or so) of your binary the beginning and end of your build.
|
I want to store strings in a 2D array using pointers but I'm confused with how to do it. The examples I've seen use only arrays of ints or use the brackets[] to allocate a fixed size of memory. So I'm trying to initialize my 2D array of strings and this is what I have:
```
char ** stringArr = (char**)malloc(/*I don't know what goes here*/);
for(i = 0; i < rows; i++)
stringArr[i] = (char*)malloc(cols *sizeof(char));
```
As you can see the parameter for my first call of malloc, I am stuck as to what to put there if I want an exact x number of rows, where each row stores a string of chars. Any help would be appreciated!
|
Do this, because you're allocating some number of pointers:
```
malloc(rows * sizeof(char*))
```
|
I have an function address stored in anunsigned int, and a function pointer.
Now i want thatfunction_pointerwill contain the value offunction_address
```
unsigned int function_address = 0xdeadbeef;
void(*function_pointer)(void) = function_address; // not valid
```
how to do that in C ?
|
Perform an explicit cast.
```
void(*function_pointer)(void) = (void (*)(void))function_address;
```
|
I have an Xcode project for iOS in Xcode 7.0 that contains Objective-C, C++, and C code. Xcode tries to compile the C++ header files with the extension .h (not .hpp) as C header files which generates errors.
How do I fix this? There should be a setting for which files should be compiled as which language.
|
Individually header files doesn't compiled. Compiled source files where they included. If you include them in .c they will be compiled like C, if in .m - like Objective-c, if in .cpp - like C++, if in .mm - like Objective-C++.
It doesn't matter how you name them .h or .hpp.
If you have some portion of C++ code in h-file- you should put it in
```
#ifdef __cplusplus
#endif
```
If you have some portion of Objective-C code in h-file you should put it in
```
#ifdef __OBJC__
#endif
```
This will make code inside this statement invisible for other languages.
You can find this statement in Xcode's generated pch-file.
|
Is there any doc i can read about this kind of function?
```
// return the capital of char c
char a(char c){
return c >= 'a' && c<='z' ?
c +'A' - 'a':c;
}
```
|
Read up on the ternary operator. :) And then it will be clear the code is doing:
```
if (c >= 'a' && c<='z') {
return(c +'A' - 'a');
} else {
return c;
}
```
So basically it is capitalizing the Latin alphabet in ASCII.
|
I have this code:
```
#include <stdio.h>
#include <string.h>
int main() {
char s1[50], s2[50];
printf("write s1:\n");
fgets(s1, sizeof(s1), stdin);
printf("s2:\n");
fgets(s2, sizeof(s2), stdin);
printf("The concatenation of the two strings: %s\n", strcat(s1, s2));
if( strcmp(s2, s1) < 0 ) {
printf("s2 is shorter than s1.\n");
} else if( strcmp(s2, s1) > 0 ) {
printf("s2 is longer than s1.\n");
} else {
printf("strings are equal.\n");
}
return 0;
}
```
The problem is that when I write 2 same strings like abc or whatever, strcmp return "s2 is shorter than s1."
Is that the normal output or have I done anything wrong? If so, where?
Or strcat makes the string not equal? Can anything be done about this?
Thank you
|
You are doing
```
strcat(s1, s2)
```
before comparing. Which will modify strings1so strings will not be equal
|
I compiled and executed this code and the computer hangs. I sent the file(a.out not a.c) to a friend and he executed it and the result was same.
How do I intelligently check if there is such fork() in infinite loops? What should be the preventive measures against this attack?
```
#include<stdio.h>
int main(){
while(1)
fork();
}
```
|
Just use theulimitto limit the maximum number of processes. Additionally you can configure the limitations by editting the/etc/security/limits.conffile. Take a look to the following link which provides more information about how to prevent from this attack:
http://www.cyberciti.biz/tips/linux-limiting-user-process.html
|
I am trying to get the maximum virtual memory of the current process in Linux. And I am using getrlimit()
```
#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
struct rlimit rlim;
getrlimit(RLIMIT_AS,&rlim);
printf("Soft limit %ld",rlim.rlim_cur);
printf("Hard limit %ld",rlim.rlim_max);
```
I get -1 in both values. Shouldn't I expect the virtual memory max allowed for the current process ?
|
The valueRLIM_INFINITYdenotes no limit on a resource (both in the structure returned bygetrlimit()and in the structure passed tosetrlimit()).
These are the default values for a process. Check the value of this constant.
|
Do file descriptor are with respect to the processes or with respect to the operating system? What I basically want to know is if in a c program I open a file and that file gets assigned a file descriptor value lets say, 103, so when I open a file with file descriptor 103 in some other c program would I be referring to the same file or some other?
|
Each Process will be having its own file descriptor table. Its processor specific, if you change thefdit will be valid only to that process it wont affect the other processes in the system. once process is terminatedfdwill be discarded.
What if I fork a new process from the process I opened that file?
Current File description table i.e the table before fork system call will be inherited to the child process.
|
I'm just started learning C programming. So I have problem with change temperature via Functions. Please check this program and where did I do mistake? Thank you!!!
```
#include<stdio.h>
double f_to_c(double f);
double get_integer(void);
int main(void)
{
double a;
a = get_integer();
printf("he degree in C:%f", f_to_c(a));
return 0;
}
double get_integer(void)
{
double n;
printf("Enter the variable:");
scanf_s("%f", &n);
return n;
}
double f_to_c(double f)
{
int f, c;
c = 5.0 / 0.9*(f - 32.0);
return c;
}
`
```
|
In your case,
```
double f_to_c(double f)
{
int f, c;
c = 5.0 / 0.9*(f - 32.0);
return c;
}
```
int fis shadowing thedouble f. Use some other name for the variable(s).
Essentially, you're trying to make use of an uninitialized automatic local variable which invokesundefined behavior
|
Just curious, why below code is not equivalent to forever loop? Instead application crashes.
```
unsigned short i;
for (i = 1; i >= 0; i++)
{
printf("%d\n", i);
}
```
|
The problem is solved. Antivirus Karspersky was analysing this exe file for nearly 20 seconds it looks. If I disable antivirus, it runs immediately. Thanks for all your inputs.
|
Just curious, why below code is not equivalent to forever loop? Instead application crashes.
```
unsigned short i;
for (i = 1; i >= 0; i++)
{
printf("%d\n", i);
}
```
|
The problem is solved. Antivirus Karspersky was analysing this exe file for nearly 20 seconds it looks. If I disable antivirus, it runs immediately. Thanks for all your inputs.
|
I'm trying to call a function in main for the different programs (Q2-3 and Q4) but I'm getting an error during compiling. in my main I have
prog1 (); [it says "previous implicit declaration of prog1 was here"]
then there is a function of the same name at the very end
void prog1()
{ [it says "conflicting types for prog1"] and yes it just says it on a line where the only thing is {
the [] are just what I typed here not what is in my code. If you need more parts of my code let me know. My program is written in C not C++
|
Because you didn't give a prototype forprog1().
If it has for example the following signature
```
char *prog1(void);
```
and you don't give a prototype but call it frommain(), then you define it later with the mentioned signature, the implicitly declared prototype which isint prog1()conflicts with the definition.
Just add a prototype beforemain().
|
EXPLANATION:
simply trying to convert a a char to hexadecimal but i keep getting this error and I'm not sure how to get around this
PROBLEM:
```
warning: passing argument 1 of ‘strtol’ makes pointer from integer without a cast[cs214111@cs lab3]$ vi lab3.c
```
CODE:
```
void print_group(char array[])
{
int num,a;
char ch[10];
printf("here ");
for (a = 0 ; a < 8 ; a++)
{
strcpy(ch,array[3]);
num = strtol(ch,0,16);//------------------THIS IS IT//
printf("%i",num);
}
}
```
|
You are passingcharwherechar *is expected, maybe
```
strcpy(ch, &array[3]);
```
But from your code it would seem like this, is what you actually need
```
num = strtol(&array[3], 0, 16);
```
ifstrcpy()works in this case, then this will work.
|
Here is my code:
```
#include <stdio.h>
#include <math.h>
int main(void)
{
double x, y, z;
double numerator;
double denominator;
printf("This program will solve (x^2+y^2)/(x/y)^3\n");
printf("Enter the value for x:\n");
scanf("%lf", x);
printf("Enter the value for y:\n");
scanf("%lf", y);
numerator = sqrt(x) + sqrt(y);
denominator = pow((x/y),3);
z = (numerator/denominator);
printf("The solution is: %f\n", z);
return(0);
}
```
Can anyone give me a (hopefully) quick pointer to fix my infinite loop?
|
There's no loop in your function, so I think it's your calls toscanf()that are causing the error:
You need to pass reference toscanf(), i.e. usescanf("%lf",&x)instead ofscanf("%lf",x).
BTW, according to your fonction definition, you should usepow(x,2)instead ofsqrt(x)which returns the square root.
|
I am developing an R package with low-level C code. Suppose I have following function in myCcode.
```
SEXP myFun(SEXP obj)
```
I need to know whether the R objectobjis a regularmatrixorbig.matrix(use R packagebigmemory) so that I can call different functions for computation.
Is this possible? How could I know the class type ofobj?
|
You can use theinheritsfunction:
```
#include <R.h>
#include <Rinternals.h>
SEXP myFun(SEXP obj) {
if (inherits(obj, "big.memory")) {
// do stuff
}
}
```
|
My code is as follows to open a xterm terminal and run the ./paramax executable
```
#include <unistd.h>
#include <sys/ipc.h>
int main(int argc, char* argv[])
{
execl("/usr/bin/xterm", "/usr/bin/xterm", "-hold", "./paramax", (void*)NULL);
return 0;
}
```
Now the problem is for ./paramax I need to give a commandline argument for it to execute. How to proceed with this?
|
Runxterm -e ./paramax arg and more args, either directly or through an exec call.
|
I have a Linux kernel module which calculates network packet statistics among several CPUs (in kernel address space). Periodically I clear the corresponding memory chunk and strongly need this action to take immediate effect for all CPUs, otherwise it will distort the subsequent statistics values. My target CPU is a Power PC, so its cache coherency is very relaxed. Thus I need to manually flush data caches of all CPUs just after zeroing the memory.
So what should I place just after my clearing procedure:
```
memset(ptr, 0, size);
// what's going here?
```
|
After some reflection I realised that the problem here is not really linked to data cache flushing. Actually I try to avoid a banal race condition (the first cpu clears value while the second increments it). In my case it's too expensive to protect data by mutex, so it's worth using atomic flag to notify the owning CPU to clear the values by itself.
|
I have a loop in a C language code:
```
i = 0;
while(!isdigit(password[i]) && password[i++] != '\0');
```
password is declared globally like this:
```
char password[33];
```
iis an integer.
I want to check if the password a user is entering has at least one number or not.
If I replaced '\0' with any other character, say, 'p', it works iff p appears in the middle of the character array,
ex:
1.It works if:
```
password = bblahblah9**pa**
```
2.It doesn't work if:
```
password = blahblah9**p**
```
I guess, it is not scanning the end of the string correctly as the null character is always at the end it is being, I don't know, skipped or something.
|
The indexiis not incremented once you find a digit:
```
!isdigit(password[i]) && password[i++] != '\0'
```
ifisdigit(password[i])returnstruethe right side of&&operator is not evaluated.
|
Could someone help walk me through what some lines in this MIPs code are doing?
The C code isB[8] = A[i - j]with i = $s3, j = $s4, &A[] = $s6, and &B[] = $s7
The MIPs code is as follows...
```
sub $t0, $s3, $s4 # i - j
sll $t0, $t0, 2 #Gets the offset of 8 for B[]
add $t0, $s6, $t0 #Goes to the offset in B[] ?
lw $t1, 0($t0) #????
sw $t1, 32($s7) #????
```
I get a bit lost once it gets to the last 3 lines.
Why is it 0($t0) and 32($s7)? Or just why 0 and 32?
|
```
sll $t0, $t0, 2 // This multiplies (i-j) * 4, not 8. Because the indexes are 4-byte ints
add $t0, $s6, $t0 // $t0 = A + (i-j)*4. So $t0 = &A[i-j]
lw $t1, 0($t0) // $t1 = A[i-j]
sw $t1, 32($s7) // B[32/4] = $t1
```
32($s7) means $s7 + 32. The reason you add 32 because you are accessing the 8th element of an integer array, which is located in the memory address B + 8*sizeof(int) = B + 32
|
I'm trying to code a function that checks a through achar* a[], and often end up using something like
```
if(a[i] == 'x'){
i++;
//...
}
```
Now I would really like to change this toa[i++]instead, but it doesn't seem to work.
Question:
Am I doing something wrong here, or is there a clean alternative to avoid thei++?
Note: Currently 3 of my 13 rows in the function arei++, which makes it look significantly larger than it really is.
|
if (a[i++] == 'x')by itself is fine in C. It is, however, semantically different: Your original code only incrementsiif the condition is true, whereasif (a[i++] == 'x')always incrementsi.
|
I had written below code in C. I expected error message since array size cannot be allocated dynamically. But the code compiles. But the result size of myArray1 is absurd. I am not sure why it compiles. I am using codeblock and minGW.
```
int a;
printf("Enter the value for a\n");
scanf("%d",&a);
int myArray2[a];
printf("value of a = %d\tSize of myArray1 = %d",(sizeof(myArray2)/sizeof(myArray2[0])));
```
|
C99 standard supports variable sized arrays on the stack.
Here is thegcc docson it:
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.
|
Generally say I have some functionsstep1step2... and they are called successively:
```
int main()
{
...
step1(); // something wrong detected and need to break out of the whole program
step2();
step3();
...
}
```
How can I break out fromstep1and skip all the rest of code to terminatemain()function?
Currently I can only think of setting a global variable likebool isErras a flag so that
```
step1(); // error detected and isErr is set to 1 inside step1()
if (isErr)
return;
step2();
...
```
Are there better or more 'canonical' approaches?
BTW I've heard thatgotois bad so I discard it :)
|
Use
```
exit(1);
```
The number indicates the exit status. 0 is no failure, everything larger then 0 indicates an error.
|
I'm trying to code a function that checks a through achar* a[], and often end up using something like
```
if(a[i] == 'x'){
i++;
//...
}
```
Now I would really like to change this toa[i++]instead, but it doesn't seem to work.
Question:
Am I doing something wrong here, or is there a clean alternative to avoid thei++?
Note: Currently 3 of my 13 rows in the function arei++, which makes it look significantly larger than it really is.
|
if (a[i++] == 'x')by itself is fine in C. It is, however, semantically different: Your original code only incrementsiif the condition is true, whereasif (a[i++] == 'x')always incrementsi.
|
I had written below code in C. I expected error message since array size cannot be allocated dynamically. But the code compiles. But the result size of myArray1 is absurd. I am not sure why it compiles. I am using codeblock and minGW.
```
int a;
printf("Enter the value for a\n");
scanf("%d",&a);
int myArray2[a];
printf("value of a = %d\tSize of myArray1 = %d",(sizeof(myArray2)/sizeof(myArray2[0])));
```
|
C99 standard supports variable sized arrays on the stack.
Here is thegcc docson it:
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.
|
Generally say I have some functionsstep1step2... and they are called successively:
```
int main()
{
...
step1(); // something wrong detected and need to break out of the whole program
step2();
step3();
...
}
```
How can I break out fromstep1and skip all the rest of code to terminatemain()function?
Currently I can only think of setting a global variable likebool isErras a flag so that
```
step1(); // error detected and isErr is set to 1 inside step1()
if (isErr)
return;
step2();
...
```
Are there better or more 'canonical' approaches?
BTW I've heard thatgotois bad so I discard it :)
|
Use
```
exit(1);
```
The number indicates the exit status. 0 is no failure, everything larger then 0 indicates an error.
|
In the gcc compiler we can provide a macro to be used by the preprocessor inCusing -D flag (example-gcc -DN=10 test.c)
What is the flag that can be used to do the same in the clang compiler?
When I give the same -D option to the clang compiler on Windows, it gives an error:
"Directory not found."
|
Answer is the 2 comments from @cremno and @FUZxxl above.
The error wasn't coming from the clang compiler although it said clang error. Rather it was coming from the Windows cmd which looks for a directory after the '=' sign.
|
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.Closed7 years ago.Improve this question
When using C programming language, I have no idea how to put a user input to an array.
I need to get integers from the user in from of:
```
printf("Enter numbers. Separate each by a comma: ");
```
How can I put each number into an array?
|
This is a very helpful link
Also look up this too for clarification on Console.Read & Console.ReadlineDifference between Console.Read() and Console.ReadLine()?
|
The title says it all. The app I'm debugging has several diagnostics that callDebugger(). I want it to just print the message and continue execution.
|
Wow, this is cleverly hidden. Select the project in the project navigator. Then menu:
Product > Scheme > Edit Scheme...
Choose "Run" in the left column, then select the "Diagnostics" header on the top right.
At the bottom you'll see a checkbox for: "Legacy [ ] Stop on Debugger() and DebugStr()"
|
I wrote a C programm and saved it with a .c extension.
Then I compiled with the gcc but after that I only see my .c file and an .exe file. The program runs perfectly. But where is the .o file that I learned in theory? Has it been overwritten to .exe and all done by the gcc in on step? (Preprocessing, compiling, assembling and linking)
I'm on a VM running Debian.
|
By default,gcccompiles and links in one step. To get a.ofile, you need to compile without linking. That's done with the-coption.
Suppose you want to compile two files separately, then link them. You would do the following:
```
gcc -c file1.c # creates file1.o
gcc -c file2.c # creates file2.o
gcc -o myexe file1.o file2.o
```
If you want just the output of the preprocessor, use the-Eoption along with the-oto specify the output file:
```
gcc -E file1.c -o file1-pp.c # creates file1-pp.c
```
|
Why does the following snippet cause random numbers to print to the screen withprintf, butputcharalways outputs 1?
```
#include <stdio.h>
int main() {
char c;
printf("%d\n", c );
putchar(c);
}
```
|
According to C99 standard, this isundefined behavior. Let's see why:
Section 6.7.8.9 says that
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
This applies to your variablec, because it has automatic storage duration, and it is not initialized explicitly.
Section J.2 says that
The behavior is undefined in the following circumstances:...The value of an object with automatic storage duration is used while it isindeterminate
This applies to your code as well, because you readcwhen you pass it as a parameter to bothprintfandputchar, and the value ofcis still indeterminate, because it has not been assigned.
|
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.Closed7 years ago.Improve this question
When using C programming language, I have no idea how to put a user input to an array.
I need to get integers from the user in from of:
```
printf("Enter numbers. Separate each by a comma: ");
```
How can I put each number into an array?
|
This is a very helpful link
Also look up this too for clarification on Console.Read & Console.ReadlineDifference between Console.Read() and Console.ReadLine()?
|
The title says it all. The app I'm debugging has several diagnostics that callDebugger(). I want it to just print the message and continue execution.
|
Wow, this is cleverly hidden. Select the project in the project navigator. Then menu:
Product > Scheme > Edit Scheme...
Choose "Run" in the left column, then select the "Diagnostics" header on the top right.
At the bottom you'll see a checkbox for: "Legacy [ ] Stop on Debugger() and DebugStr()"
|
I wrote a C programm and saved it with a .c extension.
Then I compiled with the gcc but after that I only see my .c file and an .exe file. The program runs perfectly. But where is the .o file that I learned in theory? Has it been overwritten to .exe and all done by the gcc in on step? (Preprocessing, compiling, assembling and linking)
I'm on a VM running Debian.
|
By default,gcccompiles and links in one step. To get a.ofile, you need to compile without linking. That's done with the-coption.
Suppose you want to compile two files separately, then link them. You would do the following:
```
gcc -c file1.c # creates file1.o
gcc -c file2.c # creates file2.o
gcc -o myexe file1.o file2.o
```
If you want just the output of the preprocessor, use the-Eoption along with the-oto specify the output file:
```
gcc -E file1.c -o file1-pp.c # creates file1-pp.c
```
|
Why does the following snippet cause random numbers to print to the screen withprintf, butputcharalways outputs 1?
```
#include <stdio.h>
int main() {
char c;
printf("%d\n", c );
putchar(c);
}
```
|
According to C99 standard, this isundefined behavior. Let's see why:
Section 6.7.8.9 says that
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
This applies to your variablec, because it has automatic storage duration, and it is not initialized explicitly.
Section J.2 says that
The behavior is undefined in the following circumstances:...The value of an object with automatic storage duration is used while it isindeterminate
This applies to your code as well, because you readcwhen you pass it as a parameter to bothprintfandputchar, and the value ofcis still indeterminate, because it has not been assigned.
|
Is it possible to build a c (not cpp or visual cpp) application with visual studio? I do not want to only build it via cmd line but have some kind of project/solution within visual studio.
I've programmed in high-level languages like c#, java, python, etc etc but have no idea of c/cpp. I want to start learning c (again: not cpp/visual cpp). But I would prefer using visual studio since I'm pretty comfortable with it.
|
Yes, you can do that with MSVC. FromMSDNsite:
Give your files the.cextension, for examplemysource.c. The Visual C++ compiler automatically assumes that files with the.Cextension areCfiles and notC++files, and rejectsC++syntax and keywords (such aspublic,private, andclass).C++files use the.cppextension.See the/TC,/TPcompiler options for more information.
|
The title says it all. The app I'm debugging has several diagnostics that callDebugger(). I want it to just print the message and continue execution.
|
Wow, this is cleverly hidden. Select the project in the project navigator. Then menu:
Product > Scheme > Edit Scheme...
Choose "Run" in the left column, then select the "Diagnostics" header on the top right.
At the bottom you'll see a checkbox for: "Legacy [ ] Stop on Debugger() and DebugStr()"
|
I wrote a C programm and saved it with a .c extension.
Then I compiled with the gcc but after that I only see my .c file and an .exe file. The program runs perfectly. But where is the .o file that I learned in theory? Has it been overwritten to .exe and all done by the gcc in on step? (Preprocessing, compiling, assembling and linking)
I'm on a VM running Debian.
|
By default,gcccompiles and links in one step. To get a.ofile, you need to compile without linking. That's done with the-coption.
Suppose you want to compile two files separately, then link them. You would do the following:
```
gcc -c file1.c # creates file1.o
gcc -c file2.c # creates file2.o
gcc -o myexe file1.o file2.o
```
If you want just the output of the preprocessor, use the-Eoption along with the-oto specify the output file:
```
gcc -E file1.c -o file1-pp.c # creates file1-pp.c
```
|
Why does the following snippet cause random numbers to print to the screen withprintf, butputcharalways outputs 1?
```
#include <stdio.h>
int main() {
char c;
printf("%d\n", c );
putchar(c);
}
```
|
According to C99 standard, this isundefined behavior. Let's see why:
Section 6.7.8.9 says that
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
This applies to your variablec, because it has automatic storage duration, and it is not initialized explicitly.
Section J.2 says that
The behavior is undefined in the following circumstances:...The value of an object with automatic storage duration is used while it isindeterminate
This applies to your code as well, because you readcwhen you pass it as a parameter to bothprintfandputchar, and the value ofcis still indeterminate, because it has not been assigned.
|
Is it possible to build a c (not cpp or visual cpp) application with visual studio? I do not want to only build it via cmd line but have some kind of project/solution within visual studio.
I've programmed in high-level languages like c#, java, python, etc etc but have no idea of c/cpp. I want to start learning c (again: not cpp/visual cpp). But I would prefer using visual studio since I'm pretty comfortable with it.
|
Yes, you can do that with MSVC. FromMSDNsite:
Give your files the.cextension, for examplemysource.c. The Visual C++ compiler automatically assumes that files with the.Cextension areCfiles and notC++files, and rejectsC++syntax and keywords (such aspublic,private, andclass).C++files use the.cppextension.See the/TC,/TPcompiler options for more information.
|
What's wrong with this program. It compiles but is not giving correct output.
```
/* Program for Armstrong Number*/
#include<stdio.h>
#include<math.h>
void main()
{
int num,sum=0,temp,d;
printf("\n========Program for Armstrong Number=========\n");
printf("Enter the number : ");
scanf("%d",&num);
temp=num;
while(temp>10){
d=temp%10;
sum+=pow(d,3);
d/=10;
}
sum+=pow(temp,3);
if(sum==num)
printf("\nThe number %d is an Armstrong Number\n",num);
else
printf("\nThe number %d is not an armstrong number\n",num);
}
```
|
```
while(temp>10){
d=temp%10;
sum+=pow(d,3);
d/=10; // this should be temp/=10;
}
```
This loop is infinite as you don't modifytemp.
|
I downloaded Eclipse Mars although I have been doing most of my work on Android Studio. The reason is I need another tool, which is not compatible with Android Studio. The procedures I followed instructed to create an executable C project. I then added hello world to it, but I can an error stating there is nothing to build. What am I doing wrong? All of this is setup on Ubuntu Virtual Machine. I have reviewed the posts online, but the error seems to be specific to each case. Here is a screen capture...
|
Compiler is simply telling you that your code was already compiled and there are no changes in your code, then it does not compile.
Is a builtin feature of compilers, if there are no changes in source code file, compilers do not waste time.
Clean Projectbefore toBuild Projector modify Hello.c and Build your project.
|
I'm expanding circuit emulation engine for Win32 and want to add arm core support and integrate with systemC.I need some library that allows me to load binary file and execute it step by step. It shouldn't use any kernel drivers or hypervisor.The execution speed doesn't matter as it mostly will run step by step.back in the days there was a libqemu that allowed it. Moreover GDB support made it even better. But now it looks like it can work only as standalone emulator.
May be there are better way? I hope I posted it in the right forum
|
You should take a look at :https://hiventive.com
We're developing an open source solution that allow you to connect QEMU with SystemC exporting QEMU CPUs as a library with a TLM-2.0 like interface. A GDB server is also available.
There is a Raspberry Pi demo platform available through our beta.
|
In it's main page it says:
fchdir() is identical to chdir(); the only difference is that the
directory is given as an open file descriptor.
And the prototype is given as following:
int chdir(const char *path);int fchdir(int fd);
My question is how can a directory be passed as a file descriptor? Do directories also have a corresponding descriptor like files?
|
Do directories also have a corresponding descriptor like files?
Yes. The Unix philosophy(and Linux) is to treat everything as a stream of bytes. So yes, you can doopen(2)on a directory and get its file descriptor.
Not only directories but sockets, pipes and devices can also be opened usingopen(2)system call and do operations on it as though it's a file.
|
After I look around, I haven't find a built in function forUUIDcreation withinOSX kernel space. (which is limited toKernel.framework)
Are there any alternatives I could use? Or should I just use time hash (MD5/SHA1)?
|
These should help:
```
void uuid_generate(uuid_t out);
void uuid_generate_random(uuid_t out);
void uuid_generate_time(uuid_t out);
```
They're declared in<uuid/uuid.h>, and linkage is defined in Libkern.exports, i.e. your kext'sOSBundleLibrariesproperty must listcom.apple.kpi.libkern- which it probably already does.
|
In a (C++) class I took recently the teacher mentioned that using the->operator was a tiny bit slower than using dot notation and dereferencing your pointer manually (e.g.(*ptr)).
Is this true, and, if so, why?Does this apply to C as well?
|
The->operator is neither slower or faster than.operator. The fact is thatdereferencingsomething is slower than just access to a memory location, because there is one more indirection. And this is a fact of life, either in C and C++ and any other language.
In C++, you have alsoreferences, so you can dereference something using the.too! So the problem here is notarrow-vs-dot, the problem is if the compiler can go straight to a value or if it must search for its address before.
|
How can we do transaction signing in mozilla firefox by loading PKCS#11 library to database.
after some research i found about capicom library. but the thing is this library does not support with windows7 and higher versions.
|
you cannot use c code but you can do the same by java applets which are to be signed. Please referhttp://www.nakov.com/books/signatures/Java-for-Digitally-Signing-Documents-in-Web-book-Nakov.html
|
Can you please help to print the below pattern?
```
12345 15
2345 14
345 12
45 9
5 5
```
I have tried with this code?
code :
```
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(" ");
}
for(j=i;j<=5;j++)
{
printf("%i",j);
sum = sum + j;
}
printf(" ");
printf("%i",sum);
printf("\n");
}
```
output:
```
12345 15
2345 29
345 41
45 50
5 55
```
Please help to print the above pattern? Thanks in advance
|
Well the problem is clear: 29 = 15 + 14.
This means you are forgetting to clear sum when you begin a new line.
```
for(i=1;i<=5;i++)
{
sum = 0; // reset sum when we begin a new line
```
|
I am writing a C program in Linux and useforkto create a child process. When I run my program using./test 1 > out.txtboth the parent process and the child processes send information tostdout.
I would like the fileout.txtto only contain output from the parent process and discard all output from the child process.
How can I do that?
|
I would redirect the parent's stdout to the file, then when you fork, reopen the stdout handle of the child to go to something else (like /dev/null if you just want to ditch it, or you could open the terminal again if you want it to go back to stdout).
Thedup2system call can do that.opena new one,closethe old one, thendup2the new file descriptor to the old number (1 for stdout).
This is the process the shell itself uses to redirect to a file btw.
|
If I set the seed to 0 in C, I will get this sequence after callingrand()three times:
```
38, 7719, 21238, ...,
```
If I set seed to 1 (srand(1)) I will get this other sequence:
```
41, 18467, 6334, ...,
```
I know that is's very improbable, but will the sequence ofsrand(1)be present in the sequence ofsrand(0)at some point? I mean, usingsrand(0)will I get:
```
38, 7719, 21238, ..., ..., ..., 41, 18467, 6334, ...,?
```
Thanks!
|
Though it is not defined by standard - The answer to your question is yes, it depends upon the algorithm being used, which is usually Linear Congruential Generators (LCG). LCG is considered to be high on cross-autocorrelation. Looking at howrandis implemented in your platform will let you characterize it better. Here is an exampleRand Implementation
|
In C programming for Linux, I know thewait()function is used to wait for the child process to terminate, but are there some ways (or functions) for child processes to wait for parent process to terminate?
|
Linux has an extension (as in, non-POSIX functions) for this. Look upprctl("process-related control").
Withprctl, you can arrange for the child to get a signal when the parent dies. Look for thePR_SET_PDEATHSIGoperation code used withprctl.
For instance, if you set it to theSIGKILLsignal, it effectively gives us a way to have the children die when a parent dies. But of course, the signal can be something that the child can catch.
prctlcan do all kinds of other things. It's like anioctlwhose target is the process itself: a "process ioctl".
|
What happens in the follwing code, does program executes 'return 1' or exits before?
```
int cmd_quit(tok_t arg[]) {
printf("Bye\n");
exit(0);
return 1;
}
```
|
exit()ends the program, no matter what. So: no. In practice, a C runtime will always do something similar of
```
exit(main(argc, argv));
```
to execute your program.
(meaning:ifmain()returns,exit()will be called automatically with its return value)
|
Im creating a simple program in C that user insert a number, for example 5 and the program sums until 5, 0+1+2+3+4. Im using this formula
```
int sum_naturals(int n){
return (n-1)*n/2;
}
```
But now i want a formula that can sum from 2 different numbers, like user inserts number 5 and 9 and the program will do 5+6+7+8+9.
Can someone have ideia how can resolve this? Thanks
|
You can reuse your function
```
int sum(int a, int b) {
return sum_naturals(b) - sum_naturals(a-1)
}
```
Of course you have to add some validation.
|
I am using C API to create and drop tables from the oracle database. The snippet of code is
```
OCIStmt *stmt;
rc = OCIHandleAlloc(ora_env, (dvoid **)&stmt, OCI_HTYPE_STMT, 0, 0);
char *query = "DROP TABLE idmap_id;";
rc = OCIStmtPrepare(stmt, errhp, (OraText*)query, strlen(query), OCI_NTV_SYNTAX, OCI_DEFAULT);
rc = OCIStmtExecute(svchp, stmt, errhp, 1, 0, NULL, NULL, OCI_DEFAULT);
```
When I run this DROP TABLE query I get following error
```
OCIStmtExecute() ORA-00933: SQL command not properly ended
```
When I replace the query with CREATE TABLE like this
```
char *query = "CREATE TABLE idmap_id (id varchar2(32 CHAR) NOT NULL, CONSTRAINT idmap_id_pk PRIMARY KEY (id));";
```
I get error
```
OCIStmtExecute() ORA-00922: missing or invalid option
```
Can anyone please help me?
|
Remove the semi-colon.
(I guess Oracle expects another SQL statement after it.)
|
I need to use scanf to read a text file input into stdin. I want to read the text file line by line and then assign each values in the line to their values.
This is the text file38
5 35 3099 48 222 16 4 1 Ronaldo
2 33 2572 22 97 7 6 0 Neymar
1 38 3375 43 191 18 4 0 Messi
13 37 2472 22 80 1 6 0 Griezmann
The first line is the number of max games.
Then I want to read the next lines and assign it to the variables. Like number = 5, goals = 35, ....
Then on to the next line and read the same way. Number = 2, goals = 33, ....
How would I do this?
|
You can usefscanfto read from the text file (as you have fixed format of data) -
```
char name[100];
int a,b,c,d,e,f,g,h; // sorry for such variable names
while(fscanf(fp,"%d %d %d %d %d %d %d %d %99s",&a,&b,&c,&d,&e,&f,&g,&h,name)==9) // fp be file pointer
```
|
How do I get1.371429as01.37. Is it not%2.02f? I need to have a leading zero and also round it to two decimal places.
|
Try this:
```
#include<stdio.h>
int main()
{
double a = 1.2345666;
printf("%05.2lf\n", a);
return 0;
}
```
Here,05says "print 5 columns with leading zeros"..2says "print decimal digits untill 2 columns". 2 decimal digits + 1.+ 2 integer part => total 5 columns you have to print.
|
I'm trying to build my project and create an executable file in Eclipse using the Microsoft Visual C compiler. I get the following output in the Console:
```
12:02:42 **** Incremental Build of configuration Release for project ProjectName ****
make all
Building target: ProjectName.exe
Invoking: Linker (link)
link /nologo /OUT:"ProjectName.exe"
link: cannot create link `/OUT:ProjectName.exe' to `/nologo': No such file or directory
make: *** [ProjectName.exe] Error 1
```
I have been searching for a solution for hours, but no result. Any help would be really appreciated.
|
Switched to just using Visual Studio. Worked straight away.
|
In C programming for Linux, I know thewait()function is used to wait for the child process to terminate, but are there some ways (or functions) for child processes to wait for parent process to terminate?
|
Linux has an extension (as in, non-POSIX functions) for this. Look upprctl("process-related control").
Withprctl, you can arrange for the child to get a signal when the parent dies. Look for thePR_SET_PDEATHSIGoperation code used withprctl.
For instance, if you set it to theSIGKILLsignal, it effectively gives us a way to have the children die when a parent dies. But of course, the signal can be something that the child can catch.
prctlcan do all kinds of other things. It's like anioctlwhose target is the process itself: a "process ioctl".
|
What happens in the follwing code, does program executes 'return 1' or exits before?
```
int cmd_quit(tok_t arg[]) {
printf("Bye\n");
exit(0);
return 1;
}
```
|
exit()ends the program, no matter what. So: no. In practice, a C runtime will always do something similar of
```
exit(main(argc, argv));
```
to execute your program.
(meaning:ifmain()returns,exit()will be called automatically with its return value)
|
Im creating a simple program in C that user insert a number, for example 5 and the program sums until 5, 0+1+2+3+4. Im using this formula
```
int sum_naturals(int n){
return (n-1)*n/2;
}
```
But now i want a formula that can sum from 2 different numbers, like user inserts number 5 and 9 and the program will do 5+6+7+8+9.
Can someone have ideia how can resolve this? Thanks
|
You can reuse your function
```
int sum(int a, int b) {
return sum_naturals(b) - sum_naturals(a-1)
}
```
Of course you have to add some validation.
|
I am using C API to create and drop tables from the oracle database. The snippet of code is
```
OCIStmt *stmt;
rc = OCIHandleAlloc(ora_env, (dvoid **)&stmt, OCI_HTYPE_STMT, 0, 0);
char *query = "DROP TABLE idmap_id;";
rc = OCIStmtPrepare(stmt, errhp, (OraText*)query, strlen(query), OCI_NTV_SYNTAX, OCI_DEFAULT);
rc = OCIStmtExecute(svchp, stmt, errhp, 1, 0, NULL, NULL, OCI_DEFAULT);
```
When I run this DROP TABLE query I get following error
```
OCIStmtExecute() ORA-00933: SQL command not properly ended
```
When I replace the query with CREATE TABLE like this
```
char *query = "CREATE TABLE idmap_id (id varchar2(32 CHAR) NOT NULL, CONSTRAINT idmap_id_pk PRIMARY KEY (id));";
```
I get error
```
OCIStmtExecute() ORA-00922: missing or invalid option
```
Can anyone please help me?
|
Remove the semi-colon.
(I guess Oracle expects another SQL statement after it.)
|
I need to use scanf to read a text file input into stdin. I want to read the text file line by line and then assign each values in the line to their values.
This is the text file38
5 35 3099 48 222 16 4 1 Ronaldo
2 33 2572 22 97 7 6 0 Neymar
1 38 3375 43 191 18 4 0 Messi
13 37 2472 22 80 1 6 0 Griezmann
The first line is the number of max games.
Then I want to read the next lines and assign it to the variables. Like number = 5, goals = 35, ....
Then on to the next line and read the same way. Number = 2, goals = 33, ....
How would I do this?
|
You can usefscanfto read from the text file (as you have fixed format of data) -
```
char name[100];
int a,b,c,d,e,f,g,h; // sorry for such variable names
while(fscanf(fp,"%d %d %d %d %d %d %d %d %99s",&a,&b,&c,&d,&e,&f,&g,&h,name)==9) // fp be file pointer
```
|
How do I get1.371429as01.37. Is it not%2.02f? I need to have a leading zero and also round it to two decimal places.
|
Try this:
```
#include<stdio.h>
int main()
{
double a = 1.2345666;
printf("%05.2lf\n", a);
return 0;
}
```
Here,05says "print 5 columns with leading zeros"..2says "print decimal digits untill 2 columns". 2 decimal digits + 1.+ 2 integer part => total 5 columns you have to print.
|
I'm trying to build my project and create an executable file in Eclipse using the Microsoft Visual C compiler. I get the following output in the Console:
```
12:02:42 **** Incremental Build of configuration Release for project ProjectName ****
make all
Building target: ProjectName.exe
Invoking: Linker (link)
link /nologo /OUT:"ProjectName.exe"
link: cannot create link `/OUT:ProjectName.exe' to `/nologo': No such file or directory
make: *** [ProjectName.exe] Error 1
```
I have been searching for a solution for hours, but no result. Any help would be really appreciated.
|
Switched to just using Visual Studio. Worked straight away.
|
I recently came across the 'cmocka' mocking library for C. I was able to mock a single function and test the caller function successfully. Now i need it to use it for a project that i am working on, where it is required to mock a large number of functions. How to pass all the functions that I want to mock to the 'wrap' argument of Linker ? Is it possible to store the names of functions in a file, so that it could be picked up the linker ?
|
Invoke the compiler like this:
gcc -g -Wl,--wrap=something,--wrap=somethingElse code_new.c headers.c -l cmocka
|
So I've read a lot of similar posts but I can't nail down what my issue is here.
```
{
FILE * fp;
fp = fopen("integer_store.txt", "r");
int total;
int i;
clock_t start, end;
double time;
start = clock();
fscanf(fp, "%d", &i);
while(!feof(fp)) {
fscanf(fp, "%d", &i);
total = total + i;
}
end = clock();
time = ((double)(end-start)) / CLOCKS_PER_SEC;
printf("Total: %d\n",total);
printf("Execution time: %f seconds \n",time);
fclose(fp);
}
```
The goal is to print a total of all the numbers in a file of ASCII numbers separated by spaces... everything seems to work except every time I run it i get a different total for the same file.
|
Please initialize the variabletotallikeint total = 0;first.
Moreover, you should check iffopensucceeded (fpis notNULL).
|
I am new to C and programming. I am trying to print an array separated by comma. But don't wish to print the last comma element. Here is my code so far
```
void p_array(const int array[], const int s) {
for(int i = 0; i < s; i++) {
printf("%i, ",array[i]);
}
}
```
I am getting the array printed as
```
1, 2, 3, 4,
```
Whereas I dont wish to have the last element of comma printed. I know I am doing something fundamental wrong. Any help is appreciated.
```
1, 2, 3, 4
```
|
```
for(int i = 0; i < s; i++) {
if(i)
printf(", ");
printf("%i",array[i]);
}
```
|
I'm given a char* arguments. Which is basically a input stream that consists of "hex-address new_val" and I need to read both values as int*. I'm using sscanf() and reading hex-address just fine, but I can't figure out the way to advance to read new_val.No matter what I tried - I get segfault. Here is what I have so far:
```
int set_new_val(Cmd *cp, char *arguments) {
int* addr;
int* val;
sscanf(arguments, "%x",&addr);
sscanf(arguments+?????, "%x",&val);
/*see if I read it correct*/
printf("adr = %x || val = %x\n",(unsigned int)*addr,(unsigned int)*val);
/*not finished*/
return 0;
}
```
|
int addr, val; // not int*
sscanf(arguments, "%x %x",&addr, &val);
printf("adr = %x || val = %x\n", addr, val);
|
The purpose of this function is to be utilized for qsort function in the C library. The function below works only if the two sets have the same amount of elements. However, if one of the sets has less elements than the other set (and the values are continuously matching), my function seems to go into a segmentation fault. I believe the cause is that I'm recursively calling the next node when there might be a chance that the next node might be empty.
```
int cmp(const void *a, const void *b){
Node *pa = (Node*)a;
Node *pb = (Node*)b;
if (pa->val == pb->val)
cmp( pa->next, pb->next );
else if (pa->val < pb->val)
return -1;
else
return 1;
return 0; // placeholder
}
```
But I could be wrong, is the above function correct?
|
You are not at all checking if a node is NULL. You have to check it at the start of the function.
```
if(pa == NULL || pb == NULL)
return 0;
```
|
```
#include <stdio.h>
typedef struct hello{
int id;
}hello;
void modify(hello *t);
int main(int argc, char const *argv[])
{
hello t1;
modify(&t1);
printf("%d\n", t1.id);
return 0;
}
void modify(hello *t)
{
t = (hello*)malloc(sizeof(hello));
t->id = 100;
}
```
Why doesn't the program output100? Is it a problem withmalloc? I have no idea to initialize the struct.
How can I get desired output by editingmodifyonly?
|
```
void modify(hello *t)
{
t = (hello*)malloc(sizeof(hello));
t->id = 100;
}
```
should be
```
void modify(hello *t)
{
t->id = 100;
}
```
Memory is already statically allocated toh1again you are creating memory on heap and writing to it.
So the address passed to the function is overwritten bymalloc()The return address ofmalloc()is some memory on heap and not the address the objecth1is stored.
|
I tried the below code in both java and c++ , but it throwed an error in java while it does not throw an error in c++. Why is it so ?
```
while("abc"){ }
```
I do know it purely depends on the property of languages. But I would like to know why java set a condition that only boolean values should be allowed in loops ?
|
I believe you are talking about compiler error and not run-time
in case of java
```
while ( expression ) {
// expression must evaluate to boolean value true or false
// as far as I knwo "abc" is neither true or false when it comes to java hence error
}
```
in C
```
while ( expression ) {
// expression can be anything which finally gives a value of either 0 or a number
// "abc" in this case will evaluate to an address which is positive integer hence no error
}
```
|
am trying to pass along a "long long" number, the problem is when I try to divise this number by 10 , the answer is incorrect ..
```
#include <stdio.h>
int main(void)
{
int n = 0 ;
long long s = 4111111111111111;
n = s % 10 ;
printf("n after modulos %i\n",n );
s = s / 10 ;
printf("this is s after division %llo \n",s );
return 0;
}
```
Output :
```
n after modulos 1
this is s after division 13536350357330707
```
|
```
printf("this is s after division %llo \n",s );
^ (this prints (correct)value in octal representation)
```
Use specifier%lld(to get value in decimal ) .
|
So I've read a lot of similar posts but I can't nail down what my issue is here.
```
{
FILE * fp;
fp = fopen("integer_store.txt", "r");
int total;
int i;
clock_t start, end;
double time;
start = clock();
fscanf(fp, "%d", &i);
while(!feof(fp)) {
fscanf(fp, "%d", &i);
total = total + i;
}
end = clock();
time = ((double)(end-start)) / CLOCKS_PER_SEC;
printf("Total: %d\n",total);
printf("Execution time: %f seconds \n",time);
fclose(fp);
}
```
The goal is to print a total of all the numbers in a file of ASCII numbers separated by spaces... everything seems to work except every time I run it i get a different total for the same file.
|
Please initialize the variabletotallikeint total = 0;first.
Moreover, you should check iffopensucceeded (fpis notNULL).
|
This question already has answers here:srand(time(NULL)) doesn't change seed value quick enough [duplicate](6 answers)Closed8 years ago.
I am trying to generate two different random numbers in C within a given range.The range is
```
0 to nk-1
```
But my following code sometimes works and sometimes fails.What is the reason behind this?
```
n1=rand()%nk;
n2=rand()%nk;
while(n1==n2)
{
srand(time(0));
n2=rand()%nk;
}
```
|
You're supposed to seed the RNG once,
```
srand(time(0));
n1=rand()%nk;
n2=rand()%nk;
while(n1==n2)
{
n2=rand()%nk;
}
```
|
I have the following:
```
char rank[100][100];
int score = 5;
strcpy(rank[0], "%d" score);
```
However,strcpy()does not accept these arguments. Is there any way to append a formatted string into my array?
|
You could usesprintf:
```
char rank[100][100];
int score;
sprintf(rank[0], "%d", score);
```
Note however thatsnprintfis the buffer overflow-safe alternative.
|
I wrote this code in C to print nos from 1 to 10 in a txt file one by one but after the execution only first no is printed in the txt file. pls help
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i;
FILE *fptr;
fptr=fopen("C:\\program.txt","w");
for(i=1;i<=10;i++)
{
fprintf(fptr,"\n%d\n",i);
fclose(fptr);
}
}
```
|
Don't close the file until you finish writing to the file.
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i;
FILE *fptr;
fptr=fopen("C:\\program.txt","w");
for(i=1;i<=10;i++)
{
fprintf(fptr,"\n%d\n",i);
}
fclose(fptr);
}
```
|
I want to execute the following command
```
ubus -S call network.interface status '{"interface": "lan"}'
```
withexecvpin C:
```
char* arg[] = {"ubus", "-S", "call", "network.interface" , "status", "'{\"interface\": \"lan\"}'", NULL};
execvp(arg[0],arg);
```
but the command does not work. I make an investigation and I found tha t the cause is the 5th argument ('{"interface": "lan"}') contains a special charachter'which looks ignored byexecvp.
How to avoid this problem?
|
Wrong path .. the argument reads{"interface": "lan"},not'{"interface": "lan"}'. The quotes are just for your shell, so it knows the whitespace inside belongs to the argument instead of being the delimeter between two arguments.ubuswill never see them.
edit:better sayubusshouldnever see them, because in your implementation, it does, and that's just incorrect syntax toubus.
|
How do we round a floating point number in C/C++ to print exactly two digits after the decimal point rounded to the nearest decimal place?
say for example,when I use,
```
printf("%.2f", 12.555);
cout<<fixed<<setprecision(2)<<12.555<<endl;
```
I get,
```
12.55
12.55
```
but I need output as,
```
12.56
12.56
```
|
The problem is that the actual double value for 12.555 is
```
12.55499999999999971578290569595992565155029296875000
```
so when you round it to 2 decimal places it rounds down to 12.55. There's really nothing you can do about that.
|
This question already has answers here:What does ~0 do?(4 answers)Closed7 years ago.
Why doesprintf("%d", ~0);yield a value of-1? Shouldn't it be1since the~operator converts each 1-bit into a 0-bit and vice versa?
From what I understand is0000will be negated to1111.
|
~is a bitwise complement operator .00000000is flipped to11111111.
If you take2'scomplement of1(00000001)what you get is11111111which is to represent-1in binary.
Therefore the output is-1.
|
I'm trying to use x and y coordinates from mouse for a game, but i can not get the coordinates.
This is the event i've been reading:
```
typedef struct{
Uint8 type;
Uint8 button;
Uint8 state;
Uint16 x, y;
} SDL_MouseButtonEvent;
```
I need something like:
```
if(SDL_MouseButtonEvent.x >= 100)
{
//do something
}
```
I think the sintax is very different because i saw some examples using SDL_MOUSEBUTTONDOWN.
EDIT
I apologize, know this question might not be clear, but Peter's answer was just what I needed, thanks for your time.
|
A quick precision:event.mouse.xhas been replaced byevent.motion.xandevent.motion.xrelfor respectively absolute and relative mouse movement, bothint.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.