question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I have installed latest release of msys2 (msys2-x86_64-20161025). When I am runningpacman -SyuuI am getting:
and if I answeryI get after:
What should I answer these questions?
About runningpacman -Syuuafter installation of msys2 I read here:https://github.com/msys2/msys2/wiki/MSYS2-installation
|
You can answer "yes" to everything, and/or remove catgets beforehand withpacman -R libcatgets.
Relevant support ticket. They seem to be in the process of removing all dependencies to libcatgets.
|
how can i copy a double type array into an another double type array in c
here is a part of code:
```
int main(int argc, chae *argv[]){
double *a, *b;
int n = 20;
a = (double *)calloc(n, sizeof(double));
a = (double *)calloc(n, sizeof(double));
for (int i=0; i<n; i++ ){
a[i] =drand48();
}
}
```
but ... |
There is no built-in way to copy arrays in C directly.
You have two options:
The loop you mentioned:for(i = 0; i < n; i++) {
b[i] = a[i];
}Thememcpyfunction:memcpy(b, a, n * sizeof(double));
|
I wrote this function in order to swap 2 nodes in a linked list, but the result is a Segmentation Fault. Can you check it? Thanks.
(I did typedef for struct student* as punt)
```
void swap_node(punt node1, punt node2)
{
node1->next=node2->next;
node2->next=node1;
node2->prev=node1->prev;
node1->prev=node2;
(nod... |
I guess this would be sufficient, basically the only difference from your code is the last statement (did not include null checks for simplicity):
```
void swap_node(punt node1, punt node2)
{
node1->next=node2->next;
node2->next=node1;
(node1->prev)->next=node2;
node2->prev=node1->prev;
node1->prev=node2;
(node1->ne... |
Apologies if I have some of the terminology wrong, I've been reading several pages and haven't seen an explicit answer to this and just want to make sure.
If I want to make a 10 character long array to build a string with, do I need to set its size to 10 or 11? I don't know what the word entered into the array is pri... |
It depends according to what your goal is:
Store an array of 10chars:
```
char someChars[10];
```
Store a string of max. 10chars:
```
char myString[11]; /* 10 + '\0' */
```
Please note that string it's not a C language type.
|
I know there are questions asking if you can call a function without parentheses and the answer to that is no but in my code that works and I'd like to know why.
```
typedef struct{
//some variables
} REG;
long foo(){
//some code
return 23; //i.e 23, it could be any positive integer
}
REG * foo1(REG **p... |
Maybe I'm missing something, but this looks like it is taking the address of thefoofunction, casting it to anint, and using thatintas the first argument (num) tocalloc. This will most likely allocate a large amount of memory, rather than just enough for 23 elements that you think it's allocating, which explains why t... |
I am new to C programming, and just learned about structures. My question is what the point of putting pointers after defining a structure? like in this example (this is my senior code btw):
```
struct lecturer {
char Lecturer_ID[40];
char Lecturer_Passport[40];
char Lecturer_Name[40];
char Lecturer_... |
This is related to the topic 'Linked List'.
Imagine you have a unknown number of lecturers which will be given to you at runtime. So you will have to dynamically allocate a space in memory each time a new lecturer record needs to be processed.
In this case you will use the 'next' pointer to create a link between the... |
I have been trying to use theDIVINE4model checker to verify a sample C program, but due to the conflicts in the provided tutorials I haven't had good results.
Can you suggest any good sources that explains the steps clearly?
(I have thoroughly looked for this, but haven't found much)
|
DIVINEmanualshould cover most of the topics you would need. However, the examples are not updated to the newest version of DIVINE.
This can be fixed. Let's take, for example, the first example airlines.cpp. If you do the following changes:
Comment out #include "divine.h".Replace all "__divine_choice" with "__vm_choo... |
I have a very simple code:
```
#include <openssl/sha.h>
int main() {
SHA_CTX sha1;
SHA_Init(&sha1);
}
```
I have installed bothlibssl-devandlibcrypto++-dev:
However I have a build failure using the following command:
```
$ gcc -lcrypto -lssl main.c
/tmp/ccfnCAxT.o: In function `main':
main.c:(.text+0x1f):... |
-lsslis not needed,-lcryptois enough, and it must be at the end:
```
gcc -o main main.c -lcrypto
```
(or whatever you want your program to be called goes after-o)
|
I want to stringify the__COUNTER__and print it as a string not an integer. Is that possible?
```
printf("%s\n", #__COUNTER__);
```
I have tried the following, but it does not work.
```
hello.c:6:19: error: stray ‘#’ in program
printf("%s\n",#__COUNTER__);
```
|
Yes, but it takes an indirection because you can't use the#operator outside of a macro.
```
#define STRINGIFY_2(a) #a
#define STRINGIFY(a) STRINGIFY_2(a)
printf("%s\n", STRINGIFY(__COUNTER__));
```
The double macro is required to expand__COUNTER__, otherwise the result would be"__COUNTER__".
If you don't want to r... |
The following code gives me a Compile error "incompatible types at assignment"
File 1:
```
struct x{
int a;
int b;
int c;
};
```
File 2:
```
static struct x d;
void copyStructVal(){
d-> a = 1;
d-> b = 2;
d-> c = 3;
}
x getStruct(){
copyStructVal();
return d;
}
```
File 3:
```
static struct x e;
... |
In C, you need to writestructbehind the name of a structure, unless youtypedefit. In other words:
```
x getStruct(){
```
Must be:
```
struct x getStruct(){
```
Since you wrote it in the rest of the code, I guess it is a typo.
On top of that, you have to fix these 3 lines, sincedis not a pointer:
```
d-> a = 1;
... |
I have a very simple code:
```
#include <openssl/sha.h>
int main() {
SHA_CTX sha1;
SHA_Init(&sha1);
}
```
I have installed bothlibssl-devandlibcrypto++-dev:
However I have a build failure using the following command:
```
$ gcc -lcrypto -lssl main.c
/tmp/ccfnCAxT.o: In function `main':
main.c:(.text+0x1f):... |
-lsslis not needed,-lcryptois enough, and it must be at the end:
```
gcc -o main main.c -lcrypto
```
(or whatever you want your program to be called goes after-o)
|
I want to stringify the__COUNTER__and print it as a string not an integer. Is that possible?
```
printf("%s\n", #__COUNTER__);
```
I have tried the following, but it does not work.
```
hello.c:6:19: error: stray ‘#’ in program
printf("%s\n",#__COUNTER__);
```
|
Yes, but it takes an indirection because you can't use the#operator outside of a macro.
```
#define STRINGIFY_2(a) #a
#define STRINGIFY(a) STRINGIFY_2(a)
printf("%s\n", STRINGIFY(__COUNTER__));
```
The double macro is required to expand__COUNTER__, otherwise the result would be"__COUNTER__".
If you don't want to r... |
The following code gives me a Compile error "incompatible types at assignment"
File 1:
```
struct x{
int a;
int b;
int c;
};
```
File 2:
```
static struct x d;
void copyStructVal(){
d-> a = 1;
d-> b = 2;
d-> c = 3;
}
x getStruct(){
copyStructVal();
return d;
}
```
File 3:
```
static struct x e;
... |
In C, you need to writestructbehind the name of a structure, unless youtypedefit. In other words:
```
x getStruct(){
```
Must be:
```
struct x getStruct(){
```
Since you wrote it in the rest of the code, I guess it is a typo.
On top of that, you have to fix these 3 lines, sincedis not a pointer:
```
d-> a = 1;
... |
I wish to read a jar in binary mode and write the binary as string(encoded if need be) to a file.
This string would be included in code to be read and converted back into binary and written as a jar file.
I'm trying to replicate what get-pip.py has done to distribute pip.
What would be the best way to do this in C?
|
You can use base64 encoding for this. Base64 is a standard, and you can use the encoder from one implementation, and the decoder from another, and you'd get back the original string on the other side. The typical straightforward implementation is a table driven one, as in this answer here:https://stackoverflow.com/a... |
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Student{
char nume[30];
char prenume[30];
float medie;
}Student;
int main()
{ FILE *st= fopen("input.txt","r");
Student a[10];
int i;
for(i=0;i<10;i++)
fscanf(st,"%s %s %f",a[i].nume,a[i].prenume,a[i].medie);
fclose(st);
return... |
Almost certainly because you are passing a[i].medie (the value of the float) not &a[i].medie (the address of the float) to fscanf().
But you will also crash if the file input.txt is not present or not readable, as you don't check for an error return from fopen()
|
I am new to C programming. Take a look at my code & point me where i am doing wrong? Here is my code to create a range function which should return int array.
```
#include<stdio.h>
int * range(int a, int b);
main()
{
int *r;
int j;
r = range(0,5);
printf("%d",r[0]); // getting the first one to check ... |
You are returning the address of a local array whose lifetime ends with the function.
Change
```
int last[b];
```
to
```
int *last = malloc(sizeof(int) * b);
```
Don't forget to callfree(r);after theprintf
|
Which is the fastest way to limit a number to 64 inclusive (ie. <= 64)
```
len = len > 64 ? 64 : len; /* limit to 64 */
```
Thanks!
|
I created a program
```
#include <stdio.h>
int main(void) {
unsigned int len;
scanf("%u", &len);
len = len > 64 ? 64 : len;
printf("%u\n", len);
}
```
and compiled withgcc -O3and it generated this assembly:
```
cmpl $64, 4(%rsp)
movl $64, %edx
leaq .LC1(%rip), %rsi
cmovbe 4(%rsp), %edx
``... |
Which is the fastest way to limit a number to 64 inclusive (ie. <= 64)
```
len = len > 64 ? 64 : len; /* limit to 64 */
```
Thanks!
|
I created a program
```
#include <stdio.h>
int main(void) {
unsigned int len;
scanf("%u", &len);
len = len > 64 ? 64 : len;
printf("%u\n", len);
}
```
and compiled withgcc -O3and it generated this assembly:
```
cmpl $64, 4(%rsp)
movl $64, %edx
leaq .LC1(%rip), %rsi
cmovbe 4(%rsp), %edx
``... |
I was coding a simple socket agent program in LINUX system(Ubuntu 16.04 server).
When I run this program in Solaris, It gets the following error:
```
Cannot find /lib64/ld-linux-x86-64.so.2
```
This list is what I included.
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include... |
Solaris is not Linux. The system libraries will most likely be in different locations. You will need to recompile your program on Solaris.
|
```
int y = 1;
int *x = &y;
printf("%p\n",x); // instead of printing, get this into variable of type unintptr_t
```
I would like to get the addressxinto variable of typeuintptr_t
Is there a way to do that in C?
|
It isn't particularly difficult...
```
uintptr_t z = (uintptr_t)x;
```
Notice that the result of this cast is implementation-defined; the only guarantee you have is that if you castzback to anint *you'll get the original pointer back.
By the way, there's no such a thing as a "hexadecimal address"; addresses are add... |
My source code contains a segment similar to the following:
```
double ****A;
my_function(A);
```
which throws a segfault error in my_function.
However, when I replace it with:
```
double ***A;
my_function(&A);
```
then my_function works. I would have thought my_function would see the same argument in both case... |
This:double ****A;is not set to point to anything. It is a dangling pointer with no known value.
This:double ***A; double ****B = &A;which is kind of what your function call does, points B at the storage of A, so the pointer actually points to something that exists.
|
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.Closed5 years ago.Improve this question
I have a variable of type int that should represent the number of spaces. How can I create a string contain... |
```
char *integerToSpaces(unsigned i)
{
char *str = malloc(i + 1);
char *ptr = str;
if(!str) return NULL;
while(i--)
{
*ptr++ = ' ';
}
*ptr = 0;
return str;
}
```
|
It is said that the stack grows by 8 bytes and%rspis decremented to make room for the return address of the next instruction call.
My question is:Does this return address take up all 8 (bytes)? That is, are all 8 locations taken up by the return address? Or does is not take up the entire 8 bytes provided, in which ... |
It takes all the 8 bytes. %rsp will be decremented by exactly 8 bytes.
|
I am populating an array of tokens from input from stdin. I was looking at a tutorial, and the code successfully populates an array, however, I am not being able to use if else condition to eliminate the token I don't want to put in the array.
```
char * token[MAX_ARGS];
char ** arg; ... |
It is cleaner to do it like this
```
char *tok = strtok(line, " \t\n");
while(tok) {
*arg++ = tok;
tok = strtok(NULL, " \t\n");
}
```
Now theNULLpointer isn't placed in the array.
But, you aren't keeping any tally of how many pointers are in the array, so why don't you want the sentinel valueNULL?
|
Is there a way to detect if a program is piped into another one?
Because when I print a colored string using ANSI colors, the get piped
too, which I want to prevent.
Or is there a better way to print colors?
|
Some program do accept color when piped into ( likeless -r).
But in your case you would want to know if your current output is a tty, and useisattyfor that purpose, and avoid printing color when your output is not a terminal.
You will also need to usefilenoto convert yourFILE*to a file descriptor.
|
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 answer... |
Check out these tools:
lrs (http://cgm.cs.mcgill.ca/~avis/C/lrs.html)polymake (https://polymake.org/doku.php)cdd (https://www.inf.ethz.ch/personal/fukudak/cdd_home/)
|
I have developed a small android application using react-native. For what it was developed, it works fine. Now to accommodate a small requirement, we need to call a library written in C. I am not sure if there will be a way to call the C code from JavaScript! But I still wanted to ask you all.
Is there a way to do th... |
You are going to have to write some native code, search for how to call a C lib on Android, then look for react native way to link a native code with a js call.
Native Module linkhttps://facebook.github.io/react-native/docs/native-modules-android.html
StackOverflow question on how to run c/cpp code on androidhow to ... |
Right now I'm making a program that is supposed to mimic how Bash operates with signals. Is there a more efficient way of printing to the terminal signal termination messages (like "segmentation fault", "Illegal instruction", "Alarm clock", etc.)? Because right now what I have in my mind is just a long, long series of... |
Trystrsignalfrom thestring.hheader orpsignalfromsignal.h. Read their man pages for documentation.
|
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.Closed5 years ago.Improve this question
If I have a struct as local variable which is only used in a function inside but the size of it is a little... |
This does of course depend on the OS, but a subjective rule of thumb is that objects somewhere around 1 kib are better off on the heap (or in.data) than on the stack.
Though some libraries where they expect that one out of many objects might be big, put everything on the heap just for the sake of consistency.
|
Is it important to include a rule for the production of an object file and then a second rule for the executable, or should I add only one rule to create the executable file in a single command?
Example of separate compile + link:
```
foo: foo.o
foo.o: foo.c
```
Single command:
```
foo: foo.c
```
|
If you have a single source file, there is little reason to prefer one over the other.
In larger projects, you will link object files from many translation units, and then it becomes necessary to separate the compilation and linking phases (so that many files can be compiled simultaneously, and many need not be compi... |
I want to modify kernel read/write functions (present in fs/read_write.c) in order to implement a simple substitution cipher, but I want to do this only for certain files and not all and hence inside kernel code I want to check if this is a file marked by user for encryption then only do this task.
One way I discovere... |
You could use extended file attributes. They allow you to set and get arbitrary metadata associated with a file.
Check man 5 attr andthis questionfor how to set and get extended attributes from the kernel.
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed5 years ago.Improve this question
I'm trying to use st... |
but it didn't work. What is wrong?Nothing wrong in scanning but you might printinga, initialize the char array first.
```
int main(void) {
char a[100] = { 0 }; /* initilize with 0 to avoid printing junk data */
scanf("%s", a+1);
printf("[%s]\n",a);/* nothing it prints bcz you putted data in a... |
I try to overwrite contents of the file usingfwrite(),fseek()in C, but it doesn't work.
The file size is 30. I want to write "ABCD" by overwrite position 10 ~ 13 in the file. So I program below.
```
FILE *fp = fopen("file.txt", "a+");
fseek(fp, 10, SEEK_SET);
fwrite("ABCD", 1, 4, fp);
```
But"ABCD"is written after... |
Use"r+"mode to open the file instead of"a+"(thebfor binary is optional and essentially irrelevant on POSIX systems):-
```
#include <stdlib.h>
#include <stdio.h>
int main(void){
FILE *fp = fopen("file.txt", "r+");
fseek(fp, 10, SEEK_SET);
fwrite("ABCD", 1, 4, fp);
fclose(fp);
return 0;
}
```
|
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 answer... |
while no API found, a good way for me is to use :
Documentationand the following guide:Kernel Guide
|
I am just practicing to understand dynamic allocation in C. I am getting a segmentation fault error. I am not sure where I made mistake.
```
int wordcount = 5;
char **args = (char**)malloc(wordcount * sizeof(char*));
for ( int i = 0; i < wordcount; i++) {
args[i] = (char*)malloc(167 * sizeof(char));
}
int c=0;
... |
You are trying to copyargs[c]to the location of the"hello\n"string, which is in read only memory, you should change the order of the parameters.
|
I tried to measure the time of some operations on the telosB platform. For that I wanted to count the clock ticks of the processor with the clock() function from time.h but it does not compile on contiki.
Are there mechanisms to measure passed time, preferably in actual clock ticks, on contiki?
Regards
|
The latest timer documentation is here:https://github.com/contiki-ng/contiki-ng/wiki/Documentation:-Timers
You can use theclock_ticks()function. However, the resolution of those is quite low (1/128 of second). If you want measure shorter time intervals, use rtimers:RTIMER_NOW()returns the time as 16-bit integer, with... |
So, I've built my makefile and it works well, but I still need to type ./escalunador (My program name) to run it, how do I include that in my makefile?
```
CC = gcc
CFLAGS = -g -Wall -std=c99
all: escalunador
escalunador: escalunador.o usables.o queue.o linkedlist.o
$(CC) $(CFLAGS) -o escalunador escalunado... |
Very simple:
```
run: escalunador
./escalunador
.PHONY: run
```
And maybe you want to modifyall: ./escalunadortoall: run.
|
I have this code
```
if(orden[i]==1)
for(i=0; i<ARRAY_SIZE; i++)
if(v[i]<v[i+k])
printf("print once ");
```
How can I make it so that it prints the line only once, if the condition inside the for loop is satisfied?
|
Use thebreakcommand to exit theforloop.
```
if(orden[i]==1)
for(i=0; i<ARRAY_SIZE; i++)
if(v[i]<v[i+k])
{
printf("print once ");
break;
}
```
|
int main(int argc, char* argv[])
In this code argv[] is a string not array so how can i use as a array to perform sum operation?
|
You can do it like this
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int sum = 0;
int i = 1;
for(;i<argc;++i)
sum += atoi(argv[i]);
printf("%d\n",sum);
return 0;
}
```
And the result:
```
$ gcc test.c && ./a.out 1 2 3 4
10
```
|
If I wanted to limit the range of values to be assigned to an integer to three different conditions. eg; Must be between 9 and 95 and also be divisible by 5 would this be the correct way to accomplish this?
I've been told that i can have multiple conditions as long as they are separated by && but I am having little s... |
Your code seems fine to me, except for this line.
```
if (input >= 5 && input <= 95 && input %5)
```
The expressioninput % 5returns the remainder ofinput/5. You wantinputto be divisible by 5, which happens wheninput % 5returns a remainder of 0. Since C interprets 0 as false, and pretty much all other integers as tru... |
I study C language and I have some difficulty to understand pointers and arrays.
In tutorial that I read I have this row:
```
char* arrP1[] = { "father","mother",NULL };
```
And my question is what is arrP1?
Is it array of pointers to the static strings:
Or it is pointer to the string array:
I am confused...... |
arrPis an array ofchar *which in this case is an array of size 3, and you've assigned the pointers to c-style strings with initial values of{"father", "mother", NULL}, which themselves are character arrays that are null terminated. So, your first answer is correct.
|
In the following C snippet that checks if the first two bits of a 16-bit sequence are set:
```
bool is_pointer(unsigned short int sequence) {
return (sequence >> 14) == 3;
}
```
CLion's Clang-Tidy is giving me a "Use of a signed integer operand with a binary bitwise operator" warning, and I can't understand why. I... |
The code for this warningchecks ifeitheroperand to the bitwise operator is signed. It is notsequencecausing the warning, but14, and you can alleviate the problem by making14unsigned by appending auto the end.
```
(sequence >> 14u)
```
This warning is bad. AsRoland's answerdescribes, CLion is fixing this.
|
I made an inverter the easy way, with the array as a parameters and two ints that are the start and the end. The problem I got stuck with is coding a function that gets as parameters the array and a number which represent how many values the array have. Any idea?
|
Use a base case for length 0 and 1, and for the recursive step, swap the first and last element, increment the array pointer, and call itself with length-2. This code does the trick:
```
void invert(int* arr, int len) {
if(len == 0) {
return;
}
else if(len == 1) {
return;
}
else {
... |
I need to remove the last part of a file path.
For example, if I have this filename"user/doc/file1", I want to be able to get"user/doc/".
|
You probably want this:
```
#include <stdio.h>
#include <string.h>
int main()
{
char string[] = "/user/doc/file1";
// find pointer to last '/' in string
char *lastslash = strrchr(string, '/');
if (lastslash) // if found
*(lastslash + 1) = 0; // terminate the string right after the '/'
p... |
int main(int argc, char* argv[])
In this code argv[] is a string not array so how can i use as a array to perform sum operation?
|
You can do it like this
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int sum = 0;
int i = 1;
for(;i<argc;++i)
sum += atoi(argv[i]);
printf("%d\n",sum);
return 0;
}
```
And the result:
```
$ gcc test.c && ./a.out 1 2 3 4
10
```
|
If I wanted to limit the range of values to be assigned to an integer to three different conditions. eg; Must be between 9 and 95 and also be divisible by 5 would this be the correct way to accomplish this?
I've been told that i can have multiple conditions as long as they are separated by && but I am having little s... |
Your code seems fine to me, except for this line.
```
if (input >= 5 && input <= 95 && input %5)
```
The expressioninput % 5returns the remainder ofinput/5. You wantinputto be divisible by 5, which happens wheninput % 5returns a remainder of 0. Since C interprets 0 as false, and pretty much all other integers as tru... |
I study C language and I have some difficulty to understand pointers and arrays.
In tutorial that I read I have this row:
```
char* arrP1[] = { "father","mother",NULL };
```
And my question is what is arrP1?
Is it array of pointers to the static strings:
Or it is pointer to the string array:
I am confused...... |
arrPis an array ofchar *which in this case is an array of size 3, and you've assigned the pointers to c-style strings with initial values of{"father", "mother", NULL}, which themselves are character arrays that are null terminated. So, your first answer is correct.
|
In the following C snippet that checks if the first two bits of a 16-bit sequence are set:
```
bool is_pointer(unsigned short int sequence) {
return (sequence >> 14) == 3;
}
```
CLion's Clang-Tidy is giving me a "Use of a signed integer operand with a binary bitwise operator" warning, and I can't understand why. I... |
The code for this warningchecks ifeitheroperand to the bitwise operator is signed. It is notsequencecausing the warning, but14, and you can alleviate the problem by making14unsigned by appending auto the end.
```
(sequence >> 14u)
```
This warning is bad. AsRoland's answerdescribes, CLion is fixing this.
|
I made an inverter the easy way, with the array as a parameters and two ints that are the start and the end. The problem I got stuck with is coding a function that gets as parameters the array and a number which represent how many values the array have. Any idea?
|
Use a base case for length 0 and 1, and for the recursive step, swap the first and last element, increment the array pointer, and call itself with length-2. This code does the trick:
```
void invert(int* arr, int len) {
if(len == 0) {
return;
}
else if(len == 1) {
return;
}
else {
... |
I need to remove the last part of a file path.
For example, if I have this filename"user/doc/file1", I want to be able to get"user/doc/".
|
You probably want this:
```
#include <stdio.h>
#include <string.h>
int main()
{
char string[] = "/user/doc/file1";
// find pointer to last '/' in string
char *lastslash = strrchr(string, '/');
if (lastslash) // if found
*(lastslash + 1) = 0; // terminate the string right after the '/'
p... |
I created modulea.handa.c. How can I create a compiled encapsulated module from it (without addinga.cfor each project, without exposinga.himplementation)?
I work with Visual Studio 2010.
Thanks
|
As @unwind points out, you will have to expose, at the very least, those types and functions that you want the user to use.
Note, however, that if the user does not need to know the internals of a given type, you just give the user opaque types/pointers/handles.
In other words:
```
typedef struct Opaque Opaque;
Op... |
In my code, I need to declare two process. In the first process, I want to call the second one like this:
```
PROCESS_THREAD(Initialization_process, ev, data)
{
PROCESS_BEGIN();
PROCESS_THREAD(example_broadcast_process, ev, data);
PROCESS_END();
}
```
But I got this error:
```
error: invalid storage cl... |
If you just want to start another process asynchronously, define this process (let's sayexample_broadcast_process) as usual, in the file scope, and then callprocess_start()from the other process:
```
process_start(&example_broadcast_process, NULL);
```
If you desire synchronous operation, you can callPT_SPAWNto star... |
Learning opengGL(+glfw) I met interesting thing: I have to use only one kind of prototype of functionmouse_callbackinglfwSetCursorPosCallback (Glfwwindow* , GLFWcursorposfun mouse_callback);How I should I use variableGLfloat yaw = -90.0f;in mymouse_callbackwithout passing it as argument(there will be an error) or glo... |
You can't. C function pointers do not support binding arguments. Generally, you can pass a pointer to a specific function that already has that value-90.0fbaked into it, or use a global variable.
Yes, this sucks. It's why C++ introducedstd::bind, and then lambdas. Unfortunately, the OpenGL API does not allow you to m... |
I am wondering how could I return a specific amount of decimals. My code is below and I want to return the value with only one decimal but I couldn't find the right syntax. (e.g x=3.465.. but I want to return x=3.4)
```
double avg(int* grade, int len){
int i; float sum=0.0;
for(i=0;i<len;i++){
sum+=*(gra... |
Why?
Precision only matters when displaying it to the user; until that point, surely you should use the highest degree of precision available?
To format a float in something like a printf statement, use%3.1f- field width of 3, 1 number after the decimal point.
|
This question already has answers here:C or C++. How to compare two strings given char * pointers?(8 answers)Closed5 years ago.
If I have achar*that is the output of another function, and I know it is one of the 10 known words, what is the best way to find what is it?
converting thechar*tostringbystd::string(char*),... |
Since you already have a C string, just usestrcmp. It will likely be faster than thes.comparemethod since you avoid the overhead of doing a conversion tostd::stringfor both the original string and the string to compare to.
```
if (strcmp(c, "hello") == 0) {
...
```
|
I'm learning C troughthis tutorial, where I stumbled upon this code:
```
int args_assigned =
sscanf(input_buffer->buffer, "insert %d %s %s",
&(statement->row_to_insert.id),
statement->row_to_insert.username,
statement->row_to_insert.email);
```
The part that confuses me is&(statement->... |
This is probably just for readibility.&(statement->row_to_insert.id)is equivalent to&statement->row_to_insert.iddue to operator precedence in C operators->and.have higher precedence than&. You can read morehere.
|
This question already has answers here:C or C++. How to compare two strings given char * pointers?(8 answers)Closed5 years ago.
If I have achar*that is the output of another function, and I know it is one of the 10 known words, what is the best way to find what is it?
converting thechar*tostringbystd::string(char*),... |
Since you already have a C string, just usestrcmp. It will likely be faster than thes.comparemethod since you avoid the overhead of doing a conversion tostd::stringfor both the original string and the string to compare to.
```
if (strcmp(c, "hello") == 0) {
...
```
|
I'm learning C troughthis tutorial, where I stumbled upon this code:
```
int args_assigned =
sscanf(input_buffer->buffer, "insert %d %s %s",
&(statement->row_to_insert.id),
statement->row_to_insert.username,
statement->row_to_insert.email);
```
The part that confuses me is&(statement->... |
This is probably just for readibility.&(statement->row_to_insert.id)is equivalent to&statement->row_to_insert.iddue to operator precedence in C operators->and.have higher precedence than&. You can read morehere.
|
A couple days ago I had the atan function from math.h working properly, but for some reason it's no longer compiling. I get the usual
'broken_code.c:(.text+0x49): undefined reference to 'atan'
I'm including the-lmflag when I compile.
I've tried compiling and running it on a different system (both another Linux sys... |
Maybe you linked the math library in the wrong order.
For example
```
gcc -lm prog.c
```
might not work while
```
gcc prog.c -lm
```
will
|
Say Iputenvan environment variable ABC and then do anexecl, or I do anexecleand add ABC to the envp array of pointers that I pass toexecle.
Is there a difference, if any?
|
putenvadds an environment variable to the current environment. Usingexeclwill then use that environment.
execlewill use the environment argument as the entire environment, i.e. it won't inherit the existing environment variables.
It's easy to see this with a simple program that just runsenv(which prints out the curr... |
This question already has answers here:How do I check OS with a preprocessor directive?(17 answers)Closed5 years ago.
I am writing aCprogram and my operating system isMacOS.
I am wondering how to add a macro in order to compile myCprogram under different operating system, mainlyWindowsandLinux?
Thanks a lot for pro... |
You can do it like below:-
```
#if defined(_WIN32)
#define OS_NAME "windows"
/* add your windows specific codes here */
#elif defined(__linux__)
#define OS_NAME "linux"
/* add your Linux specific codes here */
#elif defined(__APPLE__) && defined(__MACH__)
#define OS_NAME "MacOS"
/* add your Mac... |
Below is the small program:
```
#include <stdio.h>
#define max 'A'
int main()
{
char a;
printf("max[%d] sizeof[max][%ld]\n", max, sizeof(max));
a = max;
printf("a[%d] sizeof[a][%ld]\n", a, sizeof(a));
return 0;
}
```
And the output of the program is:
```
max[65] sizeof[max][4]
a[65] sizeof[a][1... |
sizeof(max)is replaced by the preprocessor withsizeof('A').sizeof('A')is the same assizeof(int), and the latter is 4 on your platform.
For the avoidance of doubt,'A'is anintconstantin C,notachar. (Note that in C++'A'is acharliteral, andsizeof(char)is fixed at 1 by the standard.)
|
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.Closed5 years ago.Improve this question
Hello I have along longnumber which varies from 13,15, and 16 digits in length. I want to get the first two... |
Assuming the number is available at compile-time, you can extract it at compile-time by converting it to a string:
```
#include <stdio.h>
#define NUMBER 1234567890123
#define STR(n) #n
#define FIRST(n) STR(n)[0]
#define SECOND(n) STR(n)[1]
int main(void)
{
printf("%c %c", FIRST(NUMBER), SECOND(NUMBER));
retu... |
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.Closed5 years ago.Improve this question
Best sort algorithm that can used for sorting linked list using structures in c, which ha... |
The easiest way to do that and to avoid errors would be that you create a new list and then iterate trough the original and in every iteration find the smallest/biggest element and append it to the start/end of the new list, and then delete it from the original list. This has time complexity of O(n^2) so if you want s... |
This question already has answers here:Is there a way to get text as soon as possible without waiting for a newline?(4 answers)Closed5 years ago.
I want to check if the user writes something like "car" then I can print "You want to buy it?" or something like that. Is it possible to do that in C?
EDIT: I use Windows.... |
Depending on the system you may use (not always possible) conio - for dos and windows console, ncurses for linux or other related for your system
ncurses -http://www.cs.ukzn.ac.za/~hughm/os/notes/ncurses.html#input
|
Say I have five files:main.c, sample1.c, sample1.h, sample2.candsample2.h, where in each of these filesDEBUG_PRINTSis defined as follows:
```
#ifndef DEBUG_PRINTS
#define DEBUG_PRINTS 0
#endif
```
and the code is compiled using gcc:
```
gcc -Wall main.c sample1.c sample2.c -o main
```
Now I change the value ofDEBU... |
Each file is compiled separately. Macros from one file are not visible in any other file. Once the files are independently compiled, the resulting objects are linked together to create an executable.
|
I have to do a program for college and I need to use two files with the tree and row data structure.
At the beginning I have a definition for the data each data structure is supposed to comport:
```
#define TYPE int
```
Which is implemented in the code appropriately.
Though in this task I need to fill these structu... |
Usetypedefinstead of#definebecausetypedefcan handle arrays (and pointers) where#definecannot.
```
typedef int TYPE;
typedef char TYPE[20];
```
etc.
Continue to useTYPEin your structures, etc.
|
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.Closed5 years ago.Improve this question
Best sort algorithm that can used for sorting linked list using structures in c, which ha... |
The easiest way to do that and to avoid errors would be that you create a new list and then iterate trough the original and in every iteration find the smallest/biggest element and append it to the start/end of the new list, and then delete it from the original list. This has time complexity of O(n^2) so if you want s... |
This question already has answers here:Is there a way to get text as soon as possible without waiting for a newline?(4 answers)Closed5 years ago.
I want to check if the user writes something like "car" then I can print "You want to buy it?" or something like that. Is it possible to do that in C?
EDIT: I use Windows.... |
Depending on the system you may use (not always possible) conio - for dos and windows console, ncurses for linux or other related for your system
ncurses -http://www.cs.ukzn.ac.za/~hughm/os/notes/ncurses.html#input
|
Say I have five files:main.c, sample1.c, sample1.h, sample2.candsample2.h, where in each of these filesDEBUG_PRINTSis defined as follows:
```
#ifndef DEBUG_PRINTS
#define DEBUG_PRINTS 0
#endif
```
and the code is compiled using gcc:
```
gcc -Wall main.c sample1.c sample2.c -o main
```
Now I change the value ofDEBU... |
Each file is compiled separately. Macros from one file are not visible in any other file. Once the files are independently compiled, the resulting objects are linked together to create an executable.
|
I have to do a program for college and I need to use two files with the tree and row data structure.
At the beginning I have a definition for the data each data structure is supposed to comport:
```
#define TYPE int
```
Which is implemented in the code appropriately.
Though in this task I need to fill these structu... |
Usetypedefinstead of#definebecausetypedefcan handle arrays (and pointers) where#definecannot.
```
typedef int TYPE;
typedef char TYPE[20];
```
etc.
Continue to useTYPEin your structures, etc.
|
Say I have five files:main.c, sample1.c, sample1.h, sample2.candsample2.h, where in each of these filesDEBUG_PRINTSis defined as follows:
```
#ifndef DEBUG_PRINTS
#define DEBUG_PRINTS 0
#endif
```
and the code is compiled using gcc:
```
gcc -Wall main.c sample1.c sample2.c -o main
```
Now I change the value ofDEBU... |
Each file is compiled separately. Macros from one file are not visible in any other file. Once the files are independently compiled, the resulting objects are linked together to create an executable.
|
I have to do a program for college and I need to use two files with the tree and row data structure.
At the beginning I have a definition for the data each data structure is supposed to comport:
```
#define TYPE int
```
Which is implemented in the code appropriately.
Though in this task I need to fill these structu... |
Usetypedefinstead of#definebecausetypedefcan handle arrays (and pointers) where#definecannot.
```
typedef int TYPE;
typedef char TYPE[20];
```
etc.
Continue to useTYPEin your structures, etc.
|
This question already has answers here:String literals: Where do they go?(8 answers)Closed5 years ago.
statements like:char *a = "hello"orchar *b[]= {"yes", "no"}seem to be accessible and printable without any problems in C.
Do they require a malloc?
|
Case 1:-char *a = "hello";Hereais char pointer and it needs valid address and its assigned with valid address ashellois string i.e address. So no need ofmalloc()here.
Case 2:-char *b[]= {"yes", "no"};Herebisarray of char pointeri.e each element ofbispointerthat means each elements needs to be initialized withvalid a... |
I am parsing a string using strtok. The string I am parsing may have two possibilities like"10,5"or"10". When I parse"10,5"I can successfully put then into array, but when I have this"10", I have 1 item 10 and another item a big integer in array.
here is my code
```
int array[2];
char *p = strtok (argv[1], ",");... |
You haven't initialized the array, so if the loop only finds one number, you get whatever uninitialized garbage was in the second element.
```
int array[2] = {0, 0};
```
will initialize both elements to0. If the input has only10, the array will contain10, 0.
|
I have a shell scriptcompileRunthat compiles and execute C source file.
```
#!/bin/sh
gcc bar.c -o ./bar
./bar
```
what i actualy wish to achieve is when we
```
ln -s compileRun bar.c
./bar.c
```
I would like bar.c to be compiled and executed.
I appreciate any help.
|
I understand what OP wants.
What follows would work only if source files are explicitly stored in a different place than symlinks. A path can be prepended to$0in the bash script.
Your should replacesomefile.cby$0in your bash script.
This special shell expression returns the name of the file being currently executed... |
I have an entire library made in C. It has almost 10 folders with a lot of files.
I have created a filename.c file in root folder and trying to compile it in mac usinggcc test.c -o testhowever its not including header files. Generally I have to add all the header filesgcc test.c libaudio.c -o test
How can I compile ... |
Makefiles will solve your problem. You can create your own rules to clear the project (remove the generated files), build the project indicating where is your compiler (compile the source files located in some specific path, extension, etc), set the output path and so on, without typing a large compilation order.
htt... |
What Bitmask to use for modulo division by 256 on an unsigned int in C language? Also how should one go about figuring this out?
|
You have to use all bits that are less significant than the 256-bit.
So, in this case, that would be the 128, 64, 32, 16, 8, 4, 2 and 1-bit. The resulting bitmask would therefore be 0b11111111 = 0xff.
In C, a resulting code could bej & 0xff. But that manual translation is usually unnecessary, you can also usej % 256... |
What Bitmask to use for modulo division by 256 on an unsigned int in C language? Also how should one go about figuring this out?
|
You have to use all bits that are less significant than the 256-bit.
So, in this case, that would be the 128, 64, 32, 16, 8, 4, 2 and 1-bit. The resulting bitmask would therefore be 0b11111111 = 0xff.
In C, a resulting code could bej & 0xff. But that manual translation is usually unnecessary, you can also usej % 256... |
What Bitmask to use for modulo division by 256 on an unsigned int in C language? Also how should one go about figuring this out?
|
You have to use all bits that are less significant than the 256-bit.
So, in this case, that would be the 128, 64, 32, 16, 8, 4, 2 and 1-bit. The resulting bitmask would therefore be 0b11111111 = 0xff.
In C, a resulting code could bej & 0xff. But that manual translation is usually unnecessary, you can also usej % 256... |
I am currently working on a project that relies on injecting a DLL into another process, so (AFAICT) standard debugging tools don't work. What I've been using instead is#define DEBUG(_msg) MessageBoxA(nullptr, _msg, "Debug", MB_OK).
This has the issue that it blocks the current thread until I click on the message box... |
In Visual Studio a running process can be debugged.
In the menu Debug look for Attach to process.
Then breakpoints can be triggered like normal.
|
(This is a follow-up question forhow to check if monotonic clock is supported)
I tried printing the value of_SC_MONOTONIC_CLOCKand got149. I tried GooglesearchonPOSIXsite and got no results.
(Update after the answer:149is on Debian. Just tried on macOS and FreeBSD and both are using value74.)
|
POSIX statesthat the symbolic constants_SC_*are defined in theunistd.hheader:
Theunistd.hheader shall define the following symbolic constants forsysconf(): [...]_SC_MONOTONIC_CLOCK
However, it does not define what is the value of such symbolic constant -- it shouldn't be important for your application (and you shoul... |
Is it possible to include variables through using%cand such when you have strings saved into the array?
```
char *MainMenuNames[] = { "%c - Move Left", "%c - Move Right","%c - Move Up","%c - Move Down","%c - Back","%c - Confirm","%c - Show Stats","%c - Show Inventory","%c - Show Legend","%c - Show Controls"};
```
Wh... |
You can use the array element as a parameter to formatting functions likeprintf()
```
char *commands = "lrudbcsiln";
for (int i; i < strlen(commands); i++) {
printf(MainMenuNames[i], commands[i]);
putchar('\n');
}
```
|
This code cannot stop looping even when I enter n or N.
What is causing this?
```
char next = "";
printf("Do u want continue\n");
scanf("%c", &next);
getchar();
do
{
if (next=='y' ||next=='Y')
{
selection();
}
else
{
printf("invalid... |
The conditional(next !='n'|| next!='N')is always true.
Ifnextis'n'thennext!='N'is true making the whole expression true. Similarly, ifnextis'N'thennext!='n'is true again making the whole expression true.
What you want here is to use a logical AND&&:
```
} while (next !='n' && next!='N')
```
|
in linux, I am trying the below code which is causing segmentation fault error:
```
int main(int arg_count,char *args[]){
char *buffer;
if(arg_count>1)
buffer = args[1];
else
*buffer = 0;
}
```
I know that pointers point to read only part of the memory, so I changed my first trybuffer[0]=... |
The final line of your function,*buffer = 0, is attempting to set the value referred to by the pointerbuffer.
Asbufferhas never been initialised and therefore contains an indeterminate value, dereferencingbufferis very likely to cause a segfault.
For most projects you should never write argument parsing code yoursel... |
This program should start by reading any keyboard input, then writing one character a time to a disk file, called test.ext
To terminate the code you should be able to input the EOF sequence (Crt^z for Windows I believe).
Input - keyboard
Output - test.txt (disk file)
```
#include<stdio.h>
void main() {
FILE *... |
You are usingputchar()which:
Writes a character to the standard output (stdout).
When you really want to be writing to yourptrfile. You can write to files withfprintf()like this:
```
fprintf(ptr, "%c", ch);
```
Or even better you can usefputc()to write a single character to a file:
```
fputc(ch, ptr);
```
|
I have a weird problem. In a very simple example (it's c, not c++):
```
int test[3];
auto n = _countof(test);
```
I have error E0304:
Severity Code Description Project File Line Suppression State Error
(active) E0304 no instance of function template "__countof_helper"
matches the argument
list
I... |
Usestd::sizeinstead:
```
#include <iterator>
int main()
{
int x[3];
auto const xs{::std::size(x)};
}
```
No changes are required after switching tostd::array,std::vectoror compatible wrapper:
```
::std::array<int, 3> ax{};
auto const axs{::std::size(ax)};
::std::vector<int> vx{0, 0, 0};
auto const vxs{::std... |
7.20.1.1p3mentions that exact-width integers ({u,}int{8,16,32,64}_t) are optional.
How will it practically limit the portability of my software if I use them?
(I'm particularly interested in supporting machines running Linux, Windows, or Mac OS.)
|
As a very good rule of thumb, the exact width integers are fully supported by any machine with a CPU using 2's complementsignedtypes.
You'll do well to find an exception. Some mainframes and cash registers might use 1's complement and the even rarer signed magnitude scheme. You might find it difficult to get your cod... |
This program should start by reading any keyboard input, then writing one character a time to a disk file, called test.ext
To terminate the code you should be able to input the EOF sequence (Crt^z for Windows I believe).
Input - keyboard
Output - test.txt (disk file)
```
#include<stdio.h>
void main() {
FILE *... |
You are usingputchar()which:
Writes a character to the standard output (stdout).
When you really want to be writing to yourptrfile. You can write to files withfprintf()like this:
```
fprintf(ptr, "%c", ch);
```
Or even better you can usefputc()to write a single character to a file:
```
fputc(ch, ptr);
```
|
I have a weird problem. In a very simple example (it's c, not c++):
```
int test[3];
auto n = _countof(test);
```
I have error E0304:
Severity Code Description Project File Line Suppression State Error
(active) E0304 no instance of function template "__countof_helper"
matches the argument
list
I... |
Usestd::sizeinstead:
```
#include <iterator>
int main()
{
int x[3];
auto const xs{::std::size(x)};
}
```
No changes are required after switching tostd::array,std::vectoror compatible wrapper:
```
::std::array<int, 3> ax{};
auto const axs{::std::size(ax)};
::std::vector<int> vx{0, 0, 0};
auto const vxs{::std... |
I am trying to make awhileloop that reads questions from a file and gets a users input and loops through then until it reaches the end of the questions file.
My issue is that the loop iterates twice before asking the user for input.
```
fp = fopen("questions.txt","r");
fp2 = fopen("answers.txt","w");
char buff[... |
Try to do something like:
```
char question[SIZE];
char answer[SIZE];
FILE * fin = fopen("questions.txt", "r");
FILE * fout = fopen("answers.txt", "w");
while (fgets(question, SIZE, fin) != NULL) {
printf("%s", question);
fgets(answer, SIZE, stdin);
fputs(answer, fout);
}
```
|
Are there are any Valgrind functions or macros available when used in the application code I can generate memory leaks wrt a particular function.
In other words I need to account for no memory leaks after calling a particular application function .
|
Valgrind has two mechanisms for interaction between Valgrind and the app under test.
gdbserver commandsand here formemcheck monitor commands. You can start your app under Valgrind and then attach gdb. You can then issue commands to do things like generate a leak report at that instant. In your case you could use thel... |
Let's say I have the following string which looks like a file path:
```
char *filepath = "this/is/my/path/to/file.jpg";
```
I can usestrrchr()to extractfile.jpgas follows:
```
char *filename = strrchr(filepath, '/') + 1;
```
Now I need to extract and store the rest of the stringthis/is/my/path/to. How do I do tha... |
Copy everything up to the file name, then append a'\0':
```
int pathLen = filename - filepath;
char *path = (char *) malloc(pathLen + 1);
memcpy(path, filepath, pathLen);
path[pathLen] = '\0';
...
free(path);
```
|
I am trying to find the best way of getting an input of string without the spaces and tabs.
And from it to get dynamic number of the individual strings that the main one contian.
For example:
For the string str = " abc \t tt 6 \t 4 7"
(There can be a lot more spaces and tabs between the individual strings... |
have a look to strtok() and strtok_r() functions from string.h
It allows you to split a string by specifying which characters are delimiters.
|
This question already has answers here:Switch statements in C: variable in case?(4 answers)Closed5 years ago.
I was making a college project. I faced a problem here is a over simplified version of this problem..
```
#include <stdio.h>
#define h1 2
#define h2 3
#define h3 4
const int ar[] = {h1,h2,h3};
int main(int... |
In C language, case labels must be compile time constants. in your code, ar[i] not compile time constant.
C11 6.8.4.2 The switch statement(paragraph 3) :
The expression of each case label shall be aninteger constantexpression and no two of the case constant expressions in the same
switch statement shall have the s... |
This question already has an answer here:Subscripts going out of range in an array(1 answer)Closed5 years ago.
i have this code
```
#include<stdio.h>
#include<conio.h>
#define MAXCOL 3
#define MAXROW 3
typedef struct {
int arr[MAXCOL][MAXROW];
}GAME;
void createGame(GAME *G){
int i, j;
for(i=0; i<=MAX... |
If the names MAXCOL and MAXROW are to be believed (that you want a col 3 and row 3), then you might fix it by doing:
```
typedef struct {
int arr[MAXCOL+1][MAXROW+1];
}GAME;
```
That way you will actually allocate enough space for 4 (0,1,2,3) rows and 4 columns.
|
```
#include <stdio.h>
#define A 1
#if A
printf("Csau");
#endif
int main()
{
return 0;
}
```
I am trying to run this but my compiler is giving me the error of
main.c:4:9: error: expected declaration specifiers or '...' beforestring constant printf("Csau");
Any suggestions why this isn't working ?
P.S. In mai... |
You can output messages at compile time:
```
#include <stdio.h>
#define A 1
#if A
#warning "Csau"
#endif
int main()
{
return 0;
}
```
At runtime you can not print something outside another function body.
|
I wrote an ntrip client in C using sockets(http://read.pudn.com/downloads116/sourcecode/unix_linux/493018/NtripLinuxClient.c__.htm), Receiving the reqest works fine, but after some time the server stops sending correction data because I do not now how to send nmea updates to the server.
Does anyone know how that woul... |
You just need to send your_nmea + '\r\n' regularly and that should work.
|
This question already has answers here:How can I concatenate twice with the C preprocessor and expand a macro as in "arg ## _ ## MACRO"?(3 answers)Closed5 years ago.
I have something like :
```
#define NBR 42
#define THE_ANS_IS theAnsIsNBR
```
Currently the second macro is expand as 'theAnsIsNBR' as expected, but i... |
```
#define Paste(x, y) x##y
#define Expand(x, y) Paste(x, y)
#define NBR 42
#define THE_ANS_IS Expand(theAnsIs, NBR)
```
|
I'm trying to write a function which will print message onto the screen using VGA text mode buffer.
This is function which prints a single char:
```
void putc(uint8_t c, enum Color term_color)
{
uint8_t *vidptr = (uint8_t*)0xB8000;
*vidptr = c;
vidptr++;
*vidptr = (uint8_t*)term_color;
vidptr++;
... |
The function
putc(uint8_t c, enum Color term_color)
always put the character in the same position (0xB8000).You need to declare
uint8_t *vidptr
outside the function to correctly increment it each call.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.