question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
```
# include<stdio.h>
int somthing(int);
int main()
{
int i=9;
somthing(i);
return 0;
}
int somthing(int i)
{
if(i == 0)
return 0;
else
printf("%d,", i);
somthing (i--);
}
```
I am not getting why compiler prints only9 9 9and then says time out that is its running infinitely.
I did post decreme... |
I did post decrement on i variable one less value should go into loop every time and it should print values from 9 to 0
what you are usingi--is post increment. It would send the value of i to thesomething()function and then decrement the value ofi. so, thesomthing()function always gets the value9. thus it goes to an ... |
I have the following code that I was to decompile:
```
movl $0x2feaf, -0x18(%ebp)
mov 0x8(%ebp), %eax
mov %eax, -0x14(%ebp)
```
my problem is, I don't understand what 0x8(%ebp) means in the context. I tried the following c code:
```
int b = 196271;
int a = b;
```
but that gives me
```
movl $0x2feaf, -0x8(%ebp)
... |
It means move whatever is at [EBP+8] into the EAX register.
In most contexts, [EBP+8] will be a parameter to the current function.
|
Does there exist an API for thexbacklightutility?
I'd like to make a graphical frontend in either C, C++, or Python, but I can't find any documentation.
My only guess at integration at this point would be making a call tosystem(), but I like to call libraries directly.
Doesxbacklighthave a library interface, or do ... |
The xbacklight source code can be foundhere.
It wouldn't be hard to modify the C source into an API for other languages.
|
I want to compare the second element of array against string to see if they match. I am trying to use memcmp to do this but it gives me an error. Is this the correct way of approaching this, or am I complete off? I'm sorry, I'm new to C.
```
char array[5][32] = {"foo","boo","moo"};
char string[32] = "boo";
int ret;
r... |
You can do this with the 'strcmp' function this way:
```
if ( strcmp( array[1], string ) == 0 ) {
printf("equal\n");
}
else {
printf("not equal\n");
}
```
|
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.Closed8 years ago.Improve this question
Can aMacrowith agotostatement and alabelbe defined?
|
A macro is a textual substitution taken care by the preprocessor so, yes you can. You can define a macro for a goto statement and/or a label.
Ps. anyway that's a terrible practice.. both using lots of macros and using gotos
```
#include <iostream>
#define GOTOSTMT goto helloworld;
#define LABELSTMT helloworld:
int... |
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.Closed8 years ago.Improve this question
These lines all print the correct entry out of the array, but each only prints 3 characters of each element... |
Use %c format specifier to print that...Remove & from printf...If you want to print the whole row of the array use only row index...
|
I made a program which print the sum of prime numbers which is below 4 million, it doesn't give me an output. When I count prime numbers below 1000 for instance it works well. So what's the problem with high iterations? Here is the function calculating the sum of the primes under a certain number.
```
long long is_pr... |
It doesn't make sense 'doesn't give me output', whether it produces error or it just executing for long time.
Your code's complexity is in O(n*n) that will take time for 4 million* 4 million iterations in worst case, this could be reason, wait for result.
|
I'm wondering how to declare, basically,(a const pointer to (a mutable pointer to (a const type)))in C99.
Let's say I have this call site:
```
const uint8_t* result;
create(&result);
```
Isvoid create(const uint8_t * const * resultPtr)the correct way to declare the callee in this case or does it mean something unin... |
Let's askcdecl:
```
$ cdecl declare p as const pointer to pointer to const char
const char ** const p
```
This declaration can be read entirely from right to left to obtain the English version (remembering thatconst charandchar constare the same).
|
Would this code work properly?
What is the difference between atomic_int vs _Atomic(int)
```
struct a {
int xyz;
volatile _Atomic(unsigned int) status;
int eee;
};
threadOne(void *)
{
a->status |= QW;
}
threadTwo(void *)
{
a->status |= ER;
}
```
|
Yes, it will work properly, i.e. the|=operations will be atomic
As far as where things are defined (this is more than you asked for):
_Atomicis defined by C11 (seehere)atomic_intis defined in C11 as a typedef to_Atomic int(seehere).std::atomic_intis defined in C++11 as a typedef to_Atomic int(seehere); on MS you mig... |
```
#include <stdio.h>
#include <string.h>
void main()
{
static int a=1;
++a;
printf("%d",a);
if(a<=3)
main();
printf("%d,a");
}
```
I could not understand why the o/p is : 234444 . Can any one explain ?
According to me , it should be 2344 as soon as a value reaches 4 , it should fail if condit... |
Something like this:
```
- main()
- ++a, now == 2
- print 2
- main()
- ++a, now == 3
- print 3
- main()
- ++a, now == 4
- don't call main
- print 4
- return
- print 4
- return
- print 4
- return
```
|
I have the following code that I was to decompile:
```
movl $0x2feaf, -0x18(%ebp)
mov 0x8(%ebp), %eax
mov %eax, -0x14(%ebp)
```
my problem is, I don't understand what 0x8(%ebp) means in the context. I tried the following c code:
```
int b = 196271;
int a = b;
```
but that gives me
```
movl $0x2feaf, -0x8(%ebp)
... |
It means move whatever is at [EBP+8] into the EAX register.
In most contexts, [EBP+8] will be a parameter to the current function.
|
Say, I have 2 functions like these-
```
char* f2(void){
char* str = malloc(100);
strcpy(str, "string1");
return str;
}
char* f1(void){
char* reply = malloc(150);
strcpy(reply, "string = ");
strcat(reply, f2());
return reply;
}
```
Which I call from main like so-
```
printf("reply = %s",... |
You have to free the return value off1(), too. Change
```
strcat(reply, f2());
```
to:
```
char *str = f2();
strcat(reply, str);
free(str);
```
|
Here's the code:
```
#include<stdio.h>
int main()
{
FILE *fp;
int i;
fp=fopen("DATA","w");
for(i=1;i<=30;++i)
putw(i,fp);
fclose(fp);
fp=fopen("DATA","r");
while((i=getw(fp))!=EOF)
printf("%4d",i);
fclose(fp);
return 0;
}
```
I don't get the expected output. The pr... |
ASCII 26 is theCtrl-Z (aka SUB) characterthat on some systems is used to indicate the end of file (normally only for text files). This is the reason your program stops reading the file as soon as it sees the value 26.
The reason this becomes an issue is that you're opening the file in text mode, yet are storing binar... |
Hi I am trying to convert this function from C which prompts the user for a first name and last name and returns the first and last names in the ouput parametes
```
//the C codes is this:
void getPatronName(char *fn, char *ln) {
printf("\n Enter patron name ([first] [last]): ");
scanf("%s %s", fn, ln);
}
... |
use the >> operator and change the pointers to references
```
void MenUI::getPatronName(string& fn, string& ln) {
cout<<endl<<" Enter patron name ([first] [last]: ";
cin>>fn>>ln;
}
```
|
I have just recently decided to learn C. I notice there is multiple compilers I can download. If I write C code for one compiler, it should work for all of the compilers, correct?
|
Short answer: yes
Long answer:
Yes, but only if (and not limited to):
Your code doesn't use compiler specific stuff that's not available on the other compilerThe libraries your code relies on are available and set up correctly on the other compilerYour code doesn't invoke/rely on undefined or implementation-defined... |
Hello I want to perform insertion sort using dynamic memory allocation.Here is my code and this code is giving me error that lvalue is required.Please help me.
```
int *cardSorter(int *arrayPointer,int size){
int j,i,key;
for(j=1;j<size;j++){
key=*(arrayPointer+j);
i=j-1;
while(i>=0||*... |
Just as stated in your comment,
```
//GIVING ERROR AT THIS LINE : lvalue requied
*(arrayPointer+i)+1=key;
```
It should be
```
*(arrayPointer+i+1) = key;
```
or, even easier to read,
```
arrayPointer[i+1] = key;
```
|
```
#include <stdio.h>
#include <math.h>
int main()
{
float n,f;
printf("n too:");
scanf("%f",&n);
f=sqrt(n);
f=n%f;
printf("%f",f);
return(0);
}
```
It iss my code. But i get this "Invalid operands to binary (have float and float)" error in 9th line.
How to solve this ?
|
Operands of%must be of integer type. You should use the library functionfmod.
C11: 7.12.10.1 The fmod functions
Synopsis#include <math.h>
double fmod(double x, double y);
float fmodf(float x, float y);
long double fmodl(long double x, long double y);DescriptionThefmodfunctions compute the floating-point remainder of... |
Considering a variablesTmpof(char *)defined withmalloc,
If I assign another variable to thissTmp, does the memory allocated via this variable get freed automatically or does that memory block remain allocated (& useless) until the process ends?
Let me explain with a code:
```
int main () {
char *sTmp = (char *)... |
Does “malloc”ed memory get freed implicitly?
No, there is no garbage collector mechanism in C.
You have to explicitlyfreethe memory you allocate withmalloc
```
sTmp = sNew;
```
This assignment statement causes a memory leak, free the object before the assignment.
|
What could be the simplest way to split strings in an array and put it to array of array of strings in C.
For example
```
["this is a test", "this is also a test"]
```
into
```
[["this", "is", "a", "test"], ["this", "is", "also", "a", "test"]]
```
|
Usestrtokfunction from the C library. The function splits a string into a serie of tokens.
http://man7.org/linux/man-pages/man3/strtok.3.html
|
On debugging the following two codes, first one shall print1 1and second one2 1, Can I please get explanation for this?
I do have moderate knowledge of pointers but I don't seem to understand this.
1.
```
void main()
{
int i = 257;
int *iPtr = &i;
printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );
}
... |
In little-endian systems, here are how are stored the values257and258in memory:
```
257 = 0x101
0x01 0x01 0x00 0x00
byte 0, byte 1, byte 2, byte 3
258 = 0x102
0x02 0x01 0x00 0x00
byte 0, byte 1, byte 2, byte 3
```
|
I have the following code inmain.c
```
#include "config.h"
#include "util.h"
```
and inconfig.h
```
#include "util.h"
```
and there is a normal function inutil.h
as I have include the util.h twice, I expect it should be wrong
but unfortunately, it goes damn well when I type:gcc main.c config.c util.c
why is thi... |
it should not cause an error
if you have next files:
inc.h, inc1.h and inc.h includes inc1.h and inc1.h includes inc.h, then it cause of error
in the header files made following agreement:
```
#ifndef HEADER_NAME_H
#defiene HEADER_NAME_H
//body of header file
#endif /*HEADER_NAME_H*/
```
w... |
I have code that looks something like this:
```
typedef struct
{
char mode; //e = encrypt, d = decrypt
char* infile; //name of infile
char* outfile; //name of outfile
char* password; //password string
} cipher_t;
int check_files(cipher_t *data)
{
char temp_path[] = "temp-XXXXX";
if( /** infi... |
data->infile = strdup(temp_path);
|
this one should be an easy one..
I have the following code in C:
```
#include <stdio.h>
#include <string.h>
main()
{
printf("Got to 1\n");
char *str;
*str='a';
printf("*str contains: %c",*str);
}
```
I don't get the line "Got to 1" printed before I see the Segmentation Fault (core dumped) error.
Coul... |
You have to allocate memory where you are going to store a character. The code can look like
```
char *str = malloc( sizeof( char ) );
*str='a';
printf("*str contains: %c\n",*str);
free( str );
```
Or you could write
```
char c;
char *str = &c;
*str='a';
printf("*str contains: %c\n",*str);
```
Also there is no nee... |
I am trying to implement 'whereis' command in C. But I was able to implement it partially. When I ever I try 'whereis' in Linux shell, lets say for e.g. whereis ls .. I get the following results
```
$ whereis ls
/bin/ls
/usr/share/man/man1p/ls.1p.gz
/usr/share/man/man1/ls.1.gz
```
I am able to get the first path us... |
On Linux (but not on all systems, e.g. Mac OS),whereissearches in$MANPATH(or some other default places) for matching files, which for ls are something like this:
```
$MANPATH/man(.+)/ls\.\1(\.gz)?
```
If you really need to know howwhereisworks, you can simply look at its source....
|
C11 has some things as part of the spec like byte and vec3_t.
Is there a way to determine via an#ifdefif those are already defined as too support as many compilers as possible without warnings?
|
You are misinterpreting the error message. These types are not defined by C11, but it seems that they are already defined in your include files somewhere else. What the message is refering to is that since C11typedefs can be re-iterated, if they refer to the same type. This is made so to have the same behavior as for ... |
Whenever I need to assign to a string and I have some word (calledvariedinput) that is assigned via standard input, socket, etc, I do something like
```
char buffer[50];
strcpy(buffer, "The ");
strcat(buffer, variedinput);
strcat(buffer, " jumped over the fence.");
```
Is there some other function that allows me to ... |
Yes, it is calledspnrintf. I your code:
```
snprintf(buffer, sizeof buffer, "The %s jumped over the fence", variedinput);
```
The rules for the format string and later arguments are the same as forprintf. Of course, you must make surevariedinputactually points to a string in this example.
|
I was wondering whether there is a way besides using arrays, arrayLists, linkedLists in C to reverse some user input.
For example, if the user enters a certain amount of numbers, and ends their entry with a 10, can these numbers be reversed using recursion rather than multi-element data structures?
For example,
4
5... |
```
#include <stdio.h>
void rec_f(void){
int n;
scanf("%d", &n);
if(n != 10){
rec_f();
printf("%d ", n);
}
}
int main(){
rec_f();
return 0;
}
```
|
So I get that the first for loop runs O(n) times, then inside that it runs 3 times, then 3 times again. How do I express this at big O notation though? Then do the 2 print statements matter? How do I add them to my big-o expression? Thanks, really confused and appreciate any help.
```
for (int x = 0; x < n; x++) {
... |
O(n)is linear time, so anyk * O(n)wherekis a constant (like in your example) is also linear time and is just expressed asO(n). Your example hasO(n)time complexity.
|
so I'm working on Euler's Phi function in C programming. Everything seems to be working perfect until I hit this snippet of code and it crashes.
```
while(a[i] != 0 || a[i]!= 1)
{
m=m*((a[i]-1)/a[i]);
i++;
}
```
Previous to this code the program, user enters a value and then t... |
```
a[i] != 0 || a[i] != 1
```
This is always true since a number cannot be both 0 and 1. You presumably encounter a zero divide condition whena[i]is zero.
I guess you meant to write
```
a[i] != 0 && a[i] != 1
```
But I cannot be sure of that since I cannot see the rest of your code. However, this change will avoi... |
I was trying to write my own strtok function.
```
char * toke(char * out, char * in, char * destr) {
int place = 0;
for(int i = 0; in[i] != '\0'; i++){
for(int d = 0; destr[d] != '\0'; d++){
if(in[i] == destr[d]){
printf("\nMatch.");
place = i;
... |
Your 'out' pointer is not initialized and this:
```
out[i] = in[i];
```
throws the exception
|
This question already has answers here:interview question printing a floating point number [duplicate](3 answers)Closed8 years ago.
Unexpected output while using %u specifier with float variable? my code is below please help me to understand?
```
int main()
{
float f=9.8;
printf("%u",f); //unexpected out put... |
Theuformat specifier meansunsigned int. Your call toprintfdoesn't know to convert yourfloatinto an unsigned int, soprintfjust reinterprets the bits of yourfloatas anunsigned int.
If you really do want to output it as an integer, you need to explicitly cast it:
```
printf("%u", (unsigned int) f);
```
Or if you mean... |
I have a function here
```
char ** makeArray(int count)
{
char **array[count];
return array[count];
}
```
that takes in the number of tokens from an array then returns an array with the correct size.
However for some reason it is changing count.
In my main function I use the function with this code:
``... |
I don't know what c compiler you are using, but that code won't compile in VC++. If you want to declare an array at compile time, your "count" variable must be a compile time constant.
How about this?
```
char ** makeArray(int count)
{
char** array = (char**)malloc(sizeof(char*)*count);
return array;
}
```
... |
Where do we usegetchar()instead ofscanf()orcin?
Also, shouldn't the syntax ofgetchar()bechar getchar()instead ofint getchar()? Since we are reading in character type input.
|
C and C++ are different languages;getcharexists in C whereascin(which inherently depends on classes) does not. Alsoscanfis very slow compared togetcharbecausescanfhas to read through a lot more data and do a lot more processing thangetchardoes.
Another reason for havinggetcharis that it is used in while loops like t... |
If my application dynamically allocates and frees memory numerous times, each time for objects of the same size; is it meaningful to wrap the malloc and the free with a cache of allocated memory for improving the performance? or do implementations of mallocs already do this?
|
The theboost::poolclass that can do it for you.
Another faster and easier way is to use an alternative malloc library fromTBB(tbbmalloc) orGoogle malloc(tcmalloc). Both are much faster than the default malloc and only require linking with a library so n code change is required.
I used tbbmalloc and gained a massive ... |
The below code works fine
```
void a()
{
printf("In fn");
}
#define a() printf("In macro")
void main()
{
a();
}
```
O/p In macro
But look at this code when macro is defined before the funcn definition.(Throws compilation error)
```
#define a() printf("In macro")
void a()
{
printf("In fn");
}
void ... |
In the first case the result is:
```
void a()
{
printf("In fn");
}
void main()
{
printf("In macro");
}
```
And in the second:
```
void printf("In macro")
{
printf("In fn");
}
void main()
{
printf("In macro");
}
```
Which is obviously not c code.
Defines are replaced before compilaton.
|
The following code outputs 14 using gcc. Why?
```
printf("%d", (int*)2+3); // This code is meant to be obfuscated!
```
|
int *casts2as an address. Adding3will add3*sizeof(int)to it. On your system it seems thasizeof(int)is equal to4and that's why it is giving2 + 12 = 14.
But, you should note that the given code invokesundefined behaviorfor two reasons:
Performing arithmetic on a pointer that doesn't point to an array element causes un... |
Since I don't know much(anything) , here probably everything's wrong, I'm just learning pointers
```
#include<stdio.h>
void fun(int,int);
void func(int*,int*);
int main()
{
int i=2,j=5;
void fun(i,j);
printf("\n%d %d\n",i,j);
void func(&i,&j);
printf("\n%d %d\n",i,j);
return 0;
}
void fun(i... |
When calling functions,you mustn't specify the return type before it. So remove thevoidbeforefunandfuncin themainfunction.
|
So I have a string passed into main function: int main(int argc, char* argv[])
I understand argc (which is 2 in this case), but don't understand how I can read argv[] character by character?
When I print argv[0] shouldn't that print the first character in the array of characters for that string?
Thanks
|
sample
```
#include <stdio.h>
int main(int argc, char *argv[]){
int i,j;
for(i=0; i<argc; ++i){
for(j=0; argv[i][j] != '\0'; ++j){
printf("(%c)", argv[i][j]);
}
printf("\n");
}
return 0;
}
```
|
I am using thejanssonJSON library for an application. I was reading theAPIand came across these functions:json_integer_value,json_real_valueandjson_number_value.
The first one returns the integer value stored in ajson_tobject if it isintegeror returns0on error. The other two is similar in the fact that ifjson_tis not... |
Use thejson_is_number,json_is_integerandjson_is_realmacros to check the type first.
|
I was trying to write my own strtok function.
```
char * toke(char * out, char * in, char * destr) {
int place = 0;
for(int i = 0; in[i] != '\0'; i++){
for(int d = 0; destr[d] != '\0'; d++){
if(in[i] == destr[d]){
printf("\nMatch.");
place = i;
... |
Your 'out' pointer is not initialized and this:
```
out[i] = in[i];
```
throws the exception
|
This question already has answers here:interview question printing a floating point number [duplicate](3 answers)Closed8 years ago.
Unexpected output while using %u specifier with float variable? my code is below please help me to understand?
```
int main()
{
float f=9.8;
printf("%u",f); //unexpected out put... |
Theuformat specifier meansunsigned int. Your call toprintfdoesn't know to convert yourfloatinto an unsigned int, soprintfjust reinterprets the bits of yourfloatas anunsigned int.
If you really do want to output it as an integer, you need to explicitly cast it:
```
printf("%u", (unsigned int) f);
```
Or if you mean... |
I have a function here
```
char ** makeArray(int count)
{
char **array[count];
return array[count];
}
```
that takes in the number of tokens from an array then returns an array with the correct size.
However for some reason it is changing count.
In my main function I use the function with this code:
``... |
I don't know what c compiler you are using, but that code won't compile in VC++. If you want to declare an array at compile time, your "count" variable must be a compile time constant.
How about this?
```
char ** makeArray(int count)
{
char** array = (char**)malloc(sizeof(char*)*count);
return array;
}
```
... |
Where do we usegetchar()instead ofscanf()orcin?
Also, shouldn't the syntax ofgetchar()bechar getchar()instead ofint getchar()? Since we are reading in character type input.
|
C and C++ are different languages;getcharexists in C whereascin(which inherently depends on classes) does not. Alsoscanfis very slow compared togetcharbecausescanfhas to read through a lot more data and do a lot more processing thangetchardoes.
Another reason for havinggetcharis that it is used in while loops like t... |
If my application dynamically allocates and frees memory numerous times, each time for objects of the same size; is it meaningful to wrap the malloc and the free with a cache of allocated memory for improving the performance? or do implementations of mallocs already do this?
|
The theboost::poolclass that can do it for you.
Another faster and easier way is to use an alternative malloc library fromTBB(tbbmalloc) orGoogle malloc(tcmalloc). Both are much faster than the default malloc and only require linking with a library so n code change is required.
I used tbbmalloc and gained a massive ... |
The below code works fine
```
void a()
{
printf("In fn");
}
#define a() printf("In macro")
void main()
{
a();
}
```
O/p In macro
But look at this code when macro is defined before the funcn definition.(Throws compilation error)
```
#define a() printf("In macro")
void a()
{
printf("In fn");
}
void ... |
In the first case the result is:
```
void a()
{
printf("In fn");
}
void main()
{
printf("In macro");
}
```
And in the second:
```
void printf("In macro")
{
printf("In fn");
}
void main()
{
printf("In macro");
}
```
Which is obviously not c code.
Defines are replaced before compilaton.
|
The following code outputs 14 using gcc. Why?
```
printf("%d", (int*)2+3); // This code is meant to be obfuscated!
```
|
int *casts2as an address. Adding3will add3*sizeof(int)to it. On your system it seems thasizeof(int)is equal to4and that's why it is giving2 + 12 = 14.
But, you should note that the given code invokesundefined behaviorfor two reasons:
Performing arithmetic on a pointer that doesn't point to an array element causes un... |
Since I don't know much(anything) , here probably everything's wrong, I'm just learning pointers
```
#include<stdio.h>
void fun(int,int);
void func(int*,int*);
int main()
{
int i=2,j=5;
void fun(i,j);
printf("\n%d %d\n",i,j);
void func(&i,&j);
printf("\n%d %d\n",i,j);
return 0;
}
void fun(i... |
When calling functions,you mustn't specify the return type before it. So remove thevoidbeforefunandfuncin themainfunction.
|
Good evening,
I am trying to write a suid-root binary in C and I have stumbled across the following problem:
I execute it as a non-privileged user user1 and I am able to use setuid/seteuid to change to any user id I want. The problem is that I can't do that with effective group ids.
Part of code:
```
if ( setegid(Va... |
The answer (thanks Ingo Leonhardt) is that you need to change the group id before the user id. It kind of makes sense now.. :)
|
when I am compiling this small program I am getting different values as output, instead of getting numbers from0 to 5. And the size of array is always8. The different values I am getting are:
```
-981774704
32767
0
0
4195728
0
```
Any tips would be really valuable. Thank you
```
#include <stdio.h>
int main() {
... |
You aren't assigning any values to the array, so you're getting the uninitialized values.
You need to do something likearray[0] = 5; //or some valueetc.
If you want an array of size 8, with the numbers indexing the array stored in it, so {0, 1, 2, 3, 4, 5, 6, 7}, you could do something like:
```
int array[8];
for(in... |
What is the right way to replace a white space with_in string passCode with 2 characters?
In the end it should input/output:(a )→(a_). Is there a way to do this using the isspace?
```
isspace(passCode[2]) == 0;
```
|
Check if the character is a space if yes, then replace it with_.
For example:
```
#include <stdio.h>
#include <ctype.h>
int main ()
{
int i=0;
unsigned char str[]="a ";
while (str[i])
{
if (isspace(str[i]))
str[i]='_';
i++;
}
printf("%s\n",str);
return 0;
}
```
|
I am writing a C program that use fgets to read in each line from a file. The problem is that if the file have a blank line, how to skip it to get the next line ? This is what I had try so far but it did not work.
```
char line[100];
FILE *filePtr = fopen(filename, "r");
while(fgets(line, sizeof(line), filePtr) !... |
Change
```
if (line != "\n")
```
into
```
if (line[0] != '\n')
```
|
Good evening,
I am trying to write a suid-root binary in C and I have stumbled across the following problem:
I execute it as a non-privileged user user1 and I am able to use setuid/seteuid to change to any user id I want. The problem is that I can't do that with effective group ids.
Part of code:
```
if ( setegid(Va... |
The answer (thanks Ingo Leonhardt) is that you need to change the group id before the user id. It kind of makes sense now.. :)
|
when I am compiling this small program I am getting different values as output, instead of getting numbers from0 to 5. And the size of array is always8. The different values I am getting are:
```
-981774704
32767
0
0
4195728
0
```
Any tips would be really valuable. Thank you
```
#include <stdio.h>
int main() {
... |
You aren't assigning any values to the array, so you're getting the uninitialized values.
You need to do something likearray[0] = 5; //or some valueetc.
If you want an array of size 8, with the numbers indexing the array stored in it, so {0, 1, 2, 3, 4, 5, 6, 7}, you could do something like:
```
int array[8];
for(in... |
What is the right way to replace a white space with_in string passCode with 2 characters?
In the end it should input/output:(a )→(a_). Is there a way to do this using the isspace?
```
isspace(passCode[2]) == 0;
```
|
Check if the character is a space if yes, then replace it with_.
For example:
```
#include <stdio.h>
#include <ctype.h>
int main ()
{
int i=0;
unsigned char str[]="a ";
while (str[i])
{
if (isspace(str[i]))
str[i]='_';
i++;
}
printf("%s\n",str);
return 0;
}
```
|
I am writing a C program that use fgets to read in each line from a file. The problem is that if the file have a blank line, how to skip it to get the next line ? This is what I had try so far but it did not work.
```
char line[100];
FILE *filePtr = fopen(filename, "r");
while(fgets(line, sizeof(line), filePtr) !... |
Change
```
if (line != "\n")
```
into
```
if (line[0] != '\n')
```
|
How can I set the socket buffer size for a UNIX socket file descriptor in C?
I understand setsockopt is probably the system call involved...
Can anyone give an example of how to use it, the one's I have found do not explain how to set the buffer size?
|
On Ubuntu 14.04 Linux check outman 7 socket, and specifically look atSO_RCVBUFandSO_SNDBUF.
|
Is there a way using the OpenLDAP API to set a particular network interface address to be used for socket bind on the LDAP client on a multi homed machine; like you do with the LDAP_OPT_SOCKET_BIND_ADDRESSES option with Microsoft's LDAP client.
|
You can do it by creating and binding and connecting the socket yourself and then calling ldap_init_fd() to turn it into an LDAP connection.
|
```
int i=40; //defined
int main()
{
do
{
printf("%d",i++);
}while(5,4,3,2,1,0); //what does this do ?
return 0;
}
**O/P=40**
```
I am unable to figure out what the while loop does in the above code.....
I know that do while loop execute atleast once.As theO/P=40condition of wh... |
The result of expression
```
5,4,3,2,1,0
```
is0. Sodo-whileis executed exactly one time.
SeeComma operator.
|
My program is below, this is for class.
My question is what should I be adding to my program to either stop or eliminate the '.' decimals
and zeros trailing after my answer is printed.
```
// Ch5Pgm7.cpp : Takes a number entered by the user and cubes it.
//Written by: Chris Howard Sept. 25th 2014.
#include "st... |
Use.and the number of decimal spaces you want.
```
printf("%.0lf\n", NUM);
```
|
```
int i=40; //defined
int main()
{
do
{
printf("%d",i++);
}while(5,4,3,2,1,0); //what does this do ?
return 0;
}
**O/P=40**
```
I am unable to figure out what the while loop does in the above code.....
I know that do while loop execute atleast once.As theO/P=40condition of wh... |
The result of expression
```
5,4,3,2,1,0
```
is0. Sodo-whileis executed exactly one time.
SeeComma operator.
|
My program is below, this is for class.
My question is what should I be adding to my program to either stop or eliminate the '.' decimals
and zeros trailing after my answer is printed.
```
// Ch5Pgm7.cpp : Takes a number entered by the user and cubes it.
//Written by: Chris Howard Sept. 25th 2014.
#include "st... |
Use.and the number of decimal spaces you want.
```
printf("%.0lf\n", NUM);
```
|
I'm developing in c, using visual studio 2013.
I wonder if there is a way in visual studio, or a plugin, that enable to refactor names of variable/functions ...
If not, Is there any other recommended IDE that enables refactoring with C?
Thanks.
|
Visual Assist(commercial) andVisual C++ Refactoring(free) extensions for VS 2013 support the rename refactoring for C.
|
I have to input a .in file into my program.gcc ./"file" < file.inBecause there are more than one input I have to use the While loop EOF, but
because of that I can't scanf again.
Here's a mock version of my program. Thank you
```
#include <stdio.h>
int main() {
int arr[100];
int num;
int count = 0;
wh... |
try this
```
freopen("con:", "r", stdin);//this for windows. "/dev/tty" for *nix ?
scanf("%d", &num);
```
|
I ran the following code segment in C:
```
printf("%%%\n");
```
I got the output "%" (without quotes). Can anyone explain what exactly happened?
Why we got only one % sign in result?
|
%%will print%.%\nis not a validconversion specifier.
You should always enable warnings. See the following:
```
warning: unknown conversion type character 0xa in format [-Wformat=]
printf("%\n");
^
```
As noted in the comments, this isundefined behaviorbecause according to theC11 standard, it i... |
I am trying to add tcpreplay library in C so that I can rewrite the data in the packet. I have been searching for a library in C programming. The result was to add TCPreplay and start using it's methods. Unfortunately it is not there for C language. If there is way to add the Tcpreplay to my program, let me know.
If... |
If you look at this branch:https://github.com/synfinatic/tcpreplayyou'll find my code to create a C library for tcpreplay & tcprewrite/etc. It's not complete, doesn't completely work and I have no intentions of completing it (I've since handed off Tcpreplay to Fred @ Appneta who is the new maintainer) but depending o... |
I am trying to write a binary representation of the integer into a file , accepted that I will get hexadecimal format in the file, however I don't get the expected result.
```
uint32_t a = 1;
FILE * file = fopen("out.txt", "ab+");
fwrite(&a, sizeof(uint32_t), 1, file );
```
I expect to get (little endian)
```
1000 ... |
Assuming each of those groups of two digits is a byte, what you're seeing is correct:
```
01 00 00 00
```
Little endian ordersbytes,not nybbleswithinbytes. So what you have is:
```
01 00 00 00
|| || || ||
|| || || == -> 0 * 256 * 256 * 256
|| || == ----> 0 * 256 * 256
|| == -------> 0 * 256
== ----------> 1
```
|
I have a code that needs to check if a given buffer of size 2048 is all zero. Right now I make a single traversal but wonder if there is a faster way to check if all contain 0. Is there a faster way? The cod e I have is as follows:
```
static int isSilent(Uint8* buf, int length){
int i;
for(i=0; i<lengt... |
No, generally speaking if you want to check something about a whole array, you have to check the whole array. If you know something about the array in advance then of course you may be able to optimize this.
|
Program only displaying the 32 for when I have it print "NewTemp"
NewTemp = 32 + input * 180/100; this part seems like the main problem
```
#include <stdio.h>
float celsius(float input) {
float NewTemp;
**NewTemp = 32 + input * 180/100;
printf("Please enter the temperature value to convert to fahrenhei... |
You do the math before you read the input. You need to do it the other way around.
Also, there's no reason to pass a meaningless and uninitialized value to thecelsiusfunction.
Lastly,180/100is 1 remainder 80 because when you divide two integers, you get integer division. You can use180.0/100.0.
Basically, you need ... |
How to generate random numbers with rand() and srand() without time.h in C ?
|
You could try givin another seed to the random generator like the program's pid.
```
srand(getpid());
int num = rand();
```
|
Is the following switch statement correct? I mean can i use constant and character literal in one switch case statement?
It works in code but I am asking from good practices standpoint.
```
switch(arg[1]) {
case '4':
printf("value is 4\n");
break;
case '6':
printf("value is 6\n");
... |
It works in code but I am asking from good practices standpoint.
Yes, it's fine to usecharvariables and constants inswitchstatements. It's very common to see that, for example,to process command line arguments.charis an integer type, andswitchworks as well withcharas with any other integer type.
|
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.Closed8 years ago.Improve this question
I have a list of arrays, each with its own descriptive name.
How can I create a pointer to a particular ar... |
If I understand correctly, what you mean and what you want, then you want something as Map, Dictionary etc. For example, look at this question:Quick Way to Implement Dictionary in C
|
Is it possible to create a pointer to a function pointer, i.e.
```
int32_t (*fp[2])(void) = {test_function1, test_function_2}; // initialize a function pointer
<unknown> = fp;
```
What needs to be written in place of unknown? With "normal" arrays, I could do this:
```
int a[2] = {0, 1};
int* p = a;
```
Many than... |
```
typedef void(*func_ptr_t)(void); // a function pointer
func_ptr_t* ptr_to_func_ptr; // a pointer to a function pointer - easy to read
func_ptr_t arr[2]; // an array of function pointers - easy to read
void(**func_ptr_ptr)(void); // a pointer to a function pointer - hard to read
void(*func_... |
Error after providing the input value of ID. But working when values directly assigned. Compiled Successfully.
```
#include<stdio.h>
#include <string.h>
typedef struct student
{
char name[20];
int id;
int mob;
} stu;
void printstudent(stu *stud);
void main()
{
stu s1;
strcpy(s1.name,"name");
pri... |
s1.idands1.mobare not pointers to the int, you should use&s1.idand&s1.mob
|
Incrementing an array result in lvalue required?my code is below please help me to understand
```
int main()
{
int a[]={10,20,30,40,50};
a=a+1 ;// i am increment an array address
a++ ;// but here its bad, here why lvalue required ?
}
```
|
Array names arenon-modifiable lvalues. You can't modify it. Thereforea = a + 1;anda++;both are wrong.
C11: 6.3.2.1:
A modifiable lvalue is an lvalue thatdoes not have array type, does not have an incomplete type,[...]
NOTE:
A modifiable l-value is addressable (can be the operand of unary &) and assignable (can be ... |
I have to use dlsym to load a function name from an external library.
But my concern is that he function is defined via a macro #define.
Assuming that dlopen call was successful, will dlsym find the correct symbol using the #defined name in this case?
The following is a header file which includes the #defined funct... |
Of coursedlsymcannotfind a#define-d symbol, since the C compiler is starting by its preprocessing phase which is expanding previously#define-d macros. So when the code using that name has been compiled, the preprocessed name is used (and only that name occurs in the shared object)
|
```
void local () {
int x = 100;
double *loc;
loc = (double *) malloc(sizeof(double)*100);
memset(rxnrun, 0x0, sizeof(double)*100);
// perform some operations
// free(loc);
return; // without doing free for loc variable
}
```
here, i can see what is wrong as memory leak is there forloc... |
Actually, both thexandlocvariables are local function variables, andboth variables are freedwhen the function returns.
However,locis a pointer and thememory the pointer points to is what is not freed. It's just the memory allocated bymalloc()that is not freed.
|
I am working on a project which needs to deal with large seismic data of SEGY format (from several GB to TB). This data represents the 3D underground structure.
Data structure is like:
```
1st tract, 2,3,5,3,5,....,6
2nd tract, 5,6,5,3,2,....,3
3rd tract, 7,4,5,3,1,....,8
...
```
What I want to ask is, in order to ... |
If you need to access itmultipletimes andif you need to access itrandomlyandif you need to access itfast
then load it to a databaseonce.
Do not reinvent the wheel.
|
I would like to know if it's possible to insert a global variable declaration with a gcc plugin. For example if I have the following code:
test.c:
```
int main(void) {
return 0;
}
```
and I want to transform it into:
```
int fake_var;
int main(void) {
return 0;
}
```
Is that possible?
If it's possible, in wh... |
I think you'll want to take a look at varpool_add_new_variable() in varpool.c. You should be able to pass a declaration built with type VAR_DECL to it. Similarly, take a look at add_new_static_var(), but I think the former is what you want, as it was added specifically to allow declaring globals in the middle/back end... |
I am trying to write an application inCwhich uses threads by usingthread.hdefined inC11specification.
I checkedhereandhereand both resources say that error status areunspecifiedor......
Please point me to a source which has this information.
|
That is exactly the point of having enumeration values for that purpose. You should never compare the return value to any literal number but to these constants.
```
int err = thrd_create(...);
if (err == thrd_error) {
// handle error here
}
```
|
I could not fully understand the consequences of what I read here:Casting an int pointer to a char ptr and vice versa
In short, would this work?
```
set4Bytes(unsigned char* buffer) {
const uint32_t MASK = 0xffffffff;
if ((uintmax_t)buffer % 4) {//misaligned
for (int i = 0; i < 4; i++) {
buffer[i] = ... |
This conversion is safe if you are filling same value in all4 bytes. Ifbyte ordermatters then this conversion is not safe.
Because when you use integer to fill4 Bytesat a time it will fill4 Bytesbut order depends on theendianness.
|
```
for (int i = 0; i< n; i++)
arr[arr[i]%k] += k;
```
I'm new to programming and I came across this piece of codehere. Can anyone explain what it does?
|
Translate to:
```
for (int i = 0; i< n; i++) {
int temp1 = arr[i];
int temp2 = temp1%k;
int temp3 = arr[temp2];
arr[temp2] = temp3+k;
}
```
Edit: thanks for the correction @R Sahu
|
Does K&R 2nd edition explain the usage of typedefs to make declaration and use of function pointers easier? I lost my copy and can't recollect of it does or it does not.
Thanks.
|
Yes, this is explained in section 6.7, "Typedefs".
|
I found that thevoid mainisn't correct but even when I change it tointor erase it,
I'm not getting what I'm supposed to which is the value for X given the values for A and B for the equation ax+b=0 and all I get are zeroes.
How can i fix this ?
```
void main()
{
float a,b,x=0;
printf("\n Write the values fo... |
Your use of the format specifiers to readaandbseem strange. Not sure whether you meant to have those&in there. Checkout the details of the valid format specifiers athttp://en.cppreference.com/w/cpp/io/c/fscanf.
Try:
```
scanf("%f%f",&a,&b);
```
&is not a format specifier. When you use
```
scanf("&%F&%F",&a,&b);
``... |
Just wondering if the operator "^" in C can be represented with shifts or subtraction/addition of signed integers.
|
```
A B A^B A+B
0 0 0 00
0 1 1 01
1 0 1 01
1 1 0 10
```
so Xor, can be looked as addition's first bit only (no carry out)
let's implement that :
```
unsigned char a, b;
unsigned char c, answer =0;
int i;
for (i=0; i<8; i++)
{
c = (a>>i)+(b>>i); // bit ny bit starting from... |
I've been searching for a couple of days and I can't seem to find information on how to do this in C with fnmatch.
I'm trying to make a pattern that matches: xxxx00_xxx (x being any char, 00 being any number except 02).
So far all I've got is:????[0-9][!2]_???The problem, as you can see, is that it's excluding any n... |
To solve this problem withfnmatchpatterns, you need two separate patterns, for instance:
```
????[!0]?_???
????0[!2]_???
```
I chose these to avoid the possibility of any string matching both patterns, so if you're making a list of matches (e.g. using theglobfunction) you should be able to just concatenate your list... |
In many solutions on codechef for faster input output I came across this expression but I am unable to understand it as I do not have a lot of experience.
```
inline int scan( ) {
int n=0;
int ch=getchar_unlocked();
while( ch <48 )ch=getchar_unlocked();
while( ch >47 )
n = (n<<3)+(n<<1) + ch-'0', ch=getchar_unlo... |
<<is shift left operator, that's easy to find in any C tutorials. Just google for C operator list and see.
```
(n << 3) + (n << 1) = n*8 + n*2 = n*10
```
That's an old optimization trick but probably won't be as effective as before in modern architectures with fast multipliers
|
When defining a max integer variable I get an error:
overflow in expression; result is 2147483647 with type 'int' [-Winteger-overflow]
line in the code:
const int MAXINT = (1 << (8*sizeof(int)-1))-1;
used language: C
cpu: 64bit (code maybe written in 32bit machine)
please, what should to do?
|
Overflow potentially occurs here
```
(1 << (8*sizeof(int)-1))
```
Rather than subtract 1 (after overflow occurred):
```
const int MAXINT = ((1 << (8*sizeof(int)-2))-1)*2 + 1
```
Note: better to useCHAR_BITthan8. But then that typically brings inINT_MAX(@Jonathan Leffler ) and code could use (@mafso)
```
const in... |
This question already has answers here:Pointer Arithmetic In C(2 answers)Closed8 years ago.
I'm not getting the output. Why it is happening?
```
#include <stdio.h>
int main(void){
int a[3][3];
int *p, *q;
p=a[0];
q=a[1];
printf("%d\n",sizeof(int));
printf("%d\n",q-p);
printf("%d %d\n",q,... |
I thought (q-p) should be 12
No.(q-p)==3shall hold true since they have typeint*. Meanwhile it's true thatq == p + 3.Also this is true:(char*)q - (char*)p == 12
|
My code is something like this:
```
#define ZERO_CONSTANT 0
foo(size_t * p_size);
foo(ZERO_CONSTANT); //Doesn't warn
```
Which gcc flag will make the callfoo(ZERO_CONSTANT)to warn?
|
No compilation flag can possibly help you here. The C standard defines the literal 0 to stand in for the null pointer value of any type. Quite often you'll see0,NULLand(void*)0.
(Note well that this doesnotimply that the memory address is 0. Because it'sundefined behaviourin general to assign an integral value to any... |
How would I go about writing a program in C that repeatedly prints out a string, but at different speeds. Basically, how to increase time between each return in a loop?
|
How would I go about writing a program in C that repeatedly prints out a string, but at different speeds.
You can merly increase a program's speed. But you can delay it more or less.
```
#include <stdio.h>
int main(void)
{
while (1)
{
printf("Hello World!\n");
<delay more or less here>
}
}
```
Under... |
I want to load a big array to GPU shared memory.
when I employ that just like bellow:
int index = threadidx.x;shared unsigned char x[1000];x[i] = array[i];
Then if we call a kernel code with 1000 threads and one block, for every thread a memory access will occur?
Is it possible to load this array by a single memory... |
No it can't be done with a single access.
Using threads in parallel to load shared memory, just as you have shown, is the fastest way. Shared memory canonlybe loaded by memory operations performed by threads in CUDA kernels. There are no API functions to load shared memory.
If you have an array that is larger than... |
when i trying to compile an old c source code using msys2 this error happens:
"configure: error: POSIX regex functions required and missing!"
Please any idea? Is that a library that can be added or it's an error related to the code itself?
|
It's not clear whether you want to build an MSYS2 or a native program. Anyway ..
MSYS2 has the following regex libraries. You can search for them yourself via:
```
pacman -Ss regular
```
From the mingw{32,64} (i.e. native) repositories:
```
mingw-w64-{x86_64,i686}-oniguruma
mingw-w64-{x86_64,i686}-pcre
```
From t... |
I am trying to port some simple digital IO code from a CCS compiler to XC8.
The MCU is PIC12F675.
XC8 does not have peripheral libraries for 12 series.
I have managed to configure it, set clock etc.
I can't seem to use pins 0-3 as digital IO by default.
I think it is because of the ADC configuration but it might ... |
I managed to do it, now it seems to work properly:
```
ANSEL = 0x00;
ADCON0 = 0x00;
CMCON = 0x07;
VRCON = 0x00;
TRISIO = 0x2F; //or whatever your config
GPIO = 0x00;
```
There was no need to set timers in order for digital GPIO to work.
|
I have the following code:
```
typedef enum MyEnum{
A = 0,
B,
C,
D
} MyEnumArray[] = {A, B, C, D};
```
VS 2008 gives me the error
C2513: 'MyEnum []' : no variable declared before '='
What is the correct way of declaring an array directly from atypedef enum?
|
In C++, just remove thetypedefand it would work fine.
In C also, removingtypedefis suffcient.However if you want to conveniently useMyEnuminstead ofenum MyEnumelsewherethen change a bit:
```
typedef enum {
...
} MyEnum;
MyEnum MyEnumArray[] = ...;
```
|
In the code below the result is stack overflow. Though null character is there with both the strings, so the strcpy loop should terminate as the source string has null character. Why stack overflow occurs??
```
#include <stdio.h>
#include<strings.h>
int main(void) {
char *str="Hello world";
char *str1="Good m... |
The error isn't stack overflow, but modifying a string literal.
stris a pointer that points to a string literal"Hello world", and modifying a string literal is undefined behavior.
Changestrto:
```
char str[100] = "Hello world";
```
|
I've been searching for a couple of days and I can't seem to find information on how to do this in C with fnmatch.
I'm trying to make a pattern that matches: xxxx00_xxx (x being any char, 00 being any number except 02).
So far all I've got is:????[0-9][!2]_???The problem, as you can see, is that it's excluding any n... |
To solve this problem withfnmatchpatterns, you need two separate patterns, for instance:
```
????[!0]?_???
????0[!2]_???
```
I chose these to avoid the possibility of any string matching both patterns, so if you're making a list of matches (e.g. using theglobfunction) you should be able to just concatenate your list... |
In many solutions on codechef for faster input output I came across this expression but I am unable to understand it as I do not have a lot of experience.
```
inline int scan( ) {
int n=0;
int ch=getchar_unlocked();
while( ch <48 )ch=getchar_unlocked();
while( ch >47 )
n = (n<<3)+(n<<1) + ch-'0', ch=getchar_unlo... |
<<is shift left operator, that's easy to find in any C tutorials. Just google for C operator list and see.
```
(n << 3) + (n << 1) = n*8 + n*2 = n*10
```
That's an old optimization trick but probably won't be as effective as before in modern architectures with fast multipliers
|
When defining a max integer variable I get an error:
overflow in expression; result is 2147483647 with type 'int' [-Winteger-overflow]
line in the code:
const int MAXINT = (1 << (8*sizeof(int)-1))-1;
used language: C
cpu: 64bit (code maybe written in 32bit machine)
please, what should to do?
|
Overflow potentially occurs here
```
(1 << (8*sizeof(int)-1))
```
Rather than subtract 1 (after overflow occurred):
```
const int MAXINT = ((1 << (8*sizeof(int)-2))-1)*2 + 1
```
Note: better to useCHAR_BITthan8. But then that typically brings inINT_MAX(@Jonathan Leffler ) and code could use (@mafso)
```
const in... |
This question already has answers here:Pointer Arithmetic In C(2 answers)Closed8 years ago.
I'm not getting the output. Why it is happening?
```
#include <stdio.h>
int main(void){
int a[3][3];
int *p, *q;
p=a[0];
q=a[1];
printf("%d\n",sizeof(int));
printf("%d\n",q-p);
printf("%d %d\n",q,... |
I thought (q-p) should be 12
No.(q-p)==3shall hold true since they have typeint*. Meanwhile it's true thatq == p + 3.Also this is true:(char*)q - (char*)p == 12
|
My code is something like this:
```
#define ZERO_CONSTANT 0
foo(size_t * p_size);
foo(ZERO_CONSTANT); //Doesn't warn
```
Which gcc flag will make the callfoo(ZERO_CONSTANT)to warn?
|
No compilation flag can possibly help you here. The C standard defines the literal 0 to stand in for the null pointer value of any type. Quite often you'll see0,NULLand(void*)0.
(Note well that this doesnotimply that the memory address is 0. Because it'sundefined behaviourin general to assign an integral value to any... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.