question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I want the address of the .text section of a position independent executable. Usingreadelf -S:
```
Name Type Address Offset
Size EntSize Flags Link Info Align
.text PROGBITS 0000000000002700 00002700
0000000000001672 0000000000000000 AX 0 0 16
```
I learn that it will begin 0x2700 bytes past where library was loaded into memory. But how can I get the load address of the executable?
Is there any other way to get the .text section address range during runtime (from the running program)?
|
Is there any other way to get the .text section address range during runtime (from the running program)?
Yes: you need to usedl_iterate_phdrand useinfo->dlpi_addrto locate thePIEbinary in memory at runtime. The very first call to yourcallbackwill be for the main executable.
|
This question already has answers here:Why don't I get a segmentation fault when I write beyond the end of an array?(4 answers)Closed7 years ago.
I've brushing up on my C coding and going over some old exercises I did a couple of years back. I came accros a situation I am almost 100% sure it should give a segmentation fault, but instead the program runs smoothly and terminates correctly. Why is that happening?
```
#include <stdio.h>
int main(void){
int vals[6] = {0,0,0,0,0,0};
vals[8]++; //This should not be ok!!?
printf("Done");
return 0;
}
```
|
The behaviour ofvals[8]isundefined.
It's equivalent to*(vals + 8)which isdereferencingmemory outside the bounds of the array.
A "segmentation fault" is one of many things that could happen. The compiler could also eat your cat.
|
I want to call a static function from another C file. But it always show"function" used but never defined.
In ble.c
```
static void bt_le_start_notification(void)
{
WPRINT_BT_APP_INFO(("bt_le_start_notification\n"));
}
```
In ble.h
```
static void bt_le_start_notification(void);
```
When I try to callbt_le_start_notificationinmain.c, it will show"bt_le_start_notification" used but never defined.
In main.c
```
#include "ble.h"
void application_start( void )
{
bt_le_start_notification();
}
```
Did I missing something ? Thanks in advance.
|
```
For restricting function access from other file, the keyword static is used
```
Access to static functions is restricted to the file except where they are declared.When we want to restrict access to functions from outer world, we have to make them static. If you want access functions from other file, then go for global function i.e non static functions.
|
So...it works for small numbers but if temp is bigger than 1000, it just print 0 or random number...
```
#include <stdio.h>
int main() {
int primes[10001];
primes[10000] = 0;
int i,temp;
int n = 2;
temp = 0;
while(temp<=1000){
for(i=2; i<n; i++){
if(n%i == 0){
goto Exit;
}
}primes[temp] = n; temp ++;
Exit:
n ++;
}
for(i=0; i<10001; i++){
printf("%d\n",primes[i]);
}
return 0;
}
```
|
The 1,000th prime is 7919.The 10,000th prime is 104,729.
On some systems, an int is 16 bits (65,535). This is big enough for 1,000 primes, but not for 10,000 primes. Try changing all your int variables to long variables.
|
I have failed to build a naive project using Visual Studio 2015.
It's a matter of environment which is still not fixed.
I am using Windows 10 Education, using Visual Studio Enterprise 2015.
Thank you so much for your help.
```
Error TRK0005 Failed to locate: "CL.exe". The system cannot find the file specified. myproj D:\Documents\XXX 1
```
|
Be sure to use theCustom Installrather thanTypical Installwhen installing Visual Studio 2015 if you want C/C++ tools.
As you have already installed it go to the control panel, selectPrograms and Features, select "Microsoft Visual Studio Education 2015", hit theChangeButton. When the Visual Studio dialog comes up, selectModify. Then select the checkbox next to "Common Tools for Visual C++ 2015" under Programming Languages -> Visual C++ and hitUpdate.
This requires administrator rights.
SeeVisual C++ Team Blogfor details.
|
This question already has answers here:Freeing global variable(2 answers)Closed7 years ago.
Say I declare a global arrayint arr[10];Should I free it somehow in the end?
|
You need not free it.You should usefree()only when you have usemalloc().
|
I want to call a static function from another C file. But it always show"function" used but never defined.
In ble.c
```
static void bt_le_start_notification(void)
{
WPRINT_BT_APP_INFO(("bt_le_start_notification\n"));
}
```
In ble.h
```
static void bt_le_start_notification(void);
```
When I try to callbt_le_start_notificationinmain.c, it will show"bt_le_start_notification" used but never defined.
In main.c
```
#include "ble.h"
void application_start( void )
{
bt_le_start_notification();
}
```
Did I missing something ? Thanks in advance.
|
```
For restricting function access from other file, the keyword static is used
```
Access to static functions is restricted to the file except where they are declared.When we want to restrict access to functions from outer world, we have to make them static. If you want access functions from other file, then go for global function i.e non static functions.
|
So...it works for small numbers but if temp is bigger than 1000, it just print 0 or random number...
```
#include <stdio.h>
int main() {
int primes[10001];
primes[10000] = 0;
int i,temp;
int n = 2;
temp = 0;
while(temp<=1000){
for(i=2; i<n; i++){
if(n%i == 0){
goto Exit;
}
}primes[temp] = n; temp ++;
Exit:
n ++;
}
for(i=0; i<10001; i++){
printf("%d\n",primes[i]);
}
return 0;
}
```
|
The 1,000th prime is 7919.The 10,000th prime is 104,729.
On some systems, an int is 16 bits (65,535). This is big enough for 1,000 primes, but not for 10,000 primes. Try changing all your int variables to long variables.
|
I have failed to build a naive project using Visual Studio 2015.
It's a matter of environment which is still not fixed.
I am using Windows 10 Education, using Visual Studio Enterprise 2015.
Thank you so much for your help.
```
Error TRK0005 Failed to locate: "CL.exe". The system cannot find the file specified. myproj D:\Documents\XXX 1
```
|
Be sure to use theCustom Installrather thanTypical Installwhen installing Visual Studio 2015 if you want C/C++ tools.
As you have already installed it go to the control panel, selectPrograms and Features, select "Microsoft Visual Studio Education 2015", hit theChangeButton. When the Visual Studio dialog comes up, selectModify. Then select the checkbox next to "Common Tools for Visual C++ 2015" under Programming Languages -> Visual C++ and hitUpdate.
This requires administrator rights.
SeeVisual C++ Team Blogfor details.
|
This question already has answers here:Freeing global variable(2 answers)Closed7 years ago.
Say I declare a global arrayint arr[10];Should I free it somehow in the end?
|
You need not free it.You should usefree()only when you have usemalloc().
|
I want to send the Hex commands below over uart to hardware attached to my mcu. I want to put them into an array and write them all at once as opposed to one at a time.
```
0x56
0x36
0x01
```
How do you declare this array in native c? Is it an array of strings?
This is the function to send the data.
```
uart_write_buff(const uart_t uart, const uint8_t *const data,
uint32_t len);
```
|
Do it like this:
```
unsigned char data[] = { 0x56, 0x36, 0x01 };
```
It is an array of bytes.
Or better:
```
uint8_t data[] = { 0x56, 0x36, 0x01 };
```
|
```
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char aa[35];
int a;
scanf("%d",&a);
gets(aa);
puts(aa);
}
```
It is not taking string from user but if I take the string before the integer value it is working fine.
|
Oncescanf("%d",&a);takes numeric characters out ofstdinto form theintfora, it is done. It does not consume a'\n'that may follow it.
gets(aa);, consumes data until'\n'.
So input like123xyEnterto the below will put123intoaand"xy"intoaa.
```
scanf("%d",&a);
gets(aa);
```
Input like456Enterto the above will put456intoaand""intoaa.
Recommend usingfgets()and add error handling.
```
if (fgets(aa, sizeof aa, stdin) == NULL) Handle_EOF();
if (sscanf(aa, "%d", &a) != 1) Handle_Nonnumeric_Input();
if (fgets(aa, sizeof aa, stdin) == NULL) Handle_EOF();
aa[strcspn(aa, "\n")] = '\0'; // truncate potential \n
```
|
I am stuck on this basic question:
```
int x=1;
printf(~x|x) // -1
```
Shouldn't it be ~01|01 ~01 = 10 10|01 = 11 =3?
Ok, after reading all the response, my understanding is that1111=-1on a twos compliment machine.
My follow up question is why is1111 =-1and not 15?
Thanks
|
In C, operator~(bitwise NOT) has a higher precedence than|(Bitwise OR).
Whensizeof (int) == 4:
```
x = 00000000 00000000 00000000 00000001
~x = 11111111 11111111 11111111 11111110
~x|x = 11111111 11111111 11111111 11111111
```
For two's complement,11111111 11111111 11111111 11111111is just-1.
To answer your follow up question, you can run this code and see the result:
```
unsigned int x = 1;
printf("%u", ~x|x);
```
|
In C, how can I produce an error if no arguments are given on the command line? I'm not usingint main(int argc , * char[] argv). my main has no input so I'm getting my variable usingscanf("%d", input)
|
Your question is inconsistent: if you want to get arguments from the command line, you must definemainwithargcandargv.
Your prototype formainis incorrect, it should be:
```
int main(int argc, char *argv[])
```
If the program is run without any command line arguments,arcwill have the value1. You can test it this way:
```
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("error: missing command line arguments\n");
return 1;
}
...
}
```
If you definemainwithint main(void)you have no portable access to command line arguments. Reading standard input has nothing to do with command line arguments.
|
I am stuck on this basic question:
```
int x=1;
printf(~x|x) // -1
```
Shouldn't it be ~01|01 ~01 = 10 10|01 = 11 =3?
Ok, after reading all the response, my understanding is that1111=-1on a twos compliment machine.
My follow up question is why is1111 =-1and not 15?
Thanks
|
In C, operator~(bitwise NOT) has a higher precedence than|(Bitwise OR).
Whensizeof (int) == 4:
```
x = 00000000 00000000 00000000 00000001
~x = 11111111 11111111 11111111 11111110
~x|x = 11111111 11111111 11111111 11111111
```
For two's complement,11111111 11111111 11111111 11111111is just-1.
To answer your follow up question, you can run this code and see the result:
```
unsigned int x = 1;
printf("%u", ~x|x);
```
|
In C, how can I produce an error if no arguments are given on the command line? I'm not usingint main(int argc , * char[] argv). my main has no input so I'm getting my variable usingscanf("%d", input)
|
Your question is inconsistent: if you want to get arguments from the command line, you must definemainwithargcandargv.
Your prototype formainis incorrect, it should be:
```
int main(int argc, char *argv[])
```
If the program is run without any command line arguments,arcwill have the value1. You can test it this way:
```
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("error: missing command line arguments\n");
return 1;
}
...
}
```
If you definemainwithint main(void)you have no portable access to command line arguments. Reading standard input has nothing to do with command line arguments.
|
why this code is showing value of a = 1120403456 (may be garbage) in Dev-C++.
```
#include<stdio.h>
int main()
{
int a=5;
float * pf;
pf=(float *)&a;
*pf=100.0;
printf("%d",a);
return 0;
}
```
|
The floating point number 100.0 is represented as 0x42C80000 in memory, which in decimal is 1120403456. You're printing out the 32-bit integer representation of 100.0.
|
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
In c what does this do after gets
```
int c;
while ((c = getchar()) != EOF && c != '\n');
```
I saw that many of you are telling me its while loop and all, why so much complication to it? Why cant we just use this code which I have given below?
```
gets(name);
if(name == '\n'|| name == EOF)
gets(name);`
```
|
First of, thegetsfunction is not really secure and you might want to usefgetsinstead.
Anyway, your piece of code is used toclear the buffer. When you read from the user input, all the things that the user will type is going to be stored in abuffer, and then the program will read from it. That why sometimes you need to clear the buffer so you don't read other things that you didn't want.
|
I have automated a batch file through load runner script which writes the data in a notepad file.
Now I want to pass that written data in another load runner script as a parameter.
The data written from batch file looks like this:
```
USING API KEY : Android
Base URL = /user/authorization
HEADERS :
accessKey = 45k907its35dooeo182dm0guy8k0dv8o
signature = Tdo0ZBfZazTvYd8UwmHT+haq2vM=
timestamp = 1455397355435enter
```
But when I want to read and pass the parameter in another script I just want to pass theaccess key.
How do I capture only access key from the batch file output
|
Like this :
```
@Echo off
for /f "tokens=1,2 delims==" %%a in (data.txt) do If /i "%%a"=="accessKey " set "$Key=%%b"
Echo KEY ==^> [%$Key: =%]
```
|
I'm using the pcap C library to read packets. Currently, I use the following to check and see whether a flag in thestruct tcphdr(this struct is defined in thenetinet/tcp.hlibrary) is set:
```
struct tcphdr *tcp = ....
if(tcp->th_flags & TH_SYN) {
//SYN FLAG IS SET?
}
```
Will this always work for checking if a particular flag is set in the struct? Or is there a better way? Would greatly appreciate any advice/tips :)
|
That looks fine to me.TH_SYNis a single bit, so that expression will be true (nonzero) if that bit is set inth_flags.
|
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
In c what does this do after gets
```
int c;
while ((c = getchar()) != EOF && c != '\n');
```
I saw that many of you are telling me its while loop and all, why so much complication to it? Why cant we just use this code which I have given below?
```
gets(name);
if(name == '\n'|| name == EOF)
gets(name);`
```
|
First of, thegetsfunction is not really secure and you might want to usefgetsinstead.
Anyway, your piece of code is used toclear the buffer. When you read from the user input, all the things that the user will type is going to be stored in abuffer, and then the program will read from it. That why sometimes you need to clear the buffer so you don't read other things that you didn't want.
|
This question already has answers here:Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?(19 answers)Closed7 years ago.
If I want to change the pointed value without changing the pointer's address, what should I do?
In 3,*d=*bwill return segmentation fault in running time. I think it is because the*dis not pointed to any memory space. This also explains why 2, works. However, for 1,*aand*bpointed to memory with same size, why it will return segmentation fault here?
```
void main(void){
char *a="abcd";
char *b="1234";
char *c=(char *)malloc(sizeof(char));
char *d;
*a=*b; //1.segmentation fault
*c=*b; //2.ok
*d=*b; //3.segmentation fault
}
```
|
Constant strings are usually stored in read only memory and you can't modify them.
To make them writable create a copy first:
```
char *a = strdup("abcd");
```
|
```
for (day = 1; day <= 31; day++)
{
printf("%2d", day);
if ((day + 1) % 7 > 0)
printf(" ");
else
printf("\n ");
}
```
When run this, I found that in each line, there will be one space.
How can I delete it?
Output of my code:
```
S M Tu W Th F S
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
```
|
Well, changeprintf ("\n ");toprintf ("\n");as mentioned in Aleksandar's comment.
Basically, in your case, you are going to a new line, and then printing a space. But your purpose is just to go to a new line. So you remove the space.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed7 years ago.Improve this question
I need to hold a value of range 10^20 inC. Heard that the big int inCcan hold such big values. How to declare and use the big int inC.
Does anybody know of an easy way to do that? Any help would really be appreciated!
|
You can use typeunsigned long long, the range is at least0..18446744073709551615, but that's only 1.8E19, so slightly less than what you need. If you really want to go beyond 64 bits, you can check if your system supports 128 bit integers (as type__int128,__int128_t,int128_tor something similar) or you will need a multi-precision package such as GMP.
|
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
i have seen some code where programmers include a for loop inside a for loop.for example
```
for(i=0; i<n; i++){
for(j=0;j<n;j++)
```
Why is this important?
Please tell me when do I need to include this nested loop in my code.
|
You dont use nested loops because they are important. You use it because the program requires it. Try to understand the logic of the program you are referring. Then you will understand why they are used. You can read about nested loopshere.
|
I want to get the following variable names in the array:
```
part1, part2, part3, part4...
```
Here are excerpts from the program code:
```
#define argument(x) #x
for (i=0; i<10; i++)
names[i]=strcat("part", argument(i));
```
As I think, after pre-processing I get instead of#var-"var".
But instead that i getsigmentation fault.
How to solve this problem. Maybe there are other methods?
|
Try this as recommended:
```
char names[10][100];
for (int i = 0; i < 10; i++)
{
snprintf(names[i], sizeof(names[i]), "part%d",i);
}
```
|
I was confused about how to useyylvaldefined in%union{}, whenyylvalis aint, I can use$1and$2reference to tokens, but with union type I don't know how to do. I got definition here:
```
%union {
int intval;
double floatval;
char *strval;
int subtok;
}
```
For example, I have a rule when yylval is string like this
```
line: SELECT items'\n' { printf("select item %s\n", $2); };
```
how to change it tostrvalinstead?
|
Either declare the type of each token when declaring the token...
```
%token <strval> items
```
Declare the type after declaring the token...
```
%type <strval> items
```
Or specify the type when grabbing the value...
```
$<strval>2
```
|
Reading a file, first number is anintthat's the size of the array, then the rest aredouble
Here is the function:
```
void read1dascii(double** a, int* m, char* infile)
{
FILE * fp = fopen(infile, "r");
fscanf(fp, "%d", m);
alloc1d(a, *m);
fscanf(fp, "%lf\n", *a);
fclose(fp);
}
```
Here is thealloc1dfunction it calls:
```
void alloc1d(double** a, int m)
{
*a = malloc(sizeof(double) * m);
}
```
I'm getting the first number which is the size and then the first number in array, but then the rest are reading in as zeros.
|
You need to read all of them using loop.
```
int i;
for (i = 0; i < *m; ++i) {
fscanf(fp, "%lf", *a + i);
}
```
|
How does the commandls -lcount the number of hard links of an inode?
Does it use the Linux API or is it code that requires deeper knowledge of the Linux kernel source code?
I am not, yet, able to understand the source code ofls, because I just started learning C.
|
It callsstatto get information about the file (in astruct stat). Then it looks at thest_nlinkfield of thestruct stat.
|
I installed the mingw stuff from yaourt on arch linux but when i type
```
x86_64-w64-mingw32-gcc tom.c ncurses_functions.c terminal_functions.c list_functions.c -o -lpdcurses tom_windows.exe
```
I get:
```
x86_64-w64-mingw32-gcc: error: tom_windows.exe: No such file or directory
```
It must be something simple but I don't know what!
|
Try:
```
x86_64-w64-mingw32-gcc tom.c ncurses_functions.c terminal_functions.c list_functions.c -o tom_windows.exe -lpdcurses
```
|
Typically when analyzing a core dump in gdb it'll print the reason why it was generated:
```
Core was generated by `executable'.
Program terminated with signal 11, Segmentation fault.
```
However I've encountered a situation where gdb isn't giving a reason:
```
Core was generated by `executable'.
```
I'm wondering what could cause a core dump where gdb doesn't give the reason for its generation.
|
It turns out that this core file was generated using gcore, so there wasn't actually a problem with the executable. /facepalm
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve this question
I keep getting this error. Any clue what is wrong?
```
struct numFreq(int* num, int* frequency) {
int num, frequency;
};
```
|
You are confusing the syntax for functions with that of structs. Try this:
```
struct numFreq {
int num, frequency;
};
```
|
```
#include<stdio.h>
int main()
{
int a,b;
printf("enter two numbers ");
scanf("%d \n%d",&a,&b);
printf("%d %d",a,b);
return 0;
}
```
when I give inputs like 3 and 5 , then the issue is that even if I give inputs without any newline character in between them then also the scanf function scans the input value , but in the formal string I have stated that the next input should be scanned after a newline character so how can the next input be scanned just after some few whitespaces .
|
White-space in thescanfformat string tellsscanf(and family) to read and ignore white-space in the input. It doesn't matter what kind of white-space character you use in the format: Space, newlines and tabs are all the same.
However, you don't actuallyneedit for all formats. mostscanfformats automatically reads and ignore leading white-space, including the"%d"format.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve this question
I keep getting this error. Any clue what is wrong?
```
struct numFreq(int* num, int* frequency) {
int num, frequency;
};
```
|
You are confusing the syntax for functions with that of structs. Try this:
```
struct numFreq {
int num, frequency;
};
```
|
```
#include<stdio.h>
int main()
{
int a,b;
printf("enter two numbers ");
scanf("%d \n%d",&a,&b);
printf("%d %d",a,b);
return 0;
}
```
when I give inputs like 3 and 5 , then the issue is that even if I give inputs without any newline character in between them then also the scanf function scans the input value , but in the formal string I have stated that the next input should be scanned after a newline character so how can the next input be scanned just after some few whitespaces .
|
White-space in thescanfformat string tellsscanf(and family) to read and ignore white-space in the input. It doesn't matter what kind of white-space character you use in the format: Space, newlines and tabs are all the same.
However, you don't actuallyneedit for all formats. mostscanfformats automatically reads and ignore leading white-space, including the"%d"format.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed7 years ago.Improve this question
What matrix multiplication library would you recommend for Raspberry Pi 2?
I think about BLAS or NumPy, What do you think?
I'm wondering if there is an external hardware module for matrix multiplication available.
Thank you!
|
Mathematica is part of the standard Raspbian distribution. It should be able to multiply matrices.
|
Is there any simple function or strategy that will help mefprintfonto a file from a buffer that I have while moving to the next line every 100 characters?
|
In the general case, not really:fprintfdoes not come with an automatic line wrapping facility.
But you can take advantage offprintf's return value: the number of characters that were written. Updating a column count, you can output a linefeed every time you go past a certain value. If yourfprintfchunks are small enough, the can be a good approximation of what you are trying to do. To properly compute the column count, you must take into account any linefeeds you may output as part of anfprintffunction call.
Otherwise, you cansnprintfto a buffer and search for spaces to break the line appropriately or even just break the line arbitrarily at 100 characters.
Another more general solution is to usepopen()to pipe the output through a utility that would perform the kind of wrapping you want.
|
```
#include<stdio.h>
#include<conio.h>
int main()
{
char c, p;
p=getchar();
int n=p+259;
c=n;
putchar(c);
return 0;
}
```
If I input the 'a' character, could someone tell me why this program's output is the 'd' character?
If p='a', then n=97+259=356.
How is it possible to assign to c the value 100(ASCII code for 'd') if my n variable is 356?
|
charis an 8bit data type, and you greatly exceeded its max representation:
```
a -> ascii 97
97 + 259 -> 356
356 & 0xFF -> 100 - overflowed, strip off "high bit" which can't be stored.
100 -> ascii 'd'
```
|
Why does this code print as it does? I am trying to understand why this code with arrays prints as it does, but I am not quite sure. Can anyone try to help me understand? Thanks!
```
int main (void)
{
int numbers[10] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int i, j;
for (j = 0; j < 10; j++)
{
for (i = 0; i < j; i++)
{
numbers[j] += numbers[i];
}
}
for (j = 0; j < 10; j++)
{
printf ("%d ", numbers[j]);
printf ("\n");
}
return 0;
}
```
|
You have one loop that will iterate trough array and modify each element as a sum of all others. Only catch is that sum changes asjchanges.
On start array is:1, 0, 0, 0, 0, 0, 0, 0, 0, 0After first iteration:1, 0, 0, 0, 0, 0, 0, 0, 0, 0whenj = 0After second iteration:1,1, 0, 0, 0, 0, 0, 0, 0, 0whenj = 1After third iteration:1, 1, 2, 0, 0, 0,0, 0, 0, 0whenj = 2etc.
Please read more aboutforloops.
|
```
#include <stdio.h>
#include <stdlib.h>
#define PATRAT(x) x*x+x;
int main()
{
int x,y,z,t;
x = 104;
y = PATRAT(x - 1);
z = PATRAT(y++);
t = ++PATRAT(x);
printf ("%d %d %d", y, z, t);
return 1;
}
```
Given this code, the results are y = 105, z = 10506, t = 11130 and i can`t understand why. Can you please explain?
|
The preprocessor expands it as follows:
```
y = x - 1*x - 1+x - 1;;
z = y++*y+++y++;;
t = ++x*x+x;;
```
After we make that human-readable, it says:
```
y = x - (1 * x) - 1 + x - 1;
z = (y++ * y++) + y++;
t = (++x * x) + x;
```
Which isundefined behaviorbecause we're modifyingywithout sequence points in between, so any output is possible.
|
My Ubuntu version is 14.04 LTS. I have a C program copied on the desktop by the name sendRawEth.c. When I write:
```
gcc sendRawEth.c -o sendRawEth
```
The compiler complains:
```
gcc: error: sendRawEth.c: No such file or directory
gcc: fatal error: no input files
```
I have no idea how to solve this error.
|
please do the following.
On terminal check the present directory by 'pwd' command and then check the directory in which your programme is there and see if they are same or not. And while writing gcc yourfile it's case sensitive. Hope this helps
|
I am writing up a code for thebisection method.
My code's below, and somehow the loop doesn't seem to start.
There are no special compiling issues.
I don't think there are any problems with the variable declaration / function prototypes.
Can anyone help me find the real issue here?
|
The standardbinary search algogoes like:
```
do {
m=(a+b)/2; /* Change 1, 4 lines */
pA=polynomial(a,c3,c2,c1,c0);
pB=polynomial(b,c3,c2,c1,c0);
pM=polynomial(m,c3,c2,c1,c0);
if(pA*pM<0) {
b=m;
}
else {
a=m; /* Change 2, 1 line */
}
} while(pM!=0 && fabs(a-b)>0.0001);
```
You need to conditionally change bothaandbto converge (reach closer to exit condition) and recalculatepA,pBandpMin each iteration.
There is some scope of optimization (avoid some recalculation) that I hope you can figure out once you can get the code to work to your expectation.
|
How can I convert a string to an array without usingatoi,atol,isdigit, anything like that?
Assume I have aconst char *strand aint *converted_valas parameters.
Here's what I have:
```
const char *c;
for(c = str; (*c != '\0') && isdigit(*c); ++c){
*converted_value = *converted_value*10 + *c - '0';
}
return true;
```
but once again, I can't do it without isdigit. And I'm not sure how to handle strings that are large (for instance: "10000000000000000")
|
```
int yetAnotherAtoi(char *str)
{
int res = 0; // Initialize result
// Iterate through all characters of input string and
// update result
for (int i = 0; str[i] != '\0'; ++i) {
if (str[i]> '9' || str[i]<'0')
return -1; # or other error...
res = res*10 + str[i] - '0';
}
// return result.
return res;
}
```
|
My server is hosted using Flask. I need to send a string from a C code to a page that is running on flask. I am using the socket programming in C to send data to server. But how do I receive it on the flask page? I tried using SocketIO and flask-sockets but was unable to do it properly. Any help would be appreciated. Thank you.
|
Flask talks HTTP. Write your C code to connect to Flask and send HTTP requests.
libcurlmight be useful to you.
At the Flask end, I think that you need to work through thedocumentationto get an understanding of what Flask does and how to write your web app.
You can send a HTTP GET request with a parameter containing your string. In Flask you can access the GET parameters with therequestobject that is available in your view. The URL might behttp://flaskserver/?string=hi+there. You can access the string by treatingrequestas a dictionary, e.g.string_from_c = request.get('string').
|
Is there any simple function or strategy that will help mefprintfonto a file from a buffer that I have while moving to the next line every 100 characters?
|
In the general case, not really:fprintfdoes not come with an automatic line wrapping facility.
But you can take advantage offprintf's return value: the number of characters that were written. Updating a column count, you can output a linefeed every time you go past a certain value. If yourfprintfchunks are small enough, the can be a good approximation of what you are trying to do. To properly compute the column count, you must take into account any linefeeds you may output as part of anfprintffunction call.
Otherwise, you cansnprintfto a buffer and search for spaces to break the line appropriately or even just break the line arbitrarily at 100 characters.
Another more general solution is to usepopen()to pipe the output through a utility that would perform the kind of wrapping you want.
|
```
#include<stdio.h>
#include<conio.h>
int main()
{
char c, p;
p=getchar();
int n=p+259;
c=n;
putchar(c);
return 0;
}
```
If I input the 'a' character, could someone tell me why this program's output is the 'd' character?
If p='a', then n=97+259=356.
How is it possible to assign to c the value 100(ASCII code for 'd') if my n variable is 356?
|
charis an 8bit data type, and you greatly exceeded its max representation:
```
a -> ascii 97
97 + 259 -> 356
356 & 0xFF -> 100 - overflowed, strip off "high bit" which can't be stored.
100 -> ascii 'd'
```
|
Why does this code print as it does? I am trying to understand why this code with arrays prints as it does, but I am not quite sure. Can anyone try to help me understand? Thanks!
```
int main (void)
{
int numbers[10] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int i, j;
for (j = 0; j < 10; j++)
{
for (i = 0; i < j; i++)
{
numbers[j] += numbers[i];
}
}
for (j = 0; j < 10; j++)
{
printf ("%d ", numbers[j]);
printf ("\n");
}
return 0;
}
```
|
You have one loop that will iterate trough array and modify each element as a sum of all others. Only catch is that sum changes asjchanges.
On start array is:1, 0, 0, 0, 0, 0, 0, 0, 0, 0After first iteration:1, 0, 0, 0, 0, 0, 0, 0, 0, 0whenj = 0After second iteration:1,1, 0, 0, 0, 0, 0, 0, 0, 0whenj = 1After third iteration:1, 1, 2, 0, 0, 0,0, 0, 0, 0whenj = 2etc.
Please read more aboutforloops.
|
```
#include <stdio.h>
#include <stdlib.h>
#define PATRAT(x) x*x+x;
int main()
{
int x,y,z,t;
x = 104;
y = PATRAT(x - 1);
z = PATRAT(y++);
t = ++PATRAT(x);
printf ("%d %d %d", y, z, t);
return 1;
}
```
Given this code, the results are y = 105, z = 10506, t = 11130 and i can`t understand why. Can you please explain?
|
The preprocessor expands it as follows:
```
y = x - 1*x - 1+x - 1;;
z = y++*y+++y++;;
t = ++x*x+x;;
```
After we make that human-readable, it says:
```
y = x - (1 * x) - 1 + x - 1;
z = (y++ * y++) + y++;
t = (++x * x) + x;
```
Which isundefined behaviorbecause we're modifyingywithout sequence points in between, so any output is possible.
|
My Ubuntu version is 14.04 LTS. I have a C program copied on the desktop by the name sendRawEth.c. When I write:
```
gcc sendRawEth.c -o sendRawEth
```
The compiler complains:
```
gcc: error: sendRawEth.c: No such file or directory
gcc: fatal error: no input files
```
I have no idea how to solve this error.
|
please do the following.
On terminal check the present directory by 'pwd' command and then check the directory in which your programme is there and see if they are same or not. And while writing gcc yourfile it's case sensitive. Hope this helps
|
lets say I have two int arrays, array1 and array2.
Is this line:
```
array1[i++] = array2[j++];
```
equal to this:
```
array1[i] = array2[j];
i++;
j++;
```
?
|
Yes they are equivalent,unlessyou've written#DEFINE i jor#DEFINE j i, in which case the behaviour of the first snippet isundefined.
|
There is an option '-fshort-double' in GCC, Clang does not understand it. Is there some analog of this option for Clang 3.7 ?
|
in looking at the web page:https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html#Option-Summary,
there is no-fshort-doubleoption ingcc.
therefore, the option is not valid to begin with.
suggest removing that option when changing toclang
|
This question already has answers here:Why do function pointer definitions work with any number of ampersands '&' or asterisks '*'?(5 answers)Closed7 years ago.
Using typedef for functions, like in the following example, are there any differences between using the address of the function or only the function?
```
#include <stdio.h>
int foo(int i){return i+1;}
typedef int(*mytype[2])(int);
int main(void)
{
mytype f;
f[0] = foo;
f[1] = &foo;
printf("%d %d", f[0](5), f[0](6));
return 0;
}
```
|
In the C language, functions are implicitly converted to function pointers in most contexts. Thus you see no difference betweenf[0] = fooandf[1] = &foo. I prefer the latter convention, but really, both are equally fine.
|
I am trying to print a 2D matrix with using[],instead I want to use*like a pointer.So with a 1 D array I'd do:*(arr+i)for example.
What's the syntax used to replace inmatrix[][]?
Here's the code:
```
for (i = 0; i < size; i++)
{
for (j = 0; j < (size * 2); j++)
{
printf(" %5d", matrix[i][j]);
}
printf("\n");
}
```
P.S,
I did try several things like:
```
*(matrix+i+j);
*(matrix+i)+*(matrix+j);
```
Of course none of that worked.
Thank you for your help and time!
|
Use the*two times. Each of*will basically replace one[]:
```
*(*(matrix+i)+j)
```
|
I know that I can make some complex conditions like:
```
#if defined(A) || defined(B) || defined(C)
```
But, if I want a condition like:
```
A || (B && C)
```
Can I use parentheses or the preprocessor will ignore it and force me to write some nested condition?
I have tried:
```
#if defined(A) || (defined(B) && defined(C))
```
and it works. But just for making sure it isn't platform/compiler dependent or anything else because I couldn't find any example like that.
Thanks
|
In C99 standard
6.10 Preprocessing directivesif-group:#ifconstant-expression new-line groupopt6.6.3Constant expressions shall not contain assignment, increment, decrement, function-call, or comma operators, except when they are contained within a subexpression that is not evaluated
defined(A) || (defined(B) && defined(C))is of course a valid constant expression, so it must work
|
I keep getting Segmentation Fault Error when provided with the following arguments in Ubuntu
```
gcc program.c
./a.out $gjdvc1A
```
In the following code
```
# include <stdio.h>
int lcount(char str[])
{ int i=0;
while(str[i]!='\0')
{
i++;
}
if (i<5||i>15)
printf("0");
else
printf("1");
}
main(int argc , char *argv[])
{
lcount( argv[1]);
}
```
Can any body help me and tell that why is this happening
|
You are passing the value of an environment variable $gjdvc1A as an argument. And your program does not have any argument checking, it will always crash when the value for the environment variable is not set
|
I am trying to print the power set of a string.
The code gets compiled successfully, but, when executed, nothing gets printed on the screen.
I am unable to understand the reason behind this.
Below is the code:
```
#include<stdio.h>
#include<string.h>
#include<math.h>
void main()
{
char s[]="abcd";
int i,j,k=1;
int y=strlen(s);
int z=pow(2,y);
for(i=0;i<z;i++)
{
k=1;
for(j=0;j<y;j++)
{
if(j & k)
printf(" %c",s[j]);
k=k<<1;
}
printf("\n");
}
}
```
|
j & kalways evaluates to0.
```
j = 0, k = 1 ==> j & K = 0
j = 1, k = 10 ==> j & K = 0
j = 10, k = 100 ==> j & K = 0
j = 11, k = 1000 ==> j & K = 0
```
|
I'm trying to print program's argument usingwritefunction, my program display garbage, my code looks good to me.
```
#include <stdio.h>
#include <unistd.h>
int ft_putchar(char c) {
write(1,&c,1);
return 0;
}
int main(int argc, char const *argv[]) {
int i;
int b;
i = 1;
while(i < argc) {
b =0;
while(argv[i] != '\0') {
ft_putchar(argv[i][b]);
b++;
}
i++;
}
return 0;
}
```
What am I missing here?
|
The while loop is incorrect and it should be.
```
while(argv[i][b] != '\0')
```
|
I am having a problem with pointers.
this is an example of what I want
```
struct Book
{
char name[10];
int price;
}
int main()
{
struct Book b[10]; //Array of structure variables
struct Book* p; //Pointer of Structure type
p = &b; --- HERE is the ERROR
}
```
This is the error part
```
p = &b;
```
|
bis an array, which can itself decay into a pointer variable. By writing&b, you actually take the address of that pointer and then you end up with pointer to a pointer. It is enough to just writep = b.
|
Very simple question, lets say I have to values in C++ and AND them
0101 & 0110 = 0100
I want the output to be the same as a boolean equal on each value IE: 1100
This needs to be a fast as possible, as this is a low level process for a performance application. I am just getting started with bit operations, so there is probably something simple for this.
Thanks.
|
Basically you want a NOT(XOR(A,B))
which is in c++:
```
~(a^b);
```
Or as truth-table:
```
a | b | a^b | ~(a^b)
1 | 1 | 0 | 1
1 | 0 | 1 | 0
0 | 1 | 1 | 0
0 | 0 | 0 | 1
```
|
I'm trying to reproduce the behaviour ofstrcpyin c, my problem is that the function works but it append extra stuff at the end.
```
char *ft_strcpy(char * dst, const char * src)
{
int i;
i = 0;
while (src[i] != '\0') {
dst[i] = src[i];
i++;
}
return dst;
}
```
When i run it I get the following.
```
int main()
{
char p[] = {};
char z[] = "Hello World";
ft_strcpy(p,z);
printf("%s\n", p);
return 0;
}
```
function results
|
You aren't copying the nul terminator so theprintfdoesn't know to stop.
Just adddst[i] = 0;after the loop.
Also, you haven't allocated any space forp, so you're going to get undefined behavior. For a first test just do something likechar p[100];and make surezis never > 99 chars long. Eventually you need a better fix, but that will get you started.
|
I am recieving the error message from the title in this code below
```
int main()
{
int day = 1;
float penny = 0.01;
while (day<32)
printf("On Day %d you had %f dollars",day, penny);
penny *=2;
day++;
}
return 0;
```
Any and all help is appreciated. :D
|
Missing{afterwhileand}afterreturn 0;
```
int main()
{
int day = 1;
float penny = 0.01;
while (day<32)
{
printf("On Day %d you had %f dollars",day, penny);
penny *=2;
day++;
}
return 0;
}
```
|
I'm currently learning about TCP and packets. I'm working in the C programming language, and I understand how thepcaplibrary can be used to sniff traffic on my computer. But canpcapbe used to parse and read through a trace file as well? I need to track the TCP state information from a given trace file.
In a nutshell, I'm curious how I can go about opening a trace file withpcapto parse through it? If someone could get me moving towards the right direction, it would be greatly appreciated!
|
But can pcap be used to parse and read through a trace file as well?
Yes. Most of the APIs you'd use are the same, but you'd usepcap_open_offline()to open a file rather than usingpcap_open_live(), orpcap_create()andpcap_activate(), to open a device for a live capture.
|
I am trying to obtain a number of bits from a byte in C. Currently I am doing so by shifting and then bit masking (0xFF), however the shifting operator is taking a long time. Is there another way to this using only bitwise operations? And if so how?
Thanks!
|
If you want to move a particular (single) bit to the least-significant position, you can use a hack like this:
```
(x & mask) != 0
```
wheremaskselects the single bit.
|
I was trying to use the '\r' character to write over the previous line; however, when used in conjunction with nanosleep(), the program does not output until the end. Here is a code example:
```
int i;
struct timespec t = {1, 0};
for (i = 0; i < 10; ++i) {
nanosleep(&t, NULL);
printf('\ri: %d', i);
}
```
This will wait for 10 seconds, and then print outi: 9. I would like it to show the updates, not just the end. I'm not sure if the line is being flushed or something?
Any and all help is greatly appreciated!
|
The console is caching your line until the char \n (newline) appears. You can use "fflush" to explicitly write the content to screen.
Maybe there is a little impact on performance.
|
I'm currently learning about TCP and packets. I'm working in the C programming language, and I understand how thepcaplibrary can be used to sniff traffic on my computer. But canpcapbe used to parse and read through a trace file as well? I need to track the TCP state information from a given trace file.
In a nutshell, I'm curious how I can go about opening a trace file withpcapto parse through it? If someone could get me moving towards the right direction, it would be greatly appreciated!
|
But can pcap be used to parse and read through a trace file as well?
Yes. Most of the APIs you'd use are the same, but you'd usepcap_open_offline()to open a file rather than usingpcap_open_live(), orpcap_create()andpcap_activate(), to open a device for a live capture.
|
I am trying to obtain a number of bits from a byte in C. Currently I am doing so by shifting and then bit masking (0xFF), however the shifting operator is taking a long time. Is there another way to this using only bitwise operations? And if so how?
Thanks!
|
If you want to move a particular (single) bit to the least-significant position, you can use a hack like this:
```
(x & mask) != 0
```
wheremaskselects the single bit.
|
I was trying to use the '\r' character to write over the previous line; however, when used in conjunction with nanosleep(), the program does not output until the end. Here is a code example:
```
int i;
struct timespec t = {1, 0};
for (i = 0; i < 10; ++i) {
nanosleep(&t, NULL);
printf('\ri: %d', i);
}
```
This will wait for 10 seconds, and then print outi: 9. I would like it to show the updates, not just the end. I'm not sure if the line is being flushed or something?
Any and all help is greatly appreciated!
|
The console is caching your line until the char \n (newline) appears. You can use "fflush" to explicitly write the content to screen.
Maybe there is a little impact on performance.
|
I was going through the examples in K&R, and stumbled upon this bit of code:
```
celcius=5 * (fahr-32) / 9;
```
The author says that we can't use 5/9 since integer division truncation will lead to a value of 0.
The program however, outputs 17 as answer when fahr=0. By my calculations, (0-32)/9 should lead to -3 (due to truncation) and then -3*5 = -15, and NOT -17. Why does this happen?
|
(0 - 32) is first multiplied by 5, giving -160. -160 / 9 = -17.
|
To aid with some precise memory allocation that I'm doing inC, I'm trying to get thesizeofa function pointer for a function with return type void that takes no parameters.
However, when I dosizeof (void (*)()), I generate a compiler warning:
function declaration isn’t a prototype [-Wstrict-prototypes]
How do I get the size that I'm looking for?
|
That is an old style function definition, it is missing the argument list, so add them:
```
sizeof( void(*)(void) )
```
|
I want to copy a string and want to stop copying either the next character is '\0' or '.'
so I wrote
```
while((dest[i]=src[i])!='\0'||src[i]=='.');
i++;
```
when the character is '\0' the while loop works perfectly
but in case of '.'
must I write a separate "if condition" for the second part ?and why?
|
You have an infinite loop there.
```
while((dest[i]=src[i])!='\0'||src[i]=='.'); // This is the end of the loop,
// with an empty statement.
```
Also, you need to change the conditional a little bit.
```
(dest[i]=src[i]) != '\0' && src[i] != '.'
```
To avoid the empty statement problem afterwhileandifstatements, you can change your coding standard so that you always use the{}.
```
while ( (dest[i]=src[i]) != '\0' && src[i] != '.' )
{
++i
}
```
|
I'm slowly reading PHP 7 source code, written in C. But I'm really curious about "instancing a class". In PHP, this happen writing$myclassvar = new myclass().
What should this code exactly do in C? What type of var is$myclass? Why should weinstantiatea class? Should this mean call the constructor__construct()? Can you please explain me what should this code refers to (detailed). Thanks
|
C does not have classes, but the closest thing in C ismallocing structures on the heap. The PHP code$myclassvar = new myclass()is most similar to
```
typedef struct {
int x, y;
} pt;
pt *p = malloc(sizeof(pt));
```
|
```
#include <stdio.h>
#define KILOMETRE 9
main()
{
float metre = KILOMETRE / 1000;
printf("%f\n", metre);
}
```
The answer should be 0.009 as 9/1000=0.009
But after executing the program the output turns out to be 0.00.
Please help. :D
|
In this expression
```
KILO/1000
```
the both operands are integers. So the result of the operation / for integer values is equal to 0.
You could write instead
```
KILO/1000.0f
```
In this case the compiler will deal with float numbers.
Take into account that according to the C Standard function main without parameters shall be declared like
```
int main( void )
```
|
I am writing aPython 3 C extensionwhere I want to use a MappingProxyType (from types import MappingProxyType). From what I saw in the Cpython source code, MappingProxyType is written in Python and not in C.
How can I use this type from C? I imagine there must be something like an C-level "import" and then I could find the PyObject (or rather, PyTypeObject) from the name as a C string.
|
There's aC APIfor for importing modules. Then you just need to get theMappingProxyTypetype attribute from the module:
```
static PyTypeObject *import_MappingProxyType(void) {
PyObject *m = PyImport_ImportModule("types");
if (!m) return NULL;
PyObject *t = PyObject_GetAttrString(m, "MappingProxyType");
Py_DECREF(m);
if (!t) return NULL;
if (PyType_Check(t))
return (PyTypeObject *) t;
Py_DECREF(t);
PyErr_SetString(PyExc_TypeError, "not the MappingProxyType type");
return NULL;
}
```
|
i have some trouble with a simple copy function:
```
void string_copy(char *from, char *to) {
while ((*to++ = *from++) != '\0')
;
}
```
It takes two pointers to strings as parameters, it looks ok but when i try it i have this error:
```
Segmentation fault: 11
```
This is the complete code:
```
#include <stdio.h>
void string_copy(char *from, char *to);
int main() {
char *from = "Hallo world!";
char *to;
string_copy(from,to);
return 0;
}
```
Thank you all
|
Your problem is with the destination of your copy: it's achar*that has not been initialized. When you try copying a C string into it, you get undefined behavior.
You need to initialize the pointer
```
char *to = malloc(100);
```
or make it an array of characters instead:
```
char to[100];
```
If you decide to go withmalloc, you need to callfree(to)once you are done with the copied string.
|
I'm slowly reading PHP 7 source code, written in C. But I'm really curious about "instancing a class". In PHP, this happen writing$myclassvar = new myclass().
What should this code exactly do in C? What type of var is$myclass? Why should weinstantiatea class? Should this mean call the constructor__construct()? Can you please explain me what should this code refers to (detailed). Thanks
|
C does not have classes, but the closest thing in C ismallocing structures on the heap. The PHP code$myclassvar = new myclass()is most similar to
```
typedef struct {
int x, y;
} pt;
pt *p = malloc(sizeof(pt));
```
|
```
#include <stdio.h>
#define KILOMETRE 9
main()
{
float metre = KILOMETRE / 1000;
printf("%f\n", metre);
}
```
The answer should be 0.009 as 9/1000=0.009
But after executing the program the output turns out to be 0.00.
Please help. :D
|
In this expression
```
KILO/1000
```
the both operands are integers. So the result of the operation / for integer values is equal to 0.
You could write instead
```
KILO/1000.0f
```
In this case the compiler will deal with float numbers.
Take into account that according to the C Standard function main without parameters shall be declared like
```
int main( void )
```
|
I am writing aPython 3 C extensionwhere I want to use a MappingProxyType (from types import MappingProxyType). From what I saw in the Cpython source code, MappingProxyType is written in Python and not in C.
How can I use this type from C? I imagine there must be something like an C-level "import" and then I could find the PyObject (or rather, PyTypeObject) from the name as a C string.
|
There's aC APIfor for importing modules. Then you just need to get theMappingProxyTypetype attribute from the module:
```
static PyTypeObject *import_MappingProxyType(void) {
PyObject *m = PyImport_ImportModule("types");
if (!m) return NULL;
PyObject *t = PyObject_GetAttrString(m, "MappingProxyType");
Py_DECREF(m);
if (!t) return NULL;
if (PyType_Check(t))
return (PyTypeObject *) t;
Py_DECREF(t);
PyErr_SetString(PyExc_TypeError, "not the MappingProxyType type");
return NULL;
}
```
|
i have some trouble with a simple copy function:
```
void string_copy(char *from, char *to) {
while ((*to++ = *from++) != '\0')
;
}
```
It takes two pointers to strings as parameters, it looks ok but when i try it i have this error:
```
Segmentation fault: 11
```
This is the complete code:
```
#include <stdio.h>
void string_copy(char *from, char *to);
int main() {
char *from = "Hallo world!";
char *to;
string_copy(from,to);
return 0;
}
```
Thank you all
|
Your problem is with the destination of your copy: it's achar*that has not been initialized. When you try copying a C string into it, you get undefined behavior.
You need to initialize the pointer
```
char *to = malloc(100);
```
or make it an array of characters instead:
```
char to[100];
```
If you decide to go withmalloc, you need to callfree(to)once you are done with the copied string.
|
In programming languages if I use "\n" it adds a newline character.
Could somebody explain how the "\n" gets translated to a newline and the same for "\t"?
|
When the compiler is reading your program and it seesbackslash somethingit knows to 'pretend' it saw something else. You can imagine that part of the compiler works like this:
```
current_character = getNextCharacter();
if (current_character == BACKSLASH) {
current_character = getNextCharacter();
if (current_character == 'n') {
/*oh, they want a newline */
} else if (current_character == 't') {
/* it's a tab they want */
} else /* ... and so on and so forth */
}
```
|
please explain the sequence of BIT wise operation being performed in different cases.
```
(gdb) set $i = 1
(gdb) p $i << 1 + ($i << 3)
$11 = 512
(gdb) set $i = 1
(gdb) p ($i << 1) + $i << 3
$12 = 24
(gdb) set $i = 1
(gdb) p $i << 1 + $i << 3
$13 = 32
(gdb)
```
|
I'll explain one case and leave the rest to you.
```
(gdb) p $i << 1 + ($i << 3)
$11 = 512
```
On this line, reading from right to left,$iis initially 1 (0001 in binary), shift left<<3 bits, we have1000because of the parentheses, then add 1 to get1001, which is 9. The next<<means shift9bits left from the initial$i, we have2^9 = 512. This is the result you see in the next line.
Notice how the original$iis not modified and you need to follow precedence.
|
I'm wondering if it is okay to use thestrcpy()function in C to copy a heap array to a stack array? Are there any potential problems to that?
|
Of course it's okay to copy into a stack array.
To be clear, it would look like this:
```
char on_stack[100];
strcpy(on_stack, source_string_on_heap);
```
Just make sure that the stack array is big enough to hold what you're copying, and be aware that the stack array will disappear after its context ends. Never have a function return a pointer to a stack variable.
Note onstrcpy()usage: Your source buffer must be null-terminated and your destination buffer must have room for the termination character as well. This has nothing to do with heap or stack usage, it's just how thestrcpy()function works.
You are also free to use any other method to copy from the heap to the stack, including usingmemcpy()or manually copying byte-by-byte with achar*and loop.
|
I want to compare to string pointers while ignoring their case. I cant think of any C function that can do that.
For example:
```
ToMMy == tommy == TOMMY == tOMmy etc.....
```
Does anyone know how this can be done in C?
|
If it is OK to support only single-byte English alphabets to ignore cases, just convert each characters to lower case (or upper case) and compare.
```
#include <ctype.h>
int cmp(const char *a, const char *b) {
while (*a || *b) {
int c1 = tolower((unsigned char)*a++);
int c2 = tolower((unsigned char)*b++);
if (c1 != c2) return c1 > c2 ? 1 : -1;
}
return 0;
}
```
|
Say I have an array arr[10], and then I copy all elements to another array, arr2[20]. I no longer need arr, so I do arr=arr2 to move its pointer to the new array. Is the memory that was used by arr[10] still used, or is it freed automatically? If it's still used, is there a way for me to free it before reassigning the pointer?
|
If you declared arr likeint arr[10];then it will be stored on thestack, and will be freed when the function ends. You generallycan'tfree stack memory mid function.
If you defined it usingmalloc()then it will be on the heap and you have to usefree()to free it. Or else it will be a memory leak and be freed after your program exits. However, even if you get a memory leak, you computer will always be able to retrieve that memory because ofvirtual memory.
|
Hi I just started learning C programming ingcccompiler on my Debian system. Here is the code
```
main()
{
fflush( stdin );
int a,b;
scanf("%d,%d",&a,&b);
printf("%d,%d",a,b);
}
```
Thescanfdoesn't take input for the second variable. I press 2 and then return key and it displays
```
root@debian:/home/wis# ./test
2
2,0root@debian:/home/wis#
```
I have used space and tab key also. Please help me.
|
You defined yourscanfstring as"%d,%d", so the program expect an input like1,2.
If you give it only one digit and press Enter, it parses the first digit and leaves the second one untouched. It was assigned0on declaration, so that's what you are seeing when printing.
Yourprintfstatement would benefit from an"\n"at the end, and your code snippet needs indentation. Please show your includes (#include <stdio.h>) next time, it makes it easier for us to compile and run the code.
|
Below is a pseudo code in C. parallelized using OpenMP. What is wrong in the parallel OpenMP code that will prevent it from producing correct result like the serial code and how will you correct that?
```
void ccode (float a[], float b[], float c[], int n) {
float x, y ; int i;
#pragma omp parallel for shared (a,b,c,n,x,y) private i
for (i = 0 ; i < n ; i++){
x = a[i] - b[i] ;
y = b[i] + a[i] ;
c[i] = x * y ;
}
```
|
I think the problem is
```
x = a[i] - b[i] ;
y = b[i] + a[i] ;
```
where bothxandyshould be declaredprivate, since each thread should be using its own pair ofxandy.
|
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
I want to do this code in c to Android
I dont use passwordtext
I need to use editText
ty
```
ph=getch();
if(ph!='\r'){
pass[i]=ph;
printf("*");
```
|
In xml of EditText iclude this attribute:
```
android:password="true"
```
If you want to do it in
|
How are the values associated with a and b? How are values of a and b assigned to variables (when they are of different data types)
```
#include <stdio.h>
#define a 1
#define b 1
int main(void)
{
printf("%s", (a & b) ? "T":"F");
return 0;
}
```
|
They are not stored, they are replaced when they appear in the code by the preprocessor. So the code is "literally" equivalent to
```
printf("%s", (1 & 1) ? "T" : "F");
```
|
This question already has answers here:How to only accept a certain precision (so many decimals places) in scanf?(4 answers)Closed7 years ago.
I am extremely beginner in programming language. so i am facing some problems. please help me out.
Is it possible to take input a floating or double number with 2 digits after the decimal point using 'scanf' in C ??
|
See here:How to only accept a certain precision (so many decimals places) in scanf?
```
float value;
scanf("%4f", &value);
```
It's not really do that, but reads 4 digitedit: 4 charactersfloat number. You can set other number instead of 4.
If you really need only 2 decimal places you can read the number withscanf, and after that round it usingroundf.
```
#include <math.h>
...
float value;
scanf("%f", &value);
value = roundf(value*100)/100
```
|
This question already has answers here:How does C handle integer literals with leading zeros, and what about "atoi"?(9 answers)Closed7 years ago.
The following code prints255, but if I assigned0255tox, as in the second line, the code prints173!
Is there any explanation for this?
```
void main()
{
unsigned long x = 255;
/* unsigned long x = 0255;*/
unsigned char *ptr = &x;
printf("%u",*ptr);
getch();
}
```
|
```
unsigned char x = 0255;
```
0255is considered an octalintliteral. This works because you can assignintliterals to chars, and octal0255is(5*8^0)+(5*8^1)+(2*8^2) = 173in decimal notation.
Visitthe referencefor more info on what the different forms of notational string literals are, but for quick reference:
```
unsigned char x = 0255; // Octal -> 173 in decimal
unsigned char x = 255; // Decimal -> 255 in decimal
unsigned char x = 0x2F // Hexadecimal -> 47 in decimal
```
|
I have an array of char (string) that contain a decimal number.
How do I convert it to unsigned char?
```
char my_first_reg[2];
memcpy( my_first_reg, &my_str_mymatch[0], 1 );
my_first_reg[1] = '\0';
// now my_first_reg contain reg number ... how to convert to unsigned char
```
|
To convertmy_first_reg[0]the ASCII character to its numeric value:
```
unsigned char value = my_first_reg[0] - '0';
```
This works because digits in the ASCII table are sequential:
```
'0' = 0x30 = 48
'1' = 0x31 = 49
'2' = 0x32 = 50
'3' = 0x33 = 51
'4' = 0x34 = 52
...
'9' = 0x39 = 57
```
The above is for converting one character. If you have a longer string, consider usingatoi(),strtol(),sscanf(), or something similar.
|
This question already has answers here:Purpose of while(1); statement in C(12 answers)Closed7 years ago.
I saw in a lots of example a form of use for the while loop that I'm not sure it's ok to use in a code.
```
while(1){
// code lines
if(condition){
break;
}
// code lines
}
```
Is this ok to use? what does
```
while(1)
```
exactly mean?
|
is this ok to use? what exactly
Yes, and its commonly used in programming.
while(1)is the same aswhile(true), basically a condition thats always true, ensuring thewhileloop never stops until you manually break out of it withbreak;
There are many applications for this behavior. It could be that the exit condition is very complex, requires function calls, etc. It could be that you just want a infinite loop for your program (for a menu for instance) that only exits on very specific prompts. Wether or not you use it often is often also a stylistic choice.
|
I am using sizeof function to calculate the size of a string.
It should have printed 2.But why 4?
Here is the code.
```
#include <stdio.h>
#include <string.h>
void main()
{
char *b = "ab";
printf(" %d ",sizeof(b));
//printf("%s ",b);
}
```
|
Because on your platform pointers are 4 bytes. Or 32bit if you prefer.
NOTE: Usingvoid main()as a signature formain()indicates that you are studyingcfrom an old book probably, be careful!
|
In C, while reading into a buffer from a socket file descriptor, how do I make the read stop if a delimiter is detected? Let's assume the delimiter is a '>' character.
```
read(socket_filedes, buffer, MAXSZ);
/* stop if delimiter '>' is detected */
```
|
You have two options here:
Read a single byte at a time until you encounter a delimiter. This is likely to be very inefficient.Read in a full buffer's worth of data at a time, then look for the delimiter there. When you find it, save off the remaining data in another buffer and process the data you want. When you're ready to read again, put the saved data back in the buffer and callreadwith the address of the next available byte in the buffer.
|
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
I am writing a code for solving arithmetic expression like:4+3-2*6*(3+4/2)
For that I need to compare the operators in the string with precedence like:
```
1. ( or )
2. * or /
3. + or -
```
Can someone tell me how to compare two characters. As their ASCII values are not in the order which I want!
|
Use a lookup table. If using ASCII, it is just a 256 element table. You index it with the char.
|
I am trying to display...(three dots), but each dot then a second delay then a second dot then a second delay then a third dot.
I tried this
```
for(int i = 0;i < 3;i++)
{
sleep(1);
printf(".");
sleep(1);
}
```
But this just waits for 6 seconds and then prints the three dots all together but I don't want that. Is there a fix for this. I want
.second delay.second delay.
but it will appear
...
|
Try:
```
#include <stdio.h>
#include <unistd.h>
int main() {
for(int i = 0;i < 3;i++)
{
printf(".");
fflush(stdout);
sleep(1);
}
}
```
printf()prints tostdoutwhich is bufferred. Flush out the buffer after eachprintf().
<< std::flush;is the C++ equivalent to this.
|
every time I run the program below in the following way:./a.out -a -bit runs properly. But if choose to run./a.out -a, I result in a segmentation fault (core dumped). Is there any way I can fix this?
```
int main(int argc, char *argv[])
{
if (argc > 1)
{
if (strcmp(argv[1],"-a") == 0)
{...
if (strcmp(argv[2],"-b") == 0)
{...}
}
}
}
```
|
When you run it with./a.out -a, only one argument, then you should not do the checkstrcmp(argv[2],"-b"), because there is no third argument, and readingargv[2]would result in undefined behavior.
You can fix it by adding an extra check before doing thestrcmp(argv[2],"-b").
```
int main(int argc, char *argv[])
{
if (argc > 1)
{
if (strcmp(argv[1],"-a") == 0)
{...
if (argc > 2 && strcmp(argv[2],"-b") == 0)
{...}
}
}
}
```
This looks pretty ugly but it would work.
|
I am revisiting code that I wrote a while ago that does some math on large numbers. When I wrote the code, the lab had a few x86s that were split between 32 and 64 bits. My work was on UltraSPARCs, and I vaguely remember pulling this line of code from an Intel manual to be sure that the code was being used on a 64-bit CPU.
```
unsigned long x[4];
x[0] = 0;
x[1] = 0;
x[2] = 0;
x[3] = 0;
asm volatile(".byte 15;.byte 162" : "=a"(x[0]),"=b"(x[1]),"=c"(x[3]),"=d"(x[2]) : "0"(0) );
```
If x[0] was 0, all was well and the program started chugging away.
Can anyone explain to me what this line of code actually does?
|
The bytes.byte 15and.byte 162represent theCPUIDinstruction.When it executes you get results inEAX,EBX,ECX, andEDX.
These results will be stored in the array elements:
```
x[0] <- EAX
x[1] <- EBX
x[2] <- EDX
x[3] <- ECX
```
|
I am learningC. I am starting to understand pointers and type casting. I am following along with some guides and examples and I ran across this declaration:
```
uint32_t *sp;
...
*(uint32_t*)sp = (uint32_t)somevalue;
```
What is happening here? The first asterisk specifically is a mystery to me.
|
Breaking it down:
```
*(uint32_t*)sp
```
basically says to treatspas a pointer touint32_t((uint32_t *)is acast expression), and to dereference the result.
So,
```
*(uint32_t*)sp = (uint32_t)somevalue;
```
means, "takesomevalue, convert it to typeuint32_t, and store the result to the thingsppoints to, and treat that thing as though it were also auint32_t."
Note that the cast onspis redundant; you'vealreadydeclared it as a pointer touint32_t, so that assignment could be written as
```
*sp = (uint32_t) somevalue;
```
|
I stumbled upon some code where thetypedefkeyword is in between the type and the alias name like in
```
int typedef INT;
```
It compiles in gcc and clang (live example). I am not very good in understanding standardese. So my question is: Is this standard conformant? Can I rely on compilers to support it?
|
Thetypedefkeyword is classified as a storage class specifier in C, though the standard explicitly remarks that that's for convenience in expressing the formal language syntax. It nevertheless follows thattypedefcan appear in exactly the same places that any other storage class specifier, such asexternorstatic, can appear. [C2011, 6.7.1/5]
In fact, the syntax allows storage-class specifiers to be intermixed with type specifiers, type qualifiers, and other "declaration specifiers" in declarations. [C2011, 6.7/1, 6.7/6]
Thus, yes, it is valid to put thetypedefkeyword after the type name, as in your example.
|
In the code below, could somebody explain what the second argument is? is it a "constant pointer the data".
Thanks
|
The second argument is a const pointer to a const data.
```
const uint8_t * const == uint8_t const * const
uint8_t const * const == const pointer to const uint8_t
```
To help you, think of the backwards reading:
int*- pointer to intint const *- pointer to const intint * const- const pointer to int
etc.
So in your example,const uint8_t *const datais "data const + pointer of uint8_t const" => a const pointer to const data.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.