question
stringlengths
25
894
answer
stringlengths
4
863
I have a very simple question but i can't resolve it. There's an index from 0 to (2^32)-1 and i want to calculate an offset with this index like this : 0 to (2^8)-1 => 0 2^8 to (2^16)-1 => 1 2^16 to (2^24)-1 => 2 2^24 to (2^32)-1 => 3 Can anyone give me the equation to do ?
Assumingiis your 32 bit integer, this expression would work: ``` (i > 0xffffff? 3: i > 0xffff? 2: i > 0xff? 1: 0) ``` Actually, the last ternary?:operator is unnecessary, so the expression could be simplified to ``` (i > 0xffffff? 3: i > 0xffff? 2: i > 0xff) ``` Or you could remove the ternary operators and do only comparison and addition: ``` ((i > 0xffffff) + (i > 0xffff) + (i > 0xff)) ```
there is the code about alloc mem via mmap void *ret = mmap(NULL, 4 * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); when process exits normally, the memory will be return to os ?
According to themanand underunmap: The region is also automatically unmapped when the process is terminated. Which sounds very reasonable as the memory is added to the processes pages in the virtual memory which is freed upon termination. Opengroupdoesn't say anything on the subject. If the system does not free the memory You can try to set an at_exit up to clear up any still allocated memmaps that are still valid if you can find a pointer to it.
As per title, is there an equivalent ofpthread_barrier_ttype in windows? I' ve foundSYNCHRONIZATION_BARRIERbut seems available only since Windows 8. Is there something more portable? Thanks
Do it the old fashioned way before barriers were invented: with a counting semaphore
Any clues on what is causing it? This is the function: ``` int readfile(char** s, const char* filename) { struct stat st; int i; if(stat(filename, &st) == -1) return 0; *s = malloc(st.st_size+1); for (i=0; i<st.st_size+1; i++) *s[i] = 0; FILE* f; f = fopen(filename, "rb"); fread(*s, 1, st.st_size, f); return 1; } ``` And this is how I'm calling it: ``` char* string; if (!readfile(&string, "filename.ext")) fprintf(stderr, "Problem reading file\n"); ``` I have no troubles copying what's read byfreadto a string declared inside thereadfilefunction. Thank you in advance.
This is an operator precedence error :http://www.swansontec.com/sopc.html I think what you're trying to do is : ``` for (i=0; i<st.st_size+1; i++) (*s)[i] = 0; ```
int array[] = {1,2,3,4}; As I understand,arrayis just a pointer to&array[0] But how come thensizeof(array);knows size of an array and not just that it's only 4 byte number?
Although the name of the array does become a pointer to its initial member in certain contexts (such as passing the array to a function) the name of the array refers to that array as a whole, not only to the pointer to the initial member. This manifests itself in taking the size of the array throughsizeofoperator.
There is good documentation here (http://www.postgresql.org/docs/8.3/static/xfunc-c.html), but I didn't find a way to read/modify/delete data from existing table by tablename and columns name from C extension.
I guess what you need isSPI. P. S. Do you actually use 8.3? Use the latest (9.4) if you're not restricted somehow.
I want to write a function that when called doubles its argument (if it is non-zero) or returns a specific constant (if it is zero). The constant is always a power of 2 if that helps. Let's say the constant is 8. When called with 0, I want it to return 8. When called with 8, I want it to return 16. And so on. The trivial approach would be something like: ``` unsigned foo(unsigned value) { return (value ? value * 2 : 8); } ``` Is it possible to do this without branching?
This causes no additional memory access. ``` int f(int a) { const int c = 8; return (a*2)+(a==0)*c; } ```
In a single nibble (0-F) I can store one number from 0 to 15. In one byte, I can store a single number from 0 to 255 (00 - FF). Can I use a byte (00-FF) to store two different numbers each in the range 0-127 (00 - 7F)?
The answer to your question is NO. Youcansplit a single byte into two numbers, but the sum of the bits in the two numbers must be <= 8. Since, the range 0-127 requires 7 bits, the other number in the byte can only be 1 bit, i.e. 0-1.
``` int m,digit[100],i=0, n = 15; while(n) { m = n%2; digit[i] = "0123456789abcdefghijklmnopqrstuvwxyz"[m]; n = n/2; } ``` I did not understand what is digit[i] = "0123456789abcdefghijklmnopqrstuvwxyz"[m];
digit[i] ="0123456789abcdefghijklmnopqrstuvwxyz"[m];is themth letter of0123456789abcdefghijklmnopqrstuvwxyz.
When I resize my window and aWM_SIZEmessage is sent, does theWM_SIZEmessage get sent to the message queue or does the window procedure called directly?
Resizing a window by mouse sendsWM_SIZEdirectly to the window procedure, it does not go through the message queue.
Can I be sure that data conversion always succeeds? If I have anintand I usemmap(2), is theintconverted tooff_tandsize_t? Why are there all those different sizes? And are there conversion function?
I am not sure about the usage of the mmap function you are doing since mmap returns a pointer. Regarding conversion you can basically convert any variable to anything using a cast, however it is your responsibility to verify that this will work for example:int i; double d; d = 42.3; i = (int)d; printf("i = %d", i); Output will be 42, without the cast(int)some compilers would probably complain and warn you that you will lose floating precision. About the why of all these different sizes, first thingsize_tis meant to represent a size so you can grossly think of it as anunsigned int, regarding why not use aunsigned intrather than a typedef'ed "size_t", see this postunsigned int vs size_t.
I've recently found GLFW and have been trying out making a simple application with it and was wondering about glfwTerminate and glfwDestroyWindow. I understand that glfwTerminate will cleanup any windows that are still open so it should be safe to never call gflwDestroyWindow on the main window but should I still call gflwDestroyWindow before terminating or is it more just a personal preference? To clarify which of the following are "better". ``` auto window = glfwCreateWindow(...); // Do some things glfwDestroyWindow(window); glfwTerminate(); ``` Or ``` auto window = glfwCreateWindow(...); // Do some things glfwTerminate(); ```
According todocumentation All windows remaining whenglfwTerminateis called are destroyed as well. you don't need to do callglfwDestroyWindow(window);. Although I suppose it is better to destroy each window separately.
I am new to programming. I was finding a square root of a number usingsqrt()function in c. ` ``` scanf("%d", &n); printf("%d\n", sqrt(n)); } return 0; } ``` When I enter a value ofn = 5, I got some negative large number. Can anyone explain, please?
You've produced undefined behavior by passing the wrong type toprintf: the%dformat required a matching argument of typeintbut your argument has typedouble. You need%f(or%eor%gor%a) to print it. Also, there may be other problems, e.g. if you omitted#include <math.h>.
TheAND(&&) condition evaluates asOR(||) in this code. For ex., when user inputs numbers6and7, the output is12but when the I replace&&with||the output is42. ``` #include<stdio.h> int main() { int a,b,max,lcm; printf("Enter 2 numbers: "); scanf("%d %d", &a, &b); if(a>b) { max=a; } else { max=b; } do { max++; } while(max%a!=0 && max%b!=0); lcm=max; printf("LCM of %d and %d is %d\n", a,b,lcm); return 0; } ```
No, the&&condition is working as anandcondition, just as it should. When you input6and7,max%aevaluates to0whenmaxis12. At that pointmax%a != 0evaluates tofalse(false && true == false), andmax%a != 0 && max%b != 0evaluates tofalse, and your loop exits. However,max%a != 0 || max%b != 0evaluates totrue(max%bis5for amaxof12andbof7,false || true == true), so the loop continues.
int array[] = {1,2,3,4}; As I understand,arrayis just a pointer to&array[0] But how come thensizeof(array);knows size of an array and not just that it's only 4 byte number?
Although the name of the array does become a pointer to its initial member in certain contexts (such as passing the array to a function) the name of the array refers to that array as a whole, not only to the pointer to the initial member. This manifests itself in taking the size of the array throughsizeofoperator.
There is good documentation here (http://www.postgresql.org/docs/8.3/static/xfunc-c.html), but I didn't find a way to read/modify/delete data from existing table by tablename and columns name from C extension.
I guess what you need isSPI. P. S. Do you actually use 8.3? Use the latest (9.4) if you're not restricted somehow.
I want to write a function that when called doubles its argument (if it is non-zero) or returns a specific constant (if it is zero). The constant is always a power of 2 if that helps. Let's say the constant is 8. When called with 0, I want it to return 8. When called with 8, I want it to return 16. And so on. The trivial approach would be something like: ``` unsigned foo(unsigned value) { return (value ? value * 2 : 8); } ``` Is it possible to do this without branching?
This causes no additional memory access. ``` int f(int a) { const int c = 8; return (a*2)+(a==0)*c; } ```
In a single nibble (0-F) I can store one number from 0 to 15. In one byte, I can store a single number from 0 to 255 (00 - FF). Can I use a byte (00-FF) to store two different numbers each in the range 0-127 (00 - 7F)?
The answer to your question is NO. Youcansplit a single byte into two numbers, but the sum of the bits in the two numbers must be <= 8. Since, the range 0-127 requires 7 bits, the other number in the byte can only be 1 bit, i.e. 0-1.
``` int m,digit[100],i=0, n = 15; while(n) { m = n%2; digit[i] = "0123456789abcdefghijklmnopqrstuvwxyz"[m]; n = n/2; } ``` I did not understand what is digit[i] = "0123456789abcdefghijklmnopqrstuvwxyz"[m];
digit[i] ="0123456789abcdefghijklmnopqrstuvwxyz"[m];is themth letter of0123456789abcdefghijklmnopqrstuvwxyz.
When I resize my window and aWM_SIZEmessage is sent, does theWM_SIZEmessage get sent to the message queue or does the window procedure called directly?
Resizing a window by mouse sendsWM_SIZEdirectly to the window procedure, it does not go through the message queue.
Can I be sure that data conversion always succeeds? If I have anintand I usemmap(2), is theintconverted tooff_tandsize_t? Why are there all those different sizes? And are there conversion function?
I am not sure about the usage of the mmap function you are doing since mmap returns a pointer. Regarding conversion you can basically convert any variable to anything using a cast, however it is your responsibility to verify that this will work for example:int i; double d; d = 42.3; i = (int)d; printf("i = %d", i); Output will be 42, without the cast(int)some compilers would probably complain and warn you that you will lose floating precision. About the why of all these different sizes, first thingsize_tis meant to represent a size so you can grossly think of it as anunsigned int, regarding why not use aunsigned intrather than a typedef'ed "size_t", see this postunsigned int vs size_t.
I've recently found GLFW and have been trying out making a simple application with it and was wondering about glfwTerminate and glfwDestroyWindow. I understand that glfwTerminate will cleanup any windows that are still open so it should be safe to never call gflwDestroyWindow on the main window but should I still call gflwDestroyWindow before terminating or is it more just a personal preference? To clarify which of the following are "better". ``` auto window = glfwCreateWindow(...); // Do some things glfwDestroyWindow(window); glfwTerminate(); ``` Or ``` auto window = glfwCreateWindow(...); // Do some things glfwTerminate(); ```
According todocumentation All windows remaining whenglfwTerminateis called are destroyed as well. you don't need to do callglfwDestroyWindow(window);. Although I suppose it is better to destroy each window separately.
I am new to programming. I was finding a square root of a number usingsqrt()function in c. ` ``` scanf("%d", &n); printf("%d\n", sqrt(n)); } return 0; } ``` When I enter a value ofn = 5, I got some negative large number. Can anyone explain, please?
You've produced undefined behavior by passing the wrong type toprintf: the%dformat required a matching argument of typeintbut your argument has typedouble. You need%f(or%eor%gor%a) to print it. Also, there may be other problems, e.g. if you omitted#include <math.h>.
TheAND(&&) condition evaluates asOR(||) in this code. For ex., when user inputs numbers6and7, the output is12but when the I replace&&with||the output is42. ``` #include<stdio.h> int main() { int a,b,max,lcm; printf("Enter 2 numbers: "); scanf("%d %d", &a, &b); if(a>b) { max=a; } else { max=b; } do { max++; } while(max%a!=0 && max%b!=0); lcm=max; printf("LCM of %d and %d is %d\n", a,b,lcm); return 0; } ```
No, the&&condition is working as anandcondition, just as it should. When you input6and7,max%aevaluates to0whenmaxis12. At that pointmax%a != 0evaluates tofalse(false && true == false), andmax%a != 0 && max%b != 0evaluates tofalse, and your loop exits. However,max%a != 0 || max%b != 0evaluates totrue(max%bis5for amaxof12andbof7,false || true == true), so the loop continues.
I want to make a program which takes the input from the user in the form,__/__/____. What I made was ``` { int a, b, c,d,e,f; printf("Please Enter the *Joining Date* in the format DD/MM/YYYY\n"); scanf_s("%d""%d""%d", &a, &b, &c); printf("The Date you entered was %d/%d/%d\n", a, b, c); ``` What it does is, after each input the cursor moves to the new line. Please Any help will be appreciated.
Probably what you are looking for is ``` if (scanf("%d/%d/%d",&d,&m,&y) == 3) your_input_is_valid(); else your_input_is_invalid(); ``` this will ignore the"/"in the input. in the printf some chars are skiped like / because there is/n/tand other so to view DD/MM/YYYY you should use : ``` DD//MM//YYYY ```
I am printing a string such as: ``` printf("Print the number thirty: 30\n"); ``` If I make the following definition ``` #define THIRTY 30 ``` and now ``` printf("Print the number thirty: THIRTY"); ``` Does theCPre-processor replaceTHIRTY --> 30in the string? Or do I have to go: ``` printf("Print then number thirty: %d", THIRTY); ```
C Pre-processor doesnot understand what is inside String and hence does not manipulate string. The below statement will replaceTHIRTYwith30 ``` printf("Print then number thirty: %d", THIRTY); ```
I have a string that contains a 14-digit number. I want to convert the string to an int. When I use atoi(stringName), I get the max 32-bit in limitation. Example: String1 contains "201400000000" ``` long long tempNum1; tempNum1 = atoi(String1); printf("%d",tempNum1); ``` Output is: 2147483647 How can I turn this string into a number? I want to compare it to other strings of numbers and find which is the largest. (I have three strings of 14-digit numbers, I want to find which is the smallest, which is the largest).
atoireturns anint. Thatintis assigned to along long, but by then the limit has already been reached. You want to useatollwhich returns along long. And your printf format specifier is incorrect for your type.
``` #include <stdio.h> int main(void) { char *s = "Jordan"; printf("hello, %s\n, s"); } ``` Does anyone know a way that I can get this native C source code to work? I'm having trouble getting it to compile and run.
Your second quote is in the wrong place. Try: ``` printf("hello, %s\n", s); ```
I am currently learning C and want to check if my understanding of theforloop is correct. Does the outputA is 6occur because after the 5th time the loop is run, the +1 is added toa(which makes it 6), and then the condition is stopped because it is no longer<= 5? ``` int a; float b; b = 0; for (a = 1; a <= 5; a++) b = b + 0.5; printf ("A is %d\t\t B is %.2f\n", a, b); ``` Output is ``` A is 6 B is 2.50 ```
Yes. Whena == 5, the conditiona <= 5is true, so the body of the loop (b = b + 0.5;) is executed. After the body, thea++part is always executed. This makesa == 6. Then the conditiona <= 5isfalse, so the loop terminates. It is occasionally useful to use the value of the index after the loop.
I have a union defined as: ``` typedef union{ unsigned b_a: 1; unsigned b_b:1; unsigned b_c:1; int d_e; int option; int data[7]; }myUnion; ``` and I would like to declare and initialize an array of type myUnion: ``` myUnion myUnionArray[1] = { {.b_a=0, .b_b=0, .b_c=0, .d_e=5, .option=6} } ``` I've tried the above line to initialize the array but I keep get errors when compiling ("too many initializers"). Any idea what I am doing wrong?
I guess, You are confused with union and struct. Union - union is type whose members overlaps the storage and size of the union is the max size of any member. Hence you cannot initialize multiple simultaneously. Please find the difference betweenstruct and unionif you are interested in nested initialization, please followthisif you are interested in initialization of array, please followthis
So I have searched around for a bit on the answer to this question, which is probably incredibly simple, but I haven't found anything yet, so here's the issue: Something like this code here works just fine: ``` int main(void){ double x; x=ceil(5.5); } ``` But if I try this: ``` int main(void){ double x = 5.5; x=ceil(x); } ``` I get this error message: test.c:(.text+0x24): undefined reference to `ceil' Why is this and how can I send a variable to function 'ceil()' and then store it in another variable?
Two things: You need to#include <math.h>at the top of your file. You need to link with the math library by passing-lmto gcc: ``` gcc -o myprog myprog.c -lm ```
I was expecting error message (or atleast the warning) for multiple definition of variable var1 below. That means is this not a multiple definition? Is the scope of the variable inside the main is different from its scope outside the main. ``` #include <stdio.h> int var1; int main (void) { int var1; var1=12; printf("%d",var1); } ```
Is the scope of the variable inside the main is different from its scope outside the main. Yes. They are two different variables. Hence, there is no multiple variable definition error. Verify it using the following program: ``` #include <stdio.h> int var1; void foo(); int main (void) { int var1; var1=12; printf("%d\n",var1); foo(); } void foo() { var1=20; printf("%d\n",var1); } ```
Specifically, my question is, given this macro: ``` #define FAKE_VAL(type) ((type)0) ``` ...is there any value oftype(including structures, function pointers, etc.) whereFAKE_VAL(type)will cause a compile-time error? I'm asking because I have a macro that take a function pointer as an argument, and needs to find the size of its return value. I know the types and number of arguments the function pointer takes, so I'm planning to write something like: ``` sizeof(fptr(FAKE_VAL(arg_type_1), FAKE_VAL(arg_type_2))) ``` arg_type_1and2could be literally anything.
Of course there is. struct fred(i.e. not a pointer) - how do you convert 0 (scalar type) to a struct (non scalar type)? Any literal valueFAKE_VAL("hi")gives(("hi")0)- what does that mean?
Why doesnt it copy every line correctly fromafiletobfileinside the functioncopy()? The problem is inencr()method. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int copy(FILE *afile, FILE *bfile){ char line[100]; while(fgets(line, 100, line) != NULL){ fprintf(bfile, "%s\n", line); } return 1; } int main(int argc, char *argv[]) { FILE *afile; FILE *bfile; input = fopen(argv[1], "r"); output = fopen(argv[2], "w"); copy(input, output); fclose(output); } return 0; } ```
You need to parse the line in for loop, something like: ``` while(fgets(line, sizeof(line), input) != NULL){ for (index = 0; line[index] != 0; index++) { p = line[index]; ... ... fputc(c, output); //index++; remove this line } } ```
Does gethostbyaddr() function uses internet connection for converting ip address to hostname? Or it uses some cached data (like DNS cache)?
Yes. It does a DNS lookup, which may be satisfied by the local resolver's cache or may not.
``` void main() { int a; a=10; do while(a++<10); while(a++<=11); printf("%d",a); } ``` The above program gives an output of14. Can you please explain why?
This code will make you understand why , Whenever you type a++ its always incremented ``` void main() { int a; a=10; do{ while(a++<10); printf("%d",a); } while(a++<=11); printf("%d",a); } ```
I found a code like this: ``` #include <stdio.h> int main() { char buffer[20]; for(int i=0;i<20;i++) { memcpy(buffer+i, "H", 1); } } ``` What I don't understand is why there is : buffer + i and what does 1 mean at the end? Can anyone explain me
buffer + iis a pointer to a memory location at an offset ofichars frombuffer. It is equivalent to&buffer[i].The1at the end means copy 1 byte.Keep in mind that since you copy 1 byte only you are not copying the null terminating character of"H".
I wrote a program ``` #include<stdio.h> int main() { int x=3; if((x)==1,2,4,5,6) printf("number found in the list\n"); else printf("Number not found \n"); return 0; } ``` I was expecting the output to be "Number not found " but it is "Number found in the list " why it is so
The==operator has higher precedence than,, therefore the if-clause evaluates to ``` if (((x) == 1),2,4,5,6) ``` which is always true since the last "element" of the comma operator "counts" (6). From the C11 standard: The left operand of a comma operator is evaluated as avoidexpression [...]. Then the right operand is evaluated;the result has its type and value.
%d specifier inside the printf function means that we're going to display the variable as a decimal integer and %f specifier would display it as a float number and so on. But what does %di specifier does ? I found this specifier in this program(C program to add, subtract, multiply and divide Complex Numbers, complex arithmetic) For example, ``` printf("Division of two complex numbers = %d %di",temp1/temp3,temp2/temp3); ```
Iftemp/temp3evaluates to 25 andtemp2/temp3evaluates to 15, the line ``` printf("Division of two complex numbers = %d %di",temp1/temp3,temp2/temp3); ``` will print ``` Division of two complex numbers = 25 15i ``` Theiin the above format specifier prints the letteri. The%dparts print the numbers. The sole purpose of usingiin the above format specifier is to print the real and imaginary parts of a complex number in a more user friendly way.
I'm trying to dynamically create an array of ints for grades that are inside of a structure but I have a small syntax error. Here is my code: ``` typedef struct { int Stud_ID; int class_ID; int* Grades; int Grade_Cap; int Count; float Average; }enrollment; typedef struct { int Enrollment_Count; int Enrollment_Cap; enrollment *enrollment_list; }enrollments; void add_grade_space(enrollments *enroll) { enroll->enrollment_list[enroll->Enrollment_Count].Grade_Cap = malloc(sizeof(int)*2); } ``` The error I get says: assignment makes integer from pointer without cast.
``` enroll->enrollment_list[enroll->Enrollment_Count].Grade_Cap = malloc(sizeof(int)*2); ``` You are trying to allocate memory toGrade_Capwhich is not a pointer . It is an integer variable .You need to declare it asint *to allocate memory if you want to.
I'm a novice on programming and there are one unimportant but confusing problem that bothers me. Let me post my code first: ``` FILE *fp; int i; fp=fopen("test_data.txt", "r"); printf("i's address=%p\n", &i); printf("fp's address =%p\n", fp); printf("stdout's address=%p\n", stdout); close(fp); ``` The output is: ``` i's address=0x7ffd038ab8cc fp's address=0x231c010 stdout's address=0x7fbb2e4f7980 ``` My problem is that why is the fp's address 28-bit? Shouldn't it be the same as normal variables and standard output (48-bit)? I use GCC on 64-bit Ubuntu Linux. Thanks for your answers!
The most likely case here is that your file adress simply starts with zeros, which are omitted by default. Edit:Hereis a question that points to a similar kind of problem.
In this program here: ``` #include <stdio.h> int main(void) { char ch = 'A'; char* ptr = &ch; ptr[8] = 'B'; printf("ptr[8] = %c\n", ptr[8]); *ptr = 'C'; printf("*ptr = %c\n", *ptr); } ``` The output: ``` ptr[8] = B *ptr = C Segmentation fault (core dumped) ``` I supposed that the program should segfault at the lineptr[8] = 'B';and crash, but the program did execute all the lines of code in it and then crashed which is something I don't really get. Shouldn't it crash at the lineptr[8] = 'B';and stop the execution there ?
By writing intoptr[8], you probably scribbled over the return address of whatever function calledmain, so the processor tried to jump to a weird place. Core didn't like it and took a huge dump.
``` #include <stdio.h> void main() { char *s= "hello"; char *p = s; printf("%c\t%c", p[0], s[1]); } ``` output of this program is : h e Can anyone please explain how this program is working? I'm relatively new to c..
p[0]is identical to*(p+0), similarly goes fors[1].[]always operates on a pointer and is same for arrays and pointers. Note- There is no array declared in your program.
``` #include <stdio.h> int main(){ printf("asd"); return 0; } ``` The task is without modifying this program, overwriting or using define, in windows environment, this program have to write out : Yourname asd Yourname. Any idea?
You can do it like this (edited to readYournamefrom stdin): ``` #include <stdio.h> #include <string.h> int main(){ printf("asd"); return 0; } int printf(const char *__restrict __format, ...) { char str[106], scs[50]; scanf("%s", &scs); strcpy(str,scs); puts(strcat(strcat(strcat(strcat(str," "), __format)," "),scs)); return 1; } ``` Here's aworking demo.
I wrote a program ``` #include<stdio.h> int main() { int x=3; if((x)==1,2,4,5,6) printf("number found in the list\n"); else printf("Number not found \n"); return 0; } ``` I was expecting the output to be "Number not found " but it is "Number found in the list " why it is so
The==operator has higher precedence than,, therefore the if-clause evaluates to ``` if (((x) == 1),2,4,5,6) ``` which is always true since the last "element" of the comma operator "counts" (6). From the C11 standard: The left operand of a comma operator is evaluated as avoidexpression [...]. Then the right operand is evaluated;the result has its type and value.
%d specifier inside the printf function means that we're going to display the variable as a decimal integer and %f specifier would display it as a float number and so on. But what does %di specifier does ? I found this specifier in this program(C program to add, subtract, multiply and divide Complex Numbers, complex arithmetic) For example, ``` printf("Division of two complex numbers = %d %di",temp1/temp3,temp2/temp3); ```
Iftemp/temp3evaluates to 25 andtemp2/temp3evaluates to 15, the line ``` printf("Division of two complex numbers = %d %di",temp1/temp3,temp2/temp3); ``` will print ``` Division of two complex numbers = 25 15i ``` Theiin the above format specifier prints the letteri. The%dparts print the numbers. The sole purpose of usingiin the above format specifier is to print the real and imaginary parts of a complex number in a more user friendly way.
I'm trying to dynamically create an array of ints for grades that are inside of a structure but I have a small syntax error. Here is my code: ``` typedef struct { int Stud_ID; int class_ID; int* Grades; int Grade_Cap; int Count; float Average; }enrollment; typedef struct { int Enrollment_Count; int Enrollment_Cap; enrollment *enrollment_list; }enrollments; void add_grade_space(enrollments *enroll) { enroll->enrollment_list[enroll->Enrollment_Count].Grade_Cap = malloc(sizeof(int)*2); } ``` The error I get says: assignment makes integer from pointer without cast.
``` enroll->enrollment_list[enroll->Enrollment_Count].Grade_Cap = malloc(sizeof(int)*2); ``` You are trying to allocate memory toGrade_Capwhich is not a pointer . It is an integer variable .You need to declare it asint *to allocate memory if you want to.
I'm a novice on programming and there are one unimportant but confusing problem that bothers me. Let me post my code first: ``` FILE *fp; int i; fp=fopen("test_data.txt", "r"); printf("i's address=%p\n", &i); printf("fp's address =%p\n", fp); printf("stdout's address=%p\n", stdout); close(fp); ``` The output is: ``` i's address=0x7ffd038ab8cc fp's address=0x231c010 stdout's address=0x7fbb2e4f7980 ``` My problem is that why is the fp's address 28-bit? Shouldn't it be the same as normal variables and standard output (48-bit)? I use GCC on 64-bit Ubuntu Linux. Thanks for your answers!
The most likely case here is that your file adress simply starts with zeros, which are omitted by default. Edit:Hereis a question that points to a similar kind of problem.
In this program here: ``` #include <stdio.h> int main(void) { char ch = 'A'; char* ptr = &ch; ptr[8] = 'B'; printf("ptr[8] = %c\n", ptr[8]); *ptr = 'C'; printf("*ptr = %c\n", *ptr); } ``` The output: ``` ptr[8] = B *ptr = C Segmentation fault (core dumped) ``` I supposed that the program should segfault at the lineptr[8] = 'B';and crash, but the program did execute all the lines of code in it and then crashed which is something I don't really get. Shouldn't it crash at the lineptr[8] = 'B';and stop the execution there ?
By writing intoptr[8], you probably scribbled over the return address of whatever function calledmain, so the processor tried to jump to a weird place. Core didn't like it and took a huge dump.
``` #include <stdio.h> void main() { char *s= "hello"; char *p = s; printf("%c\t%c", p[0], s[1]); } ``` output of this program is : h e Can anyone please explain how this program is working? I'm relatively new to c..
p[0]is identical to*(p+0), similarly goes fors[1].[]always operates on a pointer and is same for arrays and pointers. Note- There is no array declared in your program.
``` #include <stdio.h> int main(){ printf("asd"); return 0; } ``` The task is without modifying this program, overwriting or using define, in windows environment, this program have to write out : Yourname asd Yourname. Any idea?
You can do it like this (edited to readYournamefrom stdin): ``` #include <stdio.h> #include <string.h> int main(){ printf("asd"); return 0; } int printf(const char *__restrict __format, ...) { char str[106], scs[50]; scanf("%s", &scs); strcpy(str,scs); puts(strcat(strcat(strcat(strcat(str," "), __format)," "),scs)); return 1; } ``` Here's aworking demo.
I'm a novice on programming and there are one unimportant but confusing problem that bothers me. Let me post my code first: ``` FILE *fp; int i; fp=fopen("test_data.txt", "r"); printf("i's address=%p\n", &i); printf("fp's address =%p\n", fp); printf("stdout's address=%p\n", stdout); close(fp); ``` The output is: ``` i's address=0x7ffd038ab8cc fp's address=0x231c010 stdout's address=0x7fbb2e4f7980 ``` My problem is that why is the fp's address 28-bit? Shouldn't it be the same as normal variables and standard output (48-bit)? I use GCC on 64-bit Ubuntu Linux. Thanks for your answers!
The most likely case here is that your file adress simply starts with zeros, which are omitted by default. Edit:Hereis a question that points to a similar kind of problem.
In this program here: ``` #include <stdio.h> int main(void) { char ch = 'A'; char* ptr = &ch; ptr[8] = 'B'; printf("ptr[8] = %c\n", ptr[8]); *ptr = 'C'; printf("*ptr = %c\n", *ptr); } ``` The output: ``` ptr[8] = B *ptr = C Segmentation fault (core dumped) ``` I supposed that the program should segfault at the lineptr[8] = 'B';and crash, but the program did execute all the lines of code in it and then crashed which is something I don't really get. Shouldn't it crash at the lineptr[8] = 'B';and stop the execution there ?
By writing intoptr[8], you probably scribbled over the return address of whatever function calledmain, so the processor tried to jump to a weird place. Core didn't like it and took a huge dump.
``` #include <stdio.h> void main() { char *s= "hello"; char *p = s; printf("%c\t%c", p[0], s[1]); } ``` output of this program is : h e Can anyone please explain how this program is working? I'm relatively new to c..
p[0]is identical to*(p+0), similarly goes fors[1].[]always operates on a pointer and is same for arrays and pointers. Note- There is no array declared in your program.
``` #include <stdio.h> int main(){ printf("asd"); return 0; } ``` The task is without modifying this program, overwriting or using define, in windows environment, this program have to write out : Yourname asd Yourname. Any idea?
You can do it like this (edited to readYournamefrom stdin): ``` #include <stdio.h> #include <string.h> int main(){ printf("asd"); return 0; } int printf(const char *__restrict __format, ...) { char str[106], scs[50]; scanf("%s", &scs); strcpy(str,scs); puts(strcat(strcat(strcat(strcat(str," "), __format)," "),scs)); return 1; } ``` Here's aworking demo.
Is it possible to usesscanfto read the char stringsin the example below as two 10-chars (including the blank space) wide floats? Or do I have to copy chunks of 10 chars to a temporary char array and usesscanfon that temp array? ``` #include <stdio.h> int main( int argc, const char* argv[] ) { char s[]={" 6.4887.0522e+06"}; float f1, f2; sscanf(s, "%10f%10f", &f1, &f2); printf("%10f %10f\n", f1, f2); } ``` My wish in this example is to getf1 = 6.448andf2 = 7052200.from thesscanfread.
Ifs[]is notconst, temporarily makes[10] = 0. ``` void foo(char *s) { while (*s) { size_t length = strlen(s); char temp = 0; if (length > 10) { length = 10; temp = s[10]; s[10] = 0; } float f1; if (sscanf(s, "%f", &f1) == 1) printf("%f\n", f1); s += length; s[0] = temp; } } ```
I have read a lot of ideas how to convert a single char of a string to an integer but I'm struggling with pointers in C. I am guessing at something like: ``` strftime(buffer, sizeof("0000"), "%H%M", tick_time); onedigit = atoi(&buffer[1]); ``` So I want to have the first digit of the time converted into an integer. If you have a more "elegant" way to do it - let me know.
To get the first character as an integer you want: ``` onedigit = buffer[0] - '0'; ``` This takes the first (usually ASCII) character, subtracts the (ASCII) value for0, leaving you with an integer value in the range 0..9. You can easily do the same thing for other numeric characters in the string, e.g. to get the tens digit: ``` tensdigit = buffer[1] - '0'; ```
How this works(sets all values to 0)? ``` int array[28]= {0}; ``` and why this not works(does not set all values to 4 but only the first value sets to 4 and others to 0)? ``` int array[28]= {4}; ```
The elements which are not initialized are set 0. In your first case you are initilizing it by providing it the value as 0 and rest are by default initialized as 0. In your second case the first values is intialized with 4 and rest as 0. The standard says: If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
I have a little C program where I am forking a new process and I want to execute a Jar file there. This is the exec call: ``` execl("/usr/bin/java", "-jar", "/home/user/path/file.jar", NULL) ``` But I get an error: ``` Error: Could not find or load main class .home.user.path.file.jar ``` If I run the same command from command line the Jar runs without problems. I already checked the manifest file, everything is fine there. So I have no idea why the slashes in the path are transformed into dots, leading to the error. Can anyone shed light on this issue?
Notice that execl takes "path" and "argv0" as two separate arguments, even though one usually thinks of them as the same thing. I.e, you typically need something like ``` execl("/usr/bin/java", "/usr/bin/java", "-jar", "foo.jar", NULL); ```
I need to find the length of an array, how would I do this without using thesizeoffunction. eg if ``` Array 1 = [0 1 2 3 4 5 6] ``` the size of this array would be7.
If you can't usesizeof(tell us why, please), you can use a loop and a sentinel (-1 or some number that can not be used in the array): ``` int arr[] = {0, 1, 2, 3, 4, 5, 6, -1}; int count = 0; while (arr[count] != -1) count++; ```
I have a little confusion. ``` struct node *p; and if(p==NULL) ``` Now what I have gathered based upon my studies is that NULL is not a memory address but a value (i.e 0) in the memory address. When I useif(*p==NULL)it gives an error - no match for 'operator=='. But doesn't*pgives the value in the memory address. If we just useparen't we comparing a memory address with a value in the memory address. Why isp==NULLcorrect while*p=NULLis not.
Yes,*pgives the value in a memory address. But in this case, that value is astruct nodebecausepis of type "pointer to struct node". You can't compare a structure's value to NULL.
I am pretty new to C, I used the search function but I didn't have any luck finding the legality and the use of && in C. The question that this arises from is quite vague and some insight would be great! Is the expression on the second line legal? Why or why not? What does it mean? ``` int x; ... &&x ... ``` From what I have been able to come up with and search around for was that this is a legal statement and it gets the address of the label x , although to me this does not seem like the correct representation.
It could be legal, but not in the way you're thinking. &&is the "logical and" operator. Itcouldbe legal in your example depending on what's in the....As a unary "address of" operator it's not legal, since&xwill be an "rvalue" and not define storage. Therefore, a second&will not be allowed.
Is there a way to pop the address of the top of the stack and not the content? I want the address into a register and use it to manipulate program later.
In AT&T syntax: ``` leaq (%rsp), %rax ``` In Intel syntax: ``` leaq rax, [rsp] ``` or whatever register you need to use.raxis provided only as an example. Theleacommand loads theaddressspecified into the register, not thecontent. For more information, seeWhat's the purpose of the LEA instruction? You also could do this with a simplemov: ``` mov %rsp, %rax ``` or ``` mov rax, rsp ``` If you need to actually modify the stack pointer, you can simply add the number of bytes necessary to it.
I have read a lot of ideas how to convert a single char of a string to an integer but I'm struggling with pointers in C. I am guessing at something like: ``` strftime(buffer, sizeof("0000"), "%H%M", tick_time); onedigit = atoi(&buffer[1]); ``` So I want to have the first digit of the time converted into an integer. If you have a more "elegant" way to do it - let me know.
To get the first character as an integer you want: ``` onedigit = buffer[0] - '0'; ``` This takes the first (usually ASCII) character, subtracts the (ASCII) value for0, leaving you with an integer value in the range 0..9. You can easily do the same thing for other numeric characters in the string, e.g. to get the tens digit: ``` tensdigit = buffer[1] - '0'; ```
How this works(sets all values to 0)? ``` int array[28]= {0}; ``` and why this not works(does not set all values to 4 but only the first value sets to 4 and others to 0)? ``` int array[28]= {4}; ```
The elements which are not initialized are set 0. In your first case you are initilizing it by providing it the value as 0 and rest are by default initialized as 0. In your second case the first values is intialized with 4 and rest as 0. The standard says: If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
I have a little C program where I am forking a new process and I want to execute a Jar file there. This is the exec call: ``` execl("/usr/bin/java", "-jar", "/home/user/path/file.jar", NULL) ``` But I get an error: ``` Error: Could not find or load main class .home.user.path.file.jar ``` If I run the same command from command line the Jar runs without problems. I already checked the manifest file, everything is fine there. So I have no idea why the slashes in the path are transformed into dots, leading to the error. Can anyone shed light on this issue?
Notice that execl takes "path" and "argv0" as two separate arguments, even though one usually thinks of them as the same thing. I.e, you typically need something like ``` execl("/usr/bin/java", "/usr/bin/java", "-jar", "foo.jar", NULL); ```
I need to find the length of an array, how would I do this without using thesizeoffunction. eg if ``` Array 1 = [0 1 2 3 4 5 6] ``` the size of this array would be7.
If you can't usesizeof(tell us why, please), you can use a loop and a sentinel (-1 or some number that can not be used in the array): ``` int arr[] = {0, 1, 2, 3, 4, 5, 6, -1}; int count = 0; while (arr[count] != -1) count++; ```
I have a little confusion. ``` struct node *p; and if(p==NULL) ``` Now what I have gathered based upon my studies is that NULL is not a memory address but a value (i.e 0) in the memory address. When I useif(*p==NULL)it gives an error - no match for 'operator=='. But doesn't*pgives the value in the memory address. If we just useparen't we comparing a memory address with a value in the memory address. Why isp==NULLcorrect while*p=NULLis not.
Yes,*pgives the value in a memory address. But in this case, that value is astruct nodebecausepis of type "pointer to struct node". You can't compare a structure's value to NULL.
I am pretty new to C, I used the search function but I didn't have any luck finding the legality and the use of && in C. The question that this arises from is quite vague and some insight would be great! Is the expression on the second line legal? Why or why not? What does it mean? ``` int x; ... &&x ... ``` From what I have been able to come up with and search around for was that this is a legal statement and it gets the address of the label x , although to me this does not seem like the correct representation.
It could be legal, but not in the way you're thinking. &&is the "logical and" operator. Itcouldbe legal in your example depending on what's in the....As a unary "address of" operator it's not legal, since&xwill be an "rvalue" and not define storage. Therefore, a second&will not be allowed.
Is there a way to pop the address of the top of the stack and not the content? I want the address into a register and use it to manipulate program later.
In AT&T syntax: ``` leaq (%rsp), %rax ``` In Intel syntax: ``` leaq rax, [rsp] ``` or whatever register you need to use.raxis provided only as an example. Theleacommand loads theaddressspecified into the register, not thecontent. For more information, seeWhat's the purpose of the LEA instruction? You also could do this with a simplemov: ``` mov %rsp, %rax ``` or ``` mov rax, rsp ``` If you need to actually modify the stack pointer, you can simply add the number of bytes necessary to it.
I have a little confusion. ``` struct node *p; and if(p==NULL) ``` Now what I have gathered based upon my studies is that NULL is not a memory address but a value (i.e 0) in the memory address. When I useif(*p==NULL)it gives an error - no match for 'operator=='. But doesn't*pgives the value in the memory address. If we just useparen't we comparing a memory address with a value in the memory address. Why isp==NULLcorrect while*p=NULLis not.
Yes,*pgives the value in a memory address. But in this case, that value is astruct nodebecausepis of type "pointer to struct node". You can't compare a structure's value to NULL.
I am pretty new to C, I used the search function but I didn't have any luck finding the legality and the use of && in C. The question that this arises from is quite vague and some insight would be great! Is the expression on the second line legal? Why or why not? What does it mean? ``` int x; ... &&x ... ``` From what I have been able to come up with and search around for was that this is a legal statement and it gets the address of the label x , although to me this does not seem like the correct representation.
It could be legal, but not in the way you're thinking. &&is the "logical and" operator. Itcouldbe legal in your example depending on what's in the....As a unary "address of" operator it's not legal, since&xwill be an "rvalue" and not define storage. Therefore, a second&will not be allowed.
Is there a way to pop the address of the top of the stack and not the content? I want the address into a register and use it to manipulate program later.
In AT&T syntax: ``` leaq (%rsp), %rax ``` In Intel syntax: ``` leaq rax, [rsp] ``` or whatever register you need to use.raxis provided only as an example. Theleacommand loads theaddressspecified into the register, not thecontent. For more information, seeWhat's the purpose of the LEA instruction? You also could do this with a simplemov: ``` mov %rsp, %rax ``` or ``` mov rax, rsp ``` If you need to actually modify the stack pointer, you can simply add the number of bytes necessary to it.
``` for(i=0;i++<10;) { printf("%d\n",i); } ``` Why is it printing 1 to 10? I know post increment happens after a loop, so why is it not showing 0? And why is it showing 10?
Let's label the elements of the loop: ``` for(/* 1 */ i=0; /* 2 */ i++<10; /* 4 */) { /* 3 */ printf("%d\n",i); } ``` Here's how things play out: iis initialized to0;The result ofi++is compared to10; as aside effectof this expression,iis incremented by1;The updated value ofiis printed out;If there were an expression here, it would be evaluated. Steps 2 through 4 are repeated untili++ < 10evaluates to false.
This question already has answers here:C pointer to array/array of pointers disambiguation(12 answers)Closed7 years ago. The first declaration is commonly referred to as an array of pointers. Does the second declaration have a name or description that distinguishes it from the first declaration? Declaration 1:int *p[SIZE] Declaration 2:int (*p)[SIZE]
``` int *p[SIZE] ``` This is to declare array ofSIZEnumber of pointers toint Whereas , this - ``` int (*p)[SIZE] ``` declarepas pointer to array of int (havingSIZEnumber of elements)
Why in this expression increment is evaluated after multiplication? It has higher precedence. y = x * z++; EDIT: Another example ``` int i[] = {3, 5}; int *p = i; int j = --*p++; ``` is equivalent to ``` int j = postincrement(--*p); ```
z++is more or less the same as: ``` int postincrement(int *z) { int temp = *z; *z++; return temp; } ``` So your code is more or less equivalent to: ``` y = x * z; z = z + 1; ```
I have installed codeblocks in windows 7 first time and try to run a simple C program but I get this error? can't find compiler executable in your search path (GNU GCC compiler) I tried many things to solve it but unable to compile.
Have you installed the Mingw compiler or any other simiar compiler? If not install that first. After you have done so, you need to set codeblocks to use that compiler. You can do that by going to thesettings>compiler settingsand set the necessary options there. You may need to refer the place where you have installed Mingw or other compiler. Note the compiler executable isgccfor C andg++for C++ and the linker isldi guess. Debugger isgdb. You need to tell codeblocks where are these located.
This question already has answers here:Correct format specifier to print pointer or address?(6 answers)Closed7 years ago. I want to create a program that prints the address of an int, a float and a double. ``` int main() { int a; float b; double c; printf("\na:%d \nb:%f \nc:%lf", &a, &b, &c); } ``` But in the end all I get is the address of the int. For the other two the answer is 0.00000.
Use specifier%pto print address. ``` printf("\na:%p \nb:%p \nc:%p",(void *)&a,(void *)&b,(void *)&c); ```
``` #include<stdio.h> #define PRINT(a,b) (while(a<b){printf("%d < %d\n",a,b); ++a;}) int main(void) { PRINT(1,5); return 0; } ``` I am getting a expression syntax error for the linePRINT(1,5);
The C compiler is seeing the code output fromC language preprocessor. You can run the preprocessor directly to figure out which part of the processed code is the compiler having trouble with. Once you understand how the preprocessor works, you will be able to spot such errors without having to do this. In my gnu gcc environment,cppdoes the job: % cpp <your source file name> Will print lots of code but at the end, you will see ``` int main(void) { (while(1<5){printf("%d < %d\n",1,5); ++1;}); return 0; } ``` Do you see what is wrong here? while statement is not an expression, so it cannot be enclosed in (). Next, ++1 is not allowed because1=1+1does not make sense. You need to use a variable.
This question already has answers here:What are the differences between if, else, and else if? [closed](17 answers)Closed7 years ago. what we can do with 'else if 'that we cant do with 'else' in c language if(----){ ``` printf("--"); }else{ } ``` and ``` if(----){ printf("--"); }else if("---"){ } ```
Your Question is Simple.. If and else are used, When you make a true or false statements. Example: ``` If ( 3>2) { printf ("3");} else { printf ( "2");} ``` But in case ofif and else if Example: ``` if(3>2) {printf ("3");} else if (2>3) {printf ("false");} ``` IN THIS WAY .. In else if. you should have a condition and it executes only when it is true.. but in case of else ..it is executed when if condition is false ..
I am trying to make program for rssi measurement in cooja. Recently, I found that the makefile is a must for running the programs, but the /contiki/examples has so many examples with different makefile contents. For instance, "collect" uses certain apps in makefile. How to understand the apps and tools needed for my work? Please explain.
I'm afraid that this is a too generic question to answer here. You'll have to spend some time to learn about makefiles. Google for "writing makefiles". Then you might want to do some research, instead of letting others do you homework and come acrosshttps://github.com/contiki-os/contiki/wiki/Contiki-Build-System. Oh, and before you do RSSI-Measurements in Cooja you probably want to do some research on simulation of RSSI-values - with Cooja in particular, too.
I have a file as such: ``` #include <stdio.h> #include <string.h> #include <stdlib.h> #define DEBUG int main(void) { #ifdef DEBUG printf("We are in debug mode"); #endif } ``` I was told to use ifdef and endif (for this). My problem occurs when I compile this, using a makefile(Which I'm not allowed to edit). What happens is the print statement (Debug one) prints, which shouldn't because I'm not in DEBUG mode. I tried to use this command (On Ubuntu 14.04) make -DEBUG But that did something completely different, and the output file, prints the ifdef statement, despite not being in DEBUG mode. What am I doing wrong?
You are explicitly defining DEBUG in your source file ``` #define DEBUG ``` Remove that line so that you are not overriding any definition from your build environment.
I am trying to make program for rssi measurement in cooja. Recently, I found that the makefile is a must for running the programs, but the /contiki/examples has so many examples with different makefile contents. For instance, "collect" uses certain apps in makefile. How to understand the apps and tools needed for my work? Please explain.
I'm afraid that this is a too generic question to answer here. You'll have to spend some time to learn about makefiles. Google for "writing makefiles". Then you might want to do some research, instead of letting others do you homework and come acrosshttps://github.com/contiki-os/contiki/wiki/Contiki-Build-System. Oh, and before you do RSSI-Measurements in Cooja you probably want to do some research on simulation of RSSI-values - with Cooja in particular, too.
I have a file as such: ``` #include <stdio.h> #include <string.h> #include <stdlib.h> #define DEBUG int main(void) { #ifdef DEBUG printf("We are in debug mode"); #endif } ``` I was told to use ifdef and endif (for this). My problem occurs when I compile this, using a makefile(Which I'm not allowed to edit). What happens is the print statement (Debug one) prints, which shouldn't because I'm not in DEBUG mode. I tried to use this command (On Ubuntu 14.04) make -DEBUG But that did something completely different, and the output file, prints the ifdef statement, despite not being in DEBUG mode. What am I doing wrong?
You are explicitly defining DEBUG in your source file ``` #define DEBUG ``` Remove that line so that you are not overriding any definition from your build environment.
The piece of code was : ``` if(a[i] > a[j]){ temp = a[i]; a[i] = a[j]; a[j] = temp; } ``` Why a temp variable has to be used ? When I try without temp : ``` if(a[i] > a[j]){ a[i] = a[j]; } ``` it wont work, but before it was working when I compare other variables
If you don't have this temp variable ``` temp = a[i]; a[i] = a[j]; a[j] = temp; ``` then you will lose the value that was ina[i](previous to the assignmenta[i] = a[j]. There is a way to swap values without having the using a temporal value. The solution ishere. In C is like this: ``` int x = 10, y = 5; // Code to swap 'x' (1010) and 'y' (0101) x = x ^ y; // x now becomes 15 (1111) y = x ^ y; // y becomes 10 (1010) x = x ^ y; // x becomes 5 (0101) ``` Using the XOR operator. Code is fromhere, go to that link to find the entire explanation and possible drawbacks of using this solution.
``` static int i = 2; union U { int a, b; char c[3]; }u; int main(){ u.b = 0x6; for(;i; u.b++) u.b = u.a << i--; printf("%d %o %s", u.a, u.b, u.c); return 0; } ``` This code gives the output for the character array as 3. Now I know that this code poses severalUndefined Behaviourspecially when I am a storing into one variable and accessing of some other, but just for the purpose of experiment, can anybody explain to me whyu.chas a value of3. Note: Internal memory structure would be better to understand this
After the for loop the unionucontains the bits: ``` 0x00000033 ``` which split into chars are ``` 0x33 0x00 0x00 ``` so ``` c[0]=0x33 c[1]=0x00 c[2]=0x00 ``` and 0x33 happens to be the ASCII code for the digit '3';
I correctly read values from some positions in my file, but I'm getting problem when I need to rewrite those values. It all messes up in file, after what my file reader doesn't find what he needs at required positions. Is there some way to overwrite the whole line, and to avoid these situations? I am using lseek() function to move file pointer to position I need.
Since you say "line", I assume you're talking about text files. In that case: no, there's no way to overwrite a single line,exceptif the new line you want to write isexactlythe same length. This is because the file abstraction on disk doesn't work like editing a file in e.g. a text editor, you can't do insert/delete in the middle without re-writing all the trailing data after the point of the change. In general you need to construct the change in memory and overwrite the entire file (or at least the part starting with the change).
I have a C program like this ``` #include <stdio.h> void print_int() { int i; i++; printf("%d\n",i); } int main() { print_int(); print_int(); return 0; } ``` The output returned by this program is ``` 1 2 ``` I have a doubt regarding this output. Shouldn't this be two garbage values because the variable i is not initialized ?
You are getting undefined behavior. Probably the variableiresides in the same physical memory location on each invocation, it happens to be cleared on startup, and nothing is writing garbage there so you're seeing those particular values. If you were to call some other function between the two calls toprint_int(), results would very likely differ. That's just "luck" of course, and this program is broken.
I have a string which I break up into pieces usingstrtok ``` d.dtype = strtok(incoming.mtext, "|"); d.threshold= strtok(NULL, "|"); d.pid = strtok(NULL, "|"); ``` Using ``` printf("device type %s\n", d.dtype); printf("device threshold %s\n", d.threshold); printf("device pid %s\n", d.pid); ``` I can see everything was assigned correctly. I'm then sending an outgoing message, my message structure is ``` struct msg_st { long int mtype; char mtext[BUFSIZ]; }; struct msg_st outgoing; ``` How can I copy thed.pidvalue to myoutgoing.mtype?
You can extractintvalue fromchar *by usingatoifrom<stdlib.h> ``` outgoing.mtype = atoi(d.pid); ```
``` static int i = 2; union U { int a, b; char c[3]; }u; int main(){ u.b = 0x6; for(;i; u.b++) u.b = u.a << i--; printf("%d %o %s", u.a, u.b, u.c); return 0; } ``` This code gives the output for the character array as 3. Now I know that this code poses severalUndefined Behaviourspecially when I am a storing into one variable and accessing of some other, but just for the purpose of experiment, can anybody explain to me whyu.chas a value of3. Note: Internal memory structure would be better to understand this
After the for loop the unionucontains the bits: ``` 0x00000033 ``` which split into chars are ``` 0x33 0x00 0x00 ``` so ``` c[0]=0x33 c[1]=0x00 c[2]=0x00 ``` and 0x33 happens to be the ASCII code for the digit '3';
I correctly read values from some positions in my file, but I'm getting problem when I need to rewrite those values. It all messes up in file, after what my file reader doesn't find what he needs at required positions. Is there some way to overwrite the whole line, and to avoid these situations? I am using lseek() function to move file pointer to position I need.
Since you say "line", I assume you're talking about text files. In that case: no, there's no way to overwrite a single line,exceptif the new line you want to write isexactlythe same length. This is because the file abstraction on disk doesn't work like editing a file in e.g. a text editor, you can't do insert/delete in the middle without re-writing all the trailing data after the point of the change. In general you need to construct the change in memory and overwrite the entire file (or at least the part starting with the change).
I have a C program like this ``` #include <stdio.h> void print_int() { int i; i++; printf("%d\n",i); } int main() { print_int(); print_int(); return 0; } ``` The output returned by this program is ``` 1 2 ``` I have a doubt regarding this output. Shouldn't this be two garbage values because the variable i is not initialized ?
You are getting undefined behavior. Probably the variableiresides in the same physical memory location on each invocation, it happens to be cleared on startup, and nothing is writing garbage there so you're seeing those particular values. If you were to call some other function between the two calls toprint_int(), results would very likely differ. That's just "luck" of course, and this program is broken.
I have a string which I break up into pieces usingstrtok ``` d.dtype = strtok(incoming.mtext, "|"); d.threshold= strtok(NULL, "|"); d.pid = strtok(NULL, "|"); ``` Using ``` printf("device type %s\n", d.dtype); printf("device threshold %s\n", d.threshold); printf("device pid %s\n", d.pid); ``` I can see everything was assigned correctly. I'm then sending an outgoing message, my message structure is ``` struct msg_st { long int mtype; char mtext[BUFSIZ]; }; struct msg_st outgoing; ``` How can I copy thed.pidvalue to myoutgoing.mtype?
You can extractintvalue fromchar *by usingatoifrom<stdlib.h> ``` outgoing.mtype = atoi(d.pid); ```
This question already has answers here:extern on function prototypes?(3 answers)Closed7 years ago. Please explain why it usesexternin function declaration? main.c ``` ... pthread_create(&displayThread, &attr, displayThrFxn, &displayEnv); ... ``` display.h ``` extern Void *displayThrFxn(Void *arg); ``` Whyextern? display.c ``` ... Void *displayThrFxn(Void *arg) { // some code } ... ```
The use ofexternhere is kind of redundant. By default, if nothing is specified, functions have external linkage. QuotingC11standard, chapter §6.2.3 If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifierextern. [...]
How would I go about writing a C program that lists ALL the contents of stack and heap including its own variables and mallocations ? The purpose of it is for me to be able to see what's going on in the memory as I write and test code.
The c standard doesn't explicitly mention a stack or a heap. That, along with the fact that variable and function names are compiled out, means that your task is impossible. Youcouldbuild your own compiler which would effectively be a debugging tool. But that would be ridiculous as such a thing would take a long time to build and you'd have to adapt it constantly as the standard evolves. Or you could use the output of a compiler that generates debugging symbols. Better still, learn to use a good debugger.
Inctype.h, line 20,__ismaskis defined as: ``` #define __ismask(x) (_ctype[(int)(unsigned char)(x)]) ``` What does(int)(unsigned char)(x)do? I guess it castsxto unsigned char (to retrieve the first byte only regardless ofx), but then why is it cast to anintat the end?
(unsigned char)(x)effectively computes anunsigned charwith the value ofx % (UCHAR_MAX + 1). This has the effect of giving a non-negative value (between0andUCHAR_MAX). With most implementationsUCHAR_MAXhas a value of255(although the standard permits anunsigned charto support a larger range, such implementations are uncommon). Since the result of(unsigned char)(x)is guaranteed to be in the range supported by anint, the conversion tointwill not change value. Net effect is the least significant byte, with a positive value. Some compilers give a warning when using achar(signed or not) type as an array index. The conversion tointshuts those compilers up.
So I have a.dllfile that was built via Matlab on Windows and I would like to run it on a C/C++ program I've created. Is that possible at all? I know I can run it on windows like this: ``` #include <windows.h> ... HINSTANCE hinstLib; hinstLib = LoadLibrary(TEXT("MyPuts.dll")); ... ``` Butwindows.his not available on Linux/OSX, is there any other way? Alternatively is there any other format I can build the Matlab library in? Maybe.sois that an option?
I do think that would be problamatic. As the Wauzl comment suggest you should compile it to .so if possible. Another option would be to run the entire program compiled for windows under wine. I havent checked out winelib myself, but maybe it might be worth a lookWinelib guide Winelib is a development toolkit which allows you to compile your Windows applications on Unix.
I pass a pointer of a given type to a function. In the function I allocate the memory needed: ``` Pointer = (mytype * ) malloc (N* sizeof (mytype)); ``` And it all goes well. After the function ends another one calls pointer. But the previously filled pointer is now without memory. Shouldn't pointer have kept its filled memory? Or does the ending of a function deallocate the memory? Sorry but I am unable to paste my code because I work on a non connected PC.
No. Memory allocated by malloc is not deallocated at the end of a function. Otherwise, that would be a disaster, because you would be unable to write a function that creates a data structure by allocating memory for it, filling it with data, and returning it to the caller.
I am taking CS420 - Operating Systems. My professor mentioned something in class the other day that peaked my interest and I have been researching it and have gotten close but cannot find out the answer. He mentioned that him and another professor had wondered in the past if the creation of the ++/-- operators was originally intended to bind the ++/-- operators to the test-and-set operation/instruction. He said that they weren't able to figure it out. I didn't ask him how much effort they had invested in this but would be very interested in the communities input.
C is a platform independent language and designed as such. It was designed to compile against various machine languages and architectures, so it's difficult imagine they were counting on a test-and-set instruction or any CPU family-specific instruction in particular.
main.c ``` List L; Initialize(&L); printf("%d\n", Size(&L)); ``` list.c ``` void Initialize (List *L) { L = malloc(sizeof(List)); if (L == NULL) { perror("Unable to create memory for list. Exiting."); exit(1); } L->size = 0; } int Size (List *L) { return L->size; } ``` What I want outputted would be a size of '0', however what I am getting is the max int sizeof '2673724'. I am kind of confused at this point what is wrong with my code. Looking with gdb it looks like the Initialize() function is not actually modifying the List's size as it remains the same before and after entering the function. Did I do something wrong?
ThisInitializefunction ignore the argument, allocate a buffer, write something to it, throw it away and cause memory leak. Try this simple function using the same way asSize: ``` void Initialize (List *L) { L->size = 0; } ```