question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I am learning c programming at school, and having a question about char*.
I initialized char* str5 and char* str6, and their values are the exact same.
what I want to confirm is that if I compare them in if statement, is it always comparing its addresses? If so, Why?
```
char* str5 = "hold";
printf("str5: %s\n", str5, str5);
char* str6 = "hold";
if (str5 == str6){
printf("str5 and str6 point to the same address\n");
}
else{
printf("str5 and str6 point to different addresses\n");
}
```
I appreciate any feedback, thank you so much!
|
Strings aren't a built-in type in C. What you have are two variables of typechar *, each of which contains the address of the first character of a string constant.
So when you comparestr5withstr6using==, you're comparing two addresses.
If you want to compare two strings for equality, you need to use thestrcmpfunction.
|
I'm new to React Native and the app I'm building needs to run some algorithms. Is there any way to run functions from a lower-level programming language inside the React app?
I need this because the algorithms I'm running are really time-consuming and it would take way too much time to run it in JavaScript.
Is there any way I can run some C/C++ code from inside the App? Or are there any other programming languages that can be run from the app that is faster?
|
This is not a React-specific problem. You want to run native c/c++ logic inside a js/typescript program.
Either use assembly script (similar to typescript) or web assembly (convert native c/c++ to wasm which can be imported in any js/typescript environment).
https://www.youtube.com/watch?v=9lxnm9a-Yi8&ab_channel=Maniyar
https://developer.mozilla.org/en-US/docs/WebAssembly/C_to_wasm
|
I try This code
```
#include <stdio.h>
int main() {
int testInteger;
printf("Enter an integer: \n");
scanf("%d", &testInteger);
return 0;
}
```
But in Netbeans, I can't Run this code because It only blank output
Like this
I have same err in VS code but I fix it with run in terminal
Can you help me
|
This problem is about Netbean's internal terminal/console section. The internal console is not able to runscanffunction. So use an external terminal for your project. To do this:
first right click on your project, and select properties.
In that window select"Run"tab at the bottom.
in there, there is"Console Type", change this console type from"internal terminal"to"external terminal".
That is all.
|
I am watching avideoon pointers and memory and I'm confused because I thought memory addresses are 1 byte but in the video he is saying they are 32-bits (4 bytes) and that if we hadint a = 2it would be stored in one memory address, but wouldn't an integer be stored across 4 separate memory addresses since they are a maximum 4 bytes long?
|
A pointer points to a single byte. When you're storing something larger than a byte, it's spread across multiple consecutive bytes, and the pointer points to the first of these bytes. The compiled code uses instructions that can read and write multiple bytes from memory to process the whole thing.
So you're correct, a 32-bit integer will be stored in 4 separate (but consecutive) memory locations.
This is why we have to declare the types of pointers in C. When you derefence the pointer, the type is used to determine how many bytes to read or write starting at that address.
|
I just want to know, what is the difference between esp'sESP_LOGxandprintf, related to memory use and its other features.
And which is the best to use for logESP_LOGI,printfor any other logging function?
|
I think that for most of ad hoc debuging this it is a matter of preference with indication to use printf.
ESP_LOG(I/W/E) are intended to implement "permanent" logging functionality in the code and is also used in the ESP-IDF itself. Then depending on debugging scenario it is possible to globally or locally enable required verbosity levels of information to receive.
|
```
#include <stdio.h>
int main() {
int x = 3;
while (x > 0, x--) {
printf("positive");
}
printf("%d", & x);
return 0;
}
```
output -positivepositivepositive1472586508how I got these numbers in output
|
what you are trying to do is, printing the value ofxafter some iteration, fixed code is:
```
#include <stdio.h>
int main() {
int x=3;
while (x>0)
{ printf("positive");
x--;
}
printf("%d",x);
return 0;
}
```
Note:
formatting is important this would help future coders to understand easily.&-- denotes the address of any variable, while you printing the value ofxwith the ampersand operator, you actually denotes its address.
|
I tried to do this:
```
#include <stdio.h >
int main(void) {
int common = 0;
int num1;
int num2;
int big;
int small;
int i;
printf("Enter the first number : ");
scanf("%d", &num1);
printf("Enter the second number : ");
scanf("%d", &num2);
if (num1 <= num2) {
num1 = small;
num2 = big;
}
else{
num1 = big;
num2 = small;
}
for (i = small ; ; i++)
{
}
```
I don't know what is meant by to 1 do. I'm beginner in algorithmsbut I think it means i++ isn't?
|
The algorithm says to count fromsmalldown to1. So the repetition should bei--, noti++. Usei >= 1as the repetition condition to keep looping until you get to1.
```
for (i = small; i >= 1; i--)
```
|
I'm working with the xv6 OS and I need to substitutestdiowith a file. This is normally done with thedup2syscall, which this OS doesn't have. Is there any workaround? Do I have to implement my own syscall which will try to mimic the POSIX's one behavior? Or can the functionality I need (substitute the file descriptor) can be implemented in a regular function in a c program? Thanks.
|
```
dup2( filedes, filedes2 );
```
means
```
close( filedes2 );
fcntl( filedes, F_DUPFD, filedes2 );
```
You can do
```
close(0);
dup(fd);
```
subject to race conditions, since dup2 atomic function but close and dup include two function calls.
|
I want to concatenate one word and one number to a single identifier like using the ## preprocessor operator, and use this to index an array. However, it has to happen at runtime. Ideally, something like this:
```
#include <stdio.h>
#define RUNTIME_CONCAT(a,b) //Insert concatenating operation here
int main(){
int foo1[2][1] = {{2}, {5}};
int foo2[2][1] = {{6}, {9}};
/*
By some means acquire number a here
*/
int* print_val = RUNTIME_CONCAT(foo, a)[1];
printf("Value: %d\n", *print_val);
return 0;
}
```
Is this possible?
|
the following shows how to concatenate two item together at runtime
```
char myword[] = "the word";
int mynumber = 27;
char *myarray = malloc( 100 ); //note 100 is much larger than needed
sprintf( &myarray[ strlen(myarray) ], "%s%d", myword, mynumber );
```
after the above is executed, myarray[] will contain:
```
"the word27"
```
|
I have a function to print debug logs which has to be toggled depending on the environment variable. Instead of checking the env var each time theprint_trace()is called, what should be the best method to store it and reuse that value?
```
void print_trace(const char* msg)
{
const char* s = getenv("DEBUG_TRACE");
if(!strcmp(s,"ON"))
printf(msg);
}
```
There is nomain()as this is a shared library.
|
You could save the result of the decision in a static variable.
```
void print_trace(const char* msg)
{
static int debug_on = -1; // -1 == not yet set
if (debug_on == -1) {
const char* s = getenv("DEBUG_TRACE");
debug_on = s && (strcmp(s, "ON") == 0);
}
if(debug_on)
printf("%s", msg);
}
```
|
I have a function to print debug logs which has to be toggled depending on the environment variable. Instead of checking the env var each time theprint_trace()is called, what should be the best method to store it and reuse that value?
```
void print_trace(const char* msg)
{
const char* s = getenv("DEBUG_TRACE");
if(!strcmp(s,"ON"))
printf(msg);
}
```
There is nomain()as this is a shared library.
|
You could save the result of the decision in a static variable.
```
void print_trace(const char* msg)
{
static int debug_on = -1; // -1 == not yet set
if (debug_on == -1) {
const char* s = getenv("DEBUG_TRACE");
debug_on = s && (strcmp(s, "ON") == 0);
}
if(debug_on)
printf("%s", msg);
}
```
|
In a terminal that does not support ANSI escape code, outputting a color control code like \033[0m will not only have no effect, but will also disturb the terminal.
I know a json formatting tool called jq, which judges whether the terminal can use ANSI escape code.
I want to know, how to realize this function through C programming language?
|
On Linux and probablyPOSIXsystems, you might useisatty(3)withSTDOUT_FILENO. See alsostdio(3)andfileno(3).
So your code would be
```
if (isatty(STDOUT_FILENO)) {
// standard output is a tty
...
}
```
and you have to bet that in 2021 most terminal emulators supportANSI TTY escapes.
By the way,jqis anopen sourcesoftware tool. You are allowed to download then study its source code.
Notice that the C programming language standard (readn1570or better) does not know about ttys. Read theTTY demystifiedweb page.
|
let's say I'm writing a function like strdup(), or any other function that uses malloc() for that matter. If I only call this function inside of printf() like this :
```
printf("%s", my_function(arg));
```
Is it possible to free the value returned from the function ? If yes, how ? To my knowledge, free() takes as argument a void pointer but how do you get that pointer if you never store de returned value in a variable ?
|
No - you'd need to call it as:
```
char *p;
p = my_function(arg);
printf("%s", p);
free(p);
```
EDIT
If you're into code abuse you could do something like:
```
for(char *p = my_function(arg); p != NULL ; free(p), p = NULL)
printf("%s", p);
```
But that's just hideous...
|
I have multiple threads attempting to log to the same file.
Each thread has aFILE *that points to the file. TheFILE *s were opened in append ('a') mode and are using line buffering.
Opening multipleFILE *to the same file within the same process is implementation defined according to ANSI C.
Would anyone happen to know the implementation specific behaviour for MacOS, FreeBSD and Linux, specifically whether eachFILE *will have its own line buffer, and whether there's any chance of lost or interleaved writes.
|
MacOS, FreeBSD and Linux are all POSIX systems. As such eachFILE*will have its own user-space buffer (or none if you disable it), and once that buffer is flushed it will be written to the underlying file descriptor. POSIX guarantees that append opened file descriptor writes are atomic, thus no data will be lost. As long as your data isn't split across multiple flushes it won't interleave with each other either.
|
How can I use GTK4 of C to get the pixels of the screen?
If GTK4 does not have an API, how can I get the pixels of the screen from Xlib?
|
I don't know about GTK4 but in X11:
XGetImageXGetWindowAttributes
Example:
```
//open display and get the root window of the default screen
//note: there could be more than one screen
Display *dpy = XOpenDisplay(NULL);
Window root = RootWindow(dpy, DefaultScreen(dpy));
//get the window attributes of the root window
XWindowAttributes attr;
XGetWindowAttributes(dpy, root, &attr);
//get the image of the root window
XImage* image = XGetImage(
dpy,
root,
0, 0, //attr.x, attr.y
attr.width, attr.height,
AllPlanes,
ZPixmap
);
```
Hint: IncludeX11/Xlib.hand compile with-lX11
|
The snippet below is being run by the child process as well but I don't know why because to my understanding the child's Pid should always be 0 so there's no reason for it to ever do anything below but print "I am child";
```
pid_t child_Pid1 = fork();
if((int)getpid() == 0) {
printf("I am child\n");
} else {
printf("I am parent\n");
}
```
|
getpid()always returns the current process's pid which is never zero, so in your current code, neither of the two processes does theexeclp.
You want to look atchild_Pid1instead ofgetpid(). In the child it returns 0instead ofthe child's pid.
|
How to handle the test case if I enter the number 10000
and I get 1 as a result instead of getting 00001.
How to handle this case?
```
#include <stdio.h>
int main() {
int n, rev = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &n);
while (n != 0) {
remainder = n % 10;
rev = rev * 10 + remainder;
n /= 10;
}
printf("Reversed number = %d", rev);
return 0;
}
```
|
Keep track of the number of digits in your number, and then print the number with a formatted length:
```
int numDigits = 0;
while (n != 0) {
...
numDigits++;
}
```
and then:
```
printf("Reversed number = %.*d", numDigits, rev);
```
|
im currently learning how to do binary search in C. well it worked "half-well". when i try to search for value (3,4,17,26,38) it shows the correct number of the index. but when i search for 1 or 40 or 10 or 21, it return -1 ( which is not found ), can somebody explain what is wrong?
```
#include<stdio.h>
int binarysearch(int arr[], int n, int data);
int main ()
{
int arr[9] = {1, 3, 4, 10, 17, 21, 26, 38, 40};
int n = sizeof(arr)/sizeof(arr[0]);
int data = 1;
printf("the data is located in index %d", binarysearch(arr, n, data));
return 0;
}
int binarysearch(int arr[], int n, int data){
int l = 0;
int r = n-1;
while(l < r){
int mid = (l + r)/2;
if(data == arr[mid]){
return mid;
}
else if(data > arr[mid]){
l = mid + 1;
}
else {
r = mid - 1;
}
}
return -1;
}
```
|
It can happen thatl == randarr[l] == data.
|
I have a this type of array:
```
uint8_t mArray[3] = {0x20,0x40,0x48};
```
But I need to convert this data like this as an integer 20,40,48. It's weird but the sensor sending this data like this. If the sensor wants to send decimal 20, it sends 0x20.
How can I convert"0x20"value to as a integer"20"in C?
|
You receive data in BCD format
```
int fromBCD(unsigned char b)
{
int result = (b & 0x0f) + 10 * (b >> 4);
return result;
}
```
|
This question already has answers here:What does the number in parentheses shown after Unix command names in manpages mean?(7 answers)Closed2 years ago.
for example execve(2) is the function of execve
login(1) is the function of login, what does the number means?
|
Those are the manual section numbers. From theman manual:
```
The table below shows the section numbers of the manual followed
by the types of pages they contain.
1 Executable programs or shell commands
2 System calls (functions provided by the kernel)
3 Library calls (functions within program libraries)
4 Special files (usually found in /dev)
5 File formats and conventions, e.g. /etc/passwd
6 Games
7 Miscellaneous (including macro packages and conventions),
e.g. man(7), groff(7)
8 System administration commands (usually only for root)
9 Kernel routines [Non standard]
```
|
I have a this type of array:
```
uint8_t mArray[3] = {0x20,0x40,0x48};
```
But I need to convert this data like this as an integer 20,40,48. It's weird but the sensor sending this data like this. If the sensor wants to send decimal 20, it sends 0x20.
How can I convert"0x20"value to as a integer"20"in C?
|
You receive data in BCD format
```
int fromBCD(unsigned char b)
{
int result = (b & 0x0f) + 10 * (b >> 4);
return result;
}
```
|
This question already has answers here:What does the number in parentheses shown after Unix command names in manpages mean?(7 answers)Closed2 years ago.
for example execve(2) is the function of execve
login(1) is the function of login, what does the number means?
|
Those are the manual section numbers. From theman manual:
```
The table below shows the section numbers of the manual followed
by the types of pages they contain.
1 Executable programs or shell commands
2 System calls (functions provided by the kernel)
3 Library calls (functions within program libraries)
4 Special files (usually found in /dev)
5 File formats and conventions, e.g. /etc/passwd
6 Games
7 Miscellaneous (including macro packages and conventions),
e.g. man(7), groff(7)
8 System administration commands (usually only for root)
9 Kernel routines [Non standard]
```
|
I say that it must be this function because it stops right after I enter an int and it doesn't read the print statement.
```
recipe** readAllRecipes(int numRecipes)
{
recipe** theRecipes = malloc(sizeof(recipe *) * numRecipes);
int i;
for(i = 0; i < numRecipes; i++)
{
scanf("%d", &theRecipes[i]->numItems);
printf("\n\n\t\t here in readAll for loop\n");
theRecipes[i] = readRecipe(theRecipes[i]->numItems);
}
return theRecipes;
}
```
|
Here's the problem:
```
scanf("%d", &theRecipes[i]->numItems);
```
theRecipise[i]is not initalized and you dereference it. Should allocate it first:
```
theRecipes[i] = malloc(sizeof(recipe));
scanf("%d", &theRecipes[i]->numItems);
```
but lower down I'm baffled by this:
```
theRecipes[i] = readRecipe(theRecipes[i]->numItems);
```
|
I'm very new to C and I have this function that is supposed to take in a word and output it in lowercase. This is what I have tried so far:
```
char *lowercase(const char *word) {
int length = strlen(word);
char *lower = malloc(sizeof(word));
lower[length] = '\0';
for(int i=0; i < length; i++) {
lower[i] = tolower(word[i]);
}
return lower;
}
```
This outputs ▒▒▒▒▒* for every word I enter.
|
malloc(sizeof(word))is not correct becausesizeof(word)is the same assizeof(char *)which gives the size of a single pointer. You need to allocate enough for the string including the NUL terminator. So should bemalloc(length+1).
|
I say that it must be this function because it stops right after I enter an int and it doesn't read the print statement.
```
recipe** readAllRecipes(int numRecipes)
{
recipe** theRecipes = malloc(sizeof(recipe *) * numRecipes);
int i;
for(i = 0; i < numRecipes; i++)
{
scanf("%d", &theRecipes[i]->numItems);
printf("\n\n\t\t here in readAll for loop\n");
theRecipes[i] = readRecipe(theRecipes[i]->numItems);
}
return theRecipes;
}
```
|
Here's the problem:
```
scanf("%d", &theRecipes[i]->numItems);
```
theRecipise[i]is not initalized and you dereference it. Should allocate it first:
```
theRecipes[i] = malloc(sizeof(recipe));
scanf("%d", &theRecipes[i]->numItems);
```
but lower down I'm baffled by this:
```
theRecipes[i] = readRecipe(theRecipes[i]->numItems);
```
|
I'm very new to C and I have this function that is supposed to take in a word and output it in lowercase. This is what I have tried so far:
```
char *lowercase(const char *word) {
int length = strlen(word);
char *lower = malloc(sizeof(word));
lower[length] = '\0';
for(int i=0; i < length; i++) {
lower[i] = tolower(word[i]);
}
return lower;
}
```
This outputs ▒▒▒▒▒* for every word I enter.
|
malloc(sizeof(word))is not correct becausesizeof(word)is the same assizeof(char *)which gives the size of a single pointer. You need to allocate enough for the string including the NUL terminator. So should bemalloc(length+1).
|
I am attempting to print an asterisk, but it prints a broken/special character in terminal print.
I initialize the char variable to be empty
```
char asterisk = "";
```
and set it depending on the result of:
```
asterisk = (cube % 3 == 0) ? "*\0" : "";
```
and print it using
```
printf("%d%c\n", cube, asterisk);
```
Instead, I get the output
```
Enter an integer
2000
0§
1
8
27§
64
125
216§
343
512
729§
1000
1331
1728§
```
I tried to add an escape sequence in the assignment of the non-empty char in the tertiary operator line, but this didn't solve the issue. I apologize for any simple errors, I am pretty new to C.
|
Your asterisk isn't achar, it's a string (char*, denoted by double quotes). If you want to print it correctly, you should use%s, not%c:
```
printf("%d%s\n", cube, asterisk);
/* Here --^ */
```
|
This question already has answers here:Splitting string into two integers(4 answers)Closed2 years ago.
```
string input = 1999-12-05
int year=1999
int month=12
int day=05
```
I want to split input to new three variable.Thank you.
|
You can usesscanf:
```
char* input = "1999-12-05";
int year;
int month;
int day;
sscanf(input, "%d-%d-%d", &year, &month, &day);
printf("year: %d, month: %d, day: %d\n", year, month, day);
```
demo
|
I am confused about these two structures from different tutorials:
```
typedef struct complex {
float real;
float imag;
} COMPLEX;
typedef struct {
float real;
float imag;
} COMPLEX;
COMPLEX c1;
```
Are they both correct? Why? and is it necessary to add the lowercase ofcomplexbefore struct? What is general situation?
|
With the first you can use either the type-aliasCOMPLEXorstruct complex.
With the second you have an anonymous structure which can only be used with the type-aliasCOMPLEX.
With that said, in C++ any structure name is also a type-name and can be used as a type directly:
```
struct complex { ... };
complex c1;
```
|
I want to achieve this code:
```
state(state);
```
So, first I declare a pointer to a function. I set the pointer to thestartfunction. And thestartfunction takes a pointer to a function also. I call the function using thestatepointer, and pass thestatepointer along for modification instart.How do I properly declare the function pointer created inmain, and how do I declare the prototypes?
|
Your intention isn't very clear but you can pass function pointers like this:
```
int g ((*myfunc)(int x))
{
stuff for g;
(*myfunc)(2);
}
int f (int a)
{
stuff for f;
}
main()
{
g (f);
}
```
|
I am trying to do object detection from a video file by usinghttps://github.com/pjreddie/darknet.
I've installedlibopencv-devfor opencv.
I've setopencv4=1inMakefile.
And run this code../darknet detector demo cfg/coco.data cfg/yolo-tiny-obj.cfg yolov3.weights data/1.mp4And got errorDemo needs OpenCV for webcam images.
Could anyone help me?
Thanks.
|
Try to clean make file and recompile darknet
```
make clean
make
```
You can load OpenCV from git and install sources
```
git clone https://github.com/opencv/opencv
cd opencv
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local ..
make -j7
sudo make install
```
And after recompile the darknet with
```
make clean
make
```
|
I want to read the source code of winsock, but I only see header which is winsock.h. where is winsock.c located I need to read the source code implementation so bad.
|
As to my knowledge Microsoft never released source code for that library. The best you can do is use Ida pro or simillar software to decompileWs2_32.dllorWs2_32.lib. That is the closest you will get to the source code, but it will be in pseudo C.
|
```
#include <curses.h>
int main(){
initscr();
refresh();
char s[25];
mvprintw(1,0,"Enter sentence: ");
refresh();
scanw("%s", s); // Input `one two`.
mvprintw(2,0,"%s\n", s); // This just prints `one`.
refresh();
getch();
endwin();
return 0;
}
```
Input isone two.
Output is justone, second half is missing.
Doesscanwnot treat spaces properly?
|
scanfunctions generally breaks at whitespaces, so instead of
```
scanw("%s", s);
```
do
```
scanw("%24[^\n]", s); // always do bounds checking
```
That is, read at most 24 non-newlines.
And, you should always check that the extraction works:
```
if(scanw("%24[^\n]", s) == 1) { ... }
```
If you mix input from here and there, consider using the "greedy" version that "eats" leftovers:
```
scanw(" %24[^\n]", s) // note the space at the beginning
```
|
This question already has answers here:Numeric value of digit characters in C(5 answers)Closed2 years ago.
```
while((c = getchar()) != EOF) {
if((c >= '0') && (c <= '9')) {
ndigits[length] = c;
length = length + 1;
}
}
```
I want to store each digit, in the array. But when I enter123and print the array, I get50 51 52. How can I fix this issue?
|
Characters are numbers too. In this case, you have ASCII codes, or at least the ASCII subset of UTF-8 encoded Unicode code points. The integer'1'is indeed 49,'2'is 50, etc. When you store them in your array, it stores the numerical value of the ASCII code for that number. If you want the number itself, you can do something like:
```
if((c >= '0') && (c <= '9'))
{
ndigits[length] = c - '0';
length = length + 1;
}
```
|
What is the correct OpenSSL C API function to read an elliptic curve public key in DER format that has already been read into a byte array?
The key was generated via the following command line arguments:
```
openssl ecparam -name prime256v1 -genkey -noout -out private.der -outform der
openssl ec -in private.der -pubout -out public.der -outform der
```
|
You can used2i_PUBKEYfor this purpose. See the man page here:
https://www.openssl.org/docs/man1.1.1/man3/d2i_PUBKEY.html
|
This question already has answers here:Numeric value of digit characters in C(5 answers)Closed2 years ago.
```
while((c = getchar()) != EOF) {
if((c >= '0') && (c <= '9')) {
ndigits[length] = c;
length = length + 1;
}
}
```
I want to store each digit, in the array. But when I enter123and print the array, I get50 51 52. How can I fix this issue?
|
Characters are numbers too. In this case, you have ASCII codes, or at least the ASCII subset of UTF-8 encoded Unicode code points. The integer'1'is indeed 49,'2'is 50, etc. When you store them in your array, it stores the numerical value of the ASCII code for that number. If you want the number itself, you can do something like:
```
if((c >= '0') && (c <= '9'))
{
ndigits[length] = c - '0';
length = length + 1;
}
```
|
What is the correct OpenSSL C API function to read an elliptic curve public key in DER format that has already been read into a byte array?
The key was generated via the following command line arguments:
```
openssl ecparam -name prime256v1 -genkey -noout -out private.der -outform der
openssl ec -in private.der -pubout -out public.der -outform der
```
|
You can used2i_PUBKEYfor this purpose. See the man page here:
https://www.openssl.org/docs/man1.1.1/man3/d2i_PUBKEY.html
|
```
// Buffer size
#define BUFSIZE (32)
// The buffer
int buf[BUFSIZE];
// Clearing the buffer:
// 1st way
memset(buf, 0, BUFSIZE*sizeof(int));
// or
// 2nd way
memset(buf, 0, sizeof(buf));
```
To get the size of the buffer in bytes, needed formemset, shouldsizeofbe called on theint(1st way) or on the array (2nd way)? Does it matter?
|
You should use the second variant.
It is more robust to changes of array size or type:
The first variant will fail if:
```
int buf[NEW_BUFSIZE]; // changed size
memset(buf, 0, BUFSIZE*sizeof(int)); // will partially initialize or overflow
memset(buf, 0, sizeof(buf)); // works fine
```
or
```
new_type buf[BUFSIZE]; // changed type
memset(buf, 0, BUFSIZE*sizeof(int)); // will partially initialize or overflow
memset(buf, 0, sizeof(buf)); // works fine
```
BTW.
There is no need to use parenthesizes insizeofif an operand is an expression.sizeof bufsuffices.
|
```
union one
{
int *ui;
int u;
} yoo;
void main()
{
printf("%d\m", sizeof(yoo))
}
```
Why is the sizeof union not 8 bytes but 4 bytes even if I am using pointer in my union?
I am using a 64 bit machine.
|
Its because you have compiled it as 32-bit executable.
|
This question already has answers here:self referential struct definition?(9 answers)Closed2 years ago.
If I have this:
```
typedef struct {
foo_t *bar;
} foo_t;
```
then I get errors likeerror: unknown type name ‘foo_t’. I could make bar a void* and cast later, but that seems like the wrong way to go.
Is there a proper way to resolve this chicken and egg problem?
|
Something like this
```
typedef struct foo_t {
struct foo_t *bar;
} foo;
```
So your type is foo, which is the same as struct foo_t
|
My Linux is Arch, my configuration is as follows:
```
Kernel: 5.13.13-arch1-1
Packages: 490 (pacman)
Shell: zsh 5.8
WM: dwm
Terminal: st
Terminal Font: Source Code Pro
```
When I use C output statements, such asprintfandputchar('A');, if I don't add \r or \n at the end, I will get an extra '%' character on the terminal.
```
$ ./a.out
A%
$
```
This problem has troubled me for a long time, so that I don't know who is the problem, with dwm? With sh? With zhs?
|
This is a feature of zsh to show when a program has ended without a final newline and to distinguish zsh’s command prompt from the program output.
You can disable it with the zsh commandPROMPT_EOL_MARK=''.You can also set it to something else, such asPROMPT_EOL_MARK=' -- The program did not end with a newline.'.
|
```
while(1) {
printf("Hello World");
}
```
We know this would keep on printing theHello Worldstring for infinite times. My goal is to print this for 10 seconds. I tried this:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int ticks = clock();
while(ticks <= 10000000000) {
printf("Hello World\n");
}
return 0;
}
```
It still goes for an infinite time. Please let me where did I made the mistake.
|
I mainly just want to print for like 10 seconds
Then I suggest using the standardtime()function.
```
#include <stdio.h>
#include <time.h>
int main() {
time_t end_time = time(NULL) + 10; // calculate the end time
while(time(NULL) < end_time) { // loop until the end time is reached
printf("Hello World\n");
}
}
```
|
I'm trying to use the Makefile to compile source codes into 2 executable applications.
How do I properly compile two executable applications at once using a single Makefile?
|
The problem is that both source files are being included in both versions of the executable, which means that there are two separate instances of main.
Replace line:
```
$(EXECUTABLE): $(OBJ_EXE) $(LIBRARY)
```
with
```
%: %00.o $(LIBRARY)
```
This will ensure that onlyclient00.ois used to buildclientandserver00.ois used to buildserver.
|
```
while(1) {
printf("Hello World");
}
```
We know this would keep on printing theHello Worldstring for infinite times. My goal is to print this for 10 seconds. I tried this:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int ticks = clock();
while(ticks <= 10000000000) {
printf("Hello World\n");
}
return 0;
}
```
It still goes for an infinite time. Please let me where did I made the mistake.
|
I mainly just want to print for like 10 seconds
Then I suggest using the standardtime()function.
```
#include <stdio.h>
#include <time.h>
int main() {
time_t end_time = time(NULL) + 10; // calculate the end time
while(time(NULL) < end_time) { // loop until the end time is reached
printf("Hello World\n");
}
}
```
|
I'm trying to use the Makefile to compile source codes into 2 executable applications.
How do I properly compile two executable applications at once using a single Makefile?
|
The problem is that both source files are being included in both versions of the executable, which means that there are two separate instances of main.
Replace line:
```
$(EXECUTABLE): $(OBJ_EXE) $(LIBRARY)
```
with
```
%: %00.o $(LIBRARY)
```
This will ensure that onlyclient00.ois used to buildclientandserver00.ois used to buildserver.
|
I'm new to C programming so please forgive me if this sounds like a dumb thing to do.
I had an idea in attempt to make my code a bit more readable and the idea is to#definelogical operators such as#define OR ||.
If anyone can direct me is this bad or good practice, is it common etc... and also if it has any side effects, I would be grateful.
Thanks in advance.
|
Alternate names for this and other operators are already part of standard C. Using#include <iso646.h>defines:
NameReplacementand&&and_eq&=bitand&bitor|compl~not!not_eq!=or||or_eq|=xor^xor_eq^=
|
While debugging the main function in Debug Console, I want to create a new variable called 'b' and assign a integer value 9 to it, but it compalins about 'b' being undefined. Why am I getting this error and how can I get around it?
```
-> int b = 9;
identifier "b" is undefined
```
```
#include <stdio.h>
#include <stdint.h>
int main()
{
int i = 0;
printf("i is %d", i);
return 0;
}
```
|
In gdb in general, you can defineconvenience variableslike so:
```
set $b = 9
```
in order to do this from the Debug Console, you must use the-execprefix:
```
-exec set $b = 9
```
and you can then write lines like
```
-exec p i + $b
```
(whereiis your C variable).
In picture:
and you can even use these convenience variables in places like the Watch interface:
|
I'm learning about process allocation.
Take this code block for example:
```
int main(){
pid_t pid = fork();
if(pid == 0){
while(1)
printf("Child ");
} else {
for(int i = 0; i<1000;i++)
printf("Parent ");
kill(pid,SIGTERM);
printf("\n%d \n ", pid);
}
}
```
pid = 0is the child process,pid > 0is the parent process.kill(pid,SIGTERM)is executed by the parent with it's ownpid, yet it kills the child and not itself. Why?
|
As @Siguza mentioned in the comments, you should re-read the documentation offork.forkreturns a positive value ofpidto the parent process. That value is the PID of thechildprocess. Therefore,kill(pid, SIGTERM)sends the signal to the child and not the parent.
|
While debugging the main function in Debug Console, I want to create a new variable called 'b' and assign a integer value 9 to it, but it compalins about 'b' being undefined. Why am I getting this error and how can I get around it?
```
-> int b = 9;
identifier "b" is undefined
```
```
#include <stdio.h>
#include <stdint.h>
int main()
{
int i = 0;
printf("i is %d", i);
return 0;
}
```
|
In gdb in general, you can defineconvenience variableslike so:
```
set $b = 9
```
in order to do this from the Debug Console, you must use the-execprefix:
```
-exec set $b = 9
```
and you can then write lines like
```
-exec p i + $b
```
(whereiis your C variable).
In picture:
and you can even use these convenience variables in places like the Watch interface:
|
I'm learning about process allocation.
Take this code block for example:
```
int main(){
pid_t pid = fork();
if(pid == 0){
while(1)
printf("Child ");
} else {
for(int i = 0; i<1000;i++)
printf("Parent ");
kill(pid,SIGTERM);
printf("\n%d \n ", pid);
}
}
```
pid = 0is the child process,pid > 0is the parent process.kill(pid,SIGTERM)is executed by the parent with it's ownpid, yet it kills the child and not itself. Why?
|
As @Siguza mentioned in the comments, you should re-read the documentation offork.forkreturns a positive value ofpidto the parent process. That value is the PID of thechildprocess. Therefore,kill(pid, SIGTERM)sends the signal to the child and not the parent.
|
I'm totally new in C and I want to write a function :
```
#include <unistd.h> //import write...
void ft_putchar(char str[20]) {
write(1, &str, 19);
}
char main() {
char str2[20] = "GeeksforGeeks";
ft_putchar(str2[20]);
return(0);
}
```
|
Hope this will help you a bit :)
```
#include <unistd.h> //import write...
void ft_putchar(char *str) { // the size of the buffer is not required
write(1, str, strlen(str)); // 2nd argument is a char*, not a char **
// 3rd one is the actual length of your
// string, not the size of the buffer
}
int main() {
char str2[20] = "GeeksforGeeks";
ft_putchar(str2); // the size of the buffer is not required
return(0);
}
```
|
I am trying to store an array in the backup RAM on STM32F4 MCUs, so the content can survive system power cycle such as reboot caused by watchdog.
```
typedef struct {
//
} Foo;
Foo foos[40];
```
Is there a way to make sure foos points to the start of backup RAM(BKPSRAM_BASE) ?
Thanks in advance.
|
Edit your linker script and add section which will be in your backup RAM.
to memory segments:
```
MEMORY
{
/* other segments */
BKPRAM (rw) : ORIGIN = 0x40024000, LENGTH = 4k
}
```
Add section
```
.bkpram :
{
_BKPRAM_START = .;
. = ALIGN(4);
KEEP(*(.bkpram))
_BKPRAM_END = .;
} >BKPRAM
```
Then:
```
__attribute__((section(".bkpram"))) Foo foos[40];
```
But remember that access to this SRAM has to be enabled first.
|
All the answers tothis questionabout passing an array from C to Rust usestd::slice::from_raw_partsto convert the raw C pointer and some length information into a Rust. In an embedded context (MOS 6502in my case), there might not be astdlibrary available. Soin a#![no_std]context, what is the nicest way of passing an array from C to Rust for (potentially mutable) processing?
|
Whilestd::slice::from_raw_partsis not available in ano_stdenvironment,core::slice::from_raw_partsisavailable, so you can simply use that.
In general, anything that is instdand not somehow platform dependent (so, not I/O, heap allocation and the like) should also be available inno_stdenvironments through thecorecrate.
|
I want include all header files from solutions explorer like this:
without add all directories with this option:
Is there an easy way to tell VS2019 to use and link all header files from solutions explorer automatically?
Why?
If I have a lot of source code directories and in each directory are the header files... I need to add each directory manually.
Other simple Example:The directory structure it this one:And I need to add #include "test2.h" in "test1.c" and in this case VS cant find the header file. So the header "test2.h" is NOT where the test1.c is. Why VS dont find the header automatically by solutions explorer?
|
Ok. There is no solution.
Possible alternatives:
All headers are in one place and one include path is required.Or headers in the same directory like the source code files.Or headers need to be include like #include "../../header.h"
Thanks.
|
I am getting a segmentation fault whenever I try to print the value stored within a struct. Using Valgrind, I was able to narrow it down a bit to one block of code, but I am unsure what I am doing wrong. Am I initializing my struct incorrectly?
Whenever I run valgrind, it tells me that there is aninvalid write of size 8where I saynewList->data = d.
```
typedef struct List {
struct List *np[Ends]; // next/prev neighbors
Data data;
} *List;
typedef void *Data;
static void put(Data d) {
List newList = malloc(sizeof(List));
newList->data = d;
}
```
|
This is an example of why it's bad practice totypedefa pointer.
BecauseListis defined as an alias forstruct List *,sizeof(List)gives you the size of a pointer, not the size of the struct. As a result, you're not allocating enough memory.
You instead want eithermalloc(sizeof(struct List))or (preferably)malloc(sizeof *newlist)
|
Many functions of the C library are clearly marked as thread-safe or not thread-safe. For example, when I look at the manual ofgmtime(3)there is a nice table that shows which of these functions are thread-safe and which aren't.
Looking at the manual page of thestat(2)function, it doesn't say one way or the other. Are functions supposed to be thread safe unless we are told otherwise?
Reading up thePOSIX Safety Conceptdid not really clearly state that a function not marked as unsafe is safe. Maybe I missed a sentence somewhere?
|
The POSIX page onThread Safetysays that all functions are thread-safe except the ones listed there.stat()is not in the list, nor are any of the variants (lstat(),fstat_at(),fstat()). So it should be thread-safe.
|
I am trying to print a string in reverse using recursion. However, the program below does not work as expected. What is the cause?
```
#include <stdio.h>
int main()
{
char arr[]="rama";
fun(arr);
}
int fun(char *p)
{
static int i=0;
if((p[i]) == '\0')
return;
else
{
i++;
fun(p[i]);
printf("%c", p[i]);
}
}
```
|
probably you're looking for:
```
void fun(char *p) {
if (*p) {
fun(p + 1);
printf("%c", *p);
}
}
```
|
Linuxnetdevice(7)interface introduces a number ofSIOCGIF*constants, for example,SIOCGIFNAME.
I suppose the latter reads as "socket i/o ?? interface name", where??stands for "CG".
So what is "CG" then? Shall be something simple, but I'm a little stuck here. ( And I'm in a habit of knowing of what my identifiers mean, hence the question )
|
ProbablySocketI/OControl -GetInterFaceNAME.
It seems obvious thatioctlstands for "I/O Control" (but if not then just consider that IOC stands forIOCTL)
We can see theTIOCprefix used onsome olderTerminal I/O Controls. T for Terminal and S for Socket - makes sense.
You can also notice the Get functions have G and the Set functions have S.
And IFNAME seems clear enough.
|
I want to do something similar to the code below but usingptr[i]
```
printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks);
```
|
ptr->xis the same as(*ptr).x.
*(ptr + i)is the same asptr[i].
Thus, by the transitive property,(ptr + i)->xis the same as:
```
ptr[i].x
```
|
This question already has an answer here:Printing UTF-8 strings with printf - wide vs. multibyte string literals(1 answer)Closed2 years ago.
```
#include <stdio.h>
int main(int argc, const char * argv[]){
for (char i='A'; i<='Z'; i++){
printf(" %c ",i);
if (i=='N')
printf("%c",165);
}
return 0;
}
```
|
In order to print/use the character Ñ is a program, you need to be using a character set that supports it. The easiest is probably if your system supports unicode (which most do these days), which would allow you to do something as simple as
```
printf("\u00d1");
```
which will print the unicode character codepoint #00D1, which is Ñ
|
Why I am getting a warning when shrinking arrays?There is no any way of losing the pointer value.
Warning C6308 'realloc' might return null pointer: assigning null pointer to 'arr_all_guests', which is passed as an argument to 'realloc', will cause the original memory block to be leaked.
arr_all_guests = (char**)realloc(arr_all_guests,--(*guest_counter) * sizeof(char*));
|
It means that as it is written the functionrealloccan return a null pointer. In this case an access to all the early allocated memory will be lost
```
arr_all_guests = (char**)realloc(arr_all_guests,--(*guest_counter) * sizeof(char*));
```
because the original pointerarr_all_guestswill be reassigned with a null pointer.
You need to use a temporary pointer as for example
```
char **tmp = realloc(arr_all_guests, ( *guest_counter - 1 ) * sizeof(char*));
if ( tmp != NULL )
{
arr_all_guests = tmp;
--*guest_counter;
}
```
|
Linuxnetdevice(7)interface introduces a number ofSIOCGIF*constants, for example,SIOCGIFNAME.
I suppose the latter reads as "socket i/o ?? interface name", where??stands for "CG".
So what is "CG" then? Shall be something simple, but I'm a little stuck here. ( And I'm in a habit of knowing of what my identifiers mean, hence the question )
|
ProbablySocketI/OControl -GetInterFaceNAME.
It seems obvious thatioctlstands for "I/O Control" (but if not then just consider that IOC stands forIOCTL)
We can see theTIOCprefix used onsome olderTerminal I/O Controls. T for Terminal and S for Socket - makes sense.
You can also notice the Get functions have G and the Set functions have S.
And IFNAME seems clear enough.
|
I want to do something similar to the code below but usingptr[i]
```
printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks);
```
|
ptr->xis the same as(*ptr).x.
*(ptr + i)is the same asptr[i].
Thus, by the transitive property,(ptr + i)->xis the same as:
```
ptr[i].x
```
|
This question already has an answer here:Printing UTF-8 strings with printf - wide vs. multibyte string literals(1 answer)Closed2 years ago.
```
#include <stdio.h>
int main(int argc, const char * argv[]){
for (char i='A'; i<='Z'; i++){
printf(" %c ",i);
if (i=='N')
printf("%c",165);
}
return 0;
}
```
|
In order to print/use the character Ñ is a program, you need to be using a character set that supports it. The easiest is probably if your system supports unicode (which most do these days), which would allow you to do something as simple as
```
printf("\u00d1");
```
which will print the unicode character codepoint #00D1, which is Ñ
|
Why I am getting a warning when shrinking arrays?There is no any way of losing the pointer value.
Warning C6308 'realloc' might return null pointer: assigning null pointer to 'arr_all_guests', which is passed as an argument to 'realloc', will cause the original memory block to be leaked.
arr_all_guests = (char**)realloc(arr_all_guests,--(*guest_counter) * sizeof(char*));
|
It means that as it is written the functionrealloccan return a null pointer. In this case an access to all the early allocated memory will be lost
```
arr_all_guests = (char**)realloc(arr_all_guests,--(*guest_counter) * sizeof(char*));
```
because the original pointerarr_all_guestswill be reassigned with a null pointer.
You need to use a temporary pointer as for example
```
char **tmp = realloc(arr_all_guests, ( *guest_counter - 1 ) * sizeof(char*));
if ( tmp != NULL )
{
arr_all_guests = tmp;
--*guest_counter;
}
```
|
I can't find any simple C source file or library to parse geojson files (implementingrfc7946standard).
Maybe such parsers exist in projects like GRASS or GDAL? But I still have a little trouble navigating the world of C libraries.
Some tracks ?
|
GeoJSONis in JSON format, so you can use JSON parsers. There are several out there:
https://github.com/search?l=C&q=json+parser&type=Repositories
You should add checks and other stuff yourself.
If you need a certain representation of data, you can write it yourself. Mapbox wrote aC++ version of GeoJSON parserfor converting GeoJSON into geometry.hpp representation based onRapidJSONin less than 1k lines of code.
Astandard-compliant(RFC 7946) implementation of GeoJSON in C can be foundinside SpatiaLite, but may be it's easier for you to use typical JSON parsers instead. You can take a look invirtualgeojson.cif you want to use this library.
|
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.Closed2 years ago.Improve this question
I don't know why we have limited memory in Embedded System.
Why we can't use another memory or increase it instead of using high level languages like Rust&go ?
Technology offered many types of memory from lowest memories to 2 TB memories on a sdcard.
Anyway why memory is too important ?
|
Adding memory (and bus to access it, and chip pins for the bus, and a stronger pwoer supply to power it, and more board space, etc.), adds cost; in the most tightly constrained systems every penny counts, so you don't want to spend any more pennies on memory if you can avoid it.
|
I am wondering what happens for variables & their content after STM32 mcu enters low power mode or exit from it? for example in sleep mode or standby.
do their content remove or survived?
best!
|
You can preserve or not - it is usually (depending on the mode) up to the programmer. Memory consumes power so very often it is more energy efficient to reinitialize RAM after wake up (I do it sometimes in my projects)
Example: STM32L476:
|
The question is: what is the difference between
```
char c = 'a';
char *p = &c;
```
AND
```
char c = 'a';
char *p;
*p = &c;
```
The result of execution is very different (the first as expected and the second is compilation error). I have just started "Pointers", so please, be patient about it.
|
The * has different meanings when declaring a variable verses assigning an existing variable.
When declaring the variable * means that the variable p is a pointer to a char instead of just a char.
On the other hand in the assignment to an existing variable the * dereferences a pointer. That is rather than working on the pointer the asaignment would work on the location pointed to by the pointer,
So your second example is doubly broken
Firstly it dereferences an uninitialized pointer. Secondly when it tries to make the assignment it has a type mismatch.
|
I have the following data type:
```
typedef struct {
int num;
char *str;
} NumStr;
```
And the variable x:
```
NumStr *x;
```
How can I allocate heap space for the str pointer? I've tried
```
x->str = (char*)malloc(sizeof(char*));
```
But it isn't working.
Im pretty new to C, so I apologize if I am missing something obvious. Thanks in advance.
|
A pointer likeNumStr*points to somewhere in memory - and so you need to allocatexbefore you assign tox->str:
NumStr* x = malloc(sizeof(*x));.
Note that there isno need to cast to(char*)as you've done - and don't forget tofree(x->str);and thenfree(x);in that specific order.
|
I'm a beginner in data structures. I learnt that SqLists are starting from 1, when the arrays inside SqLists are from 0.The question isif I create a loop, which of the following representation is better? Will the other one be weird?
```
//i=0 according to arrays
for(int i=0;i<L->length;++i)
L->data[i]=givenArray[i];
```
```
//i=1 according to SqList
for(int i=1;i<=L->length;++i)
L->data[i-1]=givenArray[i-1];
```
|
There is nothing wrong with either ways.With that aside, the first way of writing is more clear and often used when writing programs (in any language).
If you are programming alone, it doesn't really matter, just pick your style and stick to it.But, if you want to adhere to global programming conventions, and make your code more readable and accessible to other people, stick for the first style.
|
please explain it to me that what is the dfference betweenputs(string name)andfputs(string name,stdout)
both of them have the same output especially when I usefgets(string name,n,stdin)for get std size of a string for a safe code ,
but after that and for print to output , what is the difference between them although both of them have the same output?
|
putsappends a newline to the string, andfputsdoesn't.
Otherwise there is no difference, except of course that withfputsyou can specify a different stream, whileputsalways writes tostdout.
|
How to clear the flag set byshutdown()system call in Linux socket program?
I want to enable writes to the socket which is right now locked for writes with ashutdown(sockfd, SHUT_WR)call.
|
Unfortunately what you ask is impossible.
Issuingshutdown( sockfd, SHUT_WR );, in fact, forcesFINpacket to be sent.
Have a look to the TCP state machine:
As you can see, when aFINpacket is sent from an active socket (stateESTABLISHED) the stateCLOSE_WAITis reached, and it is a transition that cannot be"undone"in any way.
So it is not a matter of"removing a flag": the socket is set to an irreversible path tha leads to its closure, waiting just for a lastACKto complete its "life".
|
please explain it to me that what is the dfference betweenputs(string name)andfputs(string name,stdout)
both of them have the same output especially when I usefgets(string name,n,stdin)for get std size of a string for a safe code ,
but after that and for print to output , what is the difference between them although both of them have the same output?
|
putsappends a newline to the string, andfputsdoesn't.
Otherwise there is no difference, except of course that withfputsyou can specify a different stream, whileputsalways writes tostdout.
|
How to clear the flag set byshutdown()system call in Linux socket program?
I want to enable writes to the socket which is right now locked for writes with ashutdown(sockfd, SHUT_WR)call.
|
Unfortunately what you ask is impossible.
Issuingshutdown( sockfd, SHUT_WR );, in fact, forcesFINpacket to be sent.
Have a look to the TCP state machine:
As you can see, when aFINpacket is sent from an active socket (stateESTABLISHED) the stateCLOSE_WAITis reached, and it is a transition that cannot be"undone"in any way.
So it is not a matter of"removing a flag": the socket is set to an irreversible path tha leads to its closure, waiting just for a lastACKto complete its "life".
|
I am quite new to C and i am trying to use a variable twice in one line:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int myAge = 10;
char PL = "C";
printf("I am Rydex (not my real name) and i am %d years old. This was made using %s", myAge, PL);
}
```
But, when i run it, I get:
I am Rydex (not my real name) and i am 10 years old. This was made using (null)
Instead of the value in the variable "PL" i get "(null)". Can someone please help me?
|
PL is a string, not a char. You need to change the declaration to:
```
char* PL = "C";
```
The double-quoted delimiter is for a string constant, which has a span of characters terminated with a null character \0. A single quote delimiter is to define a single character constant. Here's a goodwrite-up
|
I have this char array:
```
char rcv_str = 1001ff;
```
But I want to do something like this:
```
id = 10;
sts = 01;
```
Until then I couldn't make this separation. Any suggestions?
|
If your rcv_str is always the same size you could do some thing like this:
```
#include <stdio.h>
#include <string.h>
int main()
{
char rcv_str[] = "1001ff";
char id[3];
char sts[3];
strncpy ( id, rcv_str, 2 );
strncpy ( sts, &rcv_str[2], 2 );
// Null terminate strings
id[2] = 0;
sts[2] = 0;
printf("id: %s sts: %s\n", id, sts);
return 0;
}
```
|
First syntax
```
int i;
for(i=0;i<5;i++)
{
printf("Hello");
}
```
Second syntax
```
for(int i=0;i<5;i++)
{
printf("Hello");
}
```
I ask my professor he saidboth are samebut I am not satisfied with this answer.
Please tell whether he was correct or not ?
is both syntax are same or different in some aspect?
|
Both code snippets will produce the same output, but there is a difference in meaning.
In the first code snippet, the variableiwill continue to exist after the for-loop, whereas in the second code snippet, thescopeof the variableiis limited to the body of the for-loop.
Additionally, the second code snippet is not valid for versions of C before C99, as these did not allow the declaration of a variable inside of a for-statement.
It is generally preferred to limit the scope of variable as much as possible, as this results in simpler code.
|
in the code:
```
char * strarray[] = {"first", "second", "third", "fourth", "fifth"};
```
I thought strarray[5] would be NULL since it is the value outside of the array but it is not and strarray[6] is null.
```
printf("%d %d\n", NULL == strarray[5], NULL == strarray[6]);
```
i get 0 1
|
Accessing uninitialized memory is undefined behavior, you cannot
expect your program to work in a predictable manner. Change the
compiler, compiler options, OS, and your program may crash instead of
working. Do not expect on undefined behavior and always look at all
compiler warnings.
|
When developing the firmware for STM32 in IAR, I encountered the following:
```
typedef enum ll{
A = 0b00000000000000000000000000000000,
B = 0b00000000000000000000000000000011,
} lol;
```
Error[Pe067]: expected a "}" PROJ\Core\Src\main.c 72(2d line)
But,
```
typedef enum ll{
A = 0x00000000,
B = 0x11111111,
} lol;
```
is compile successfully.
I know all of this code work in another IDE n compilers.
But what happens in my case? Why number with 0b brings errors? Maybe needed set some configure for compiler?
|
Binary literals (i.e. integers with the0bprefix, such as0b010101) arenotpart of the (standard) C language. However, theyarepart of C++ (since C++14), and some compilers (notably GCC) support them as an extension in C.
|
in printf a field width may be specified as '*'
```
printf("%*s", 99, str);
```
how can i do the same in scanf without it being interpreted as an assignment suppression character ?
Example1:
```
char str[100];
scanf("%**s %s", 10, str);
```
the 1st asterisk should be interpreted as assignment supression and the 2nd as the field width, thus the above scanf should read and ignore 10 characters, and then read and store the next string in str.
Example2:
```
char str[100];
scanf("%*s", 10, str);
```
the 1st asterisk should be interpreted as the field width, so the above scanf should read 10 characters and store them in str
|
You can't do this.scanfdoesn't work in the same way asprintf. Specifically:
an asterisk in the format string always means 'suppress the assignment'field widths must appear as literals in the format string; they cannot appear as parameters ofscanf
Full documentationhere.
|
Soadb shellgives one a linux terminal into an android phone, when it is connected to a computer. One can run all the standard linux commands likelsandcatinside the android phone, and explore the android filesystem using theadb shell.
Now I wonder, is it possible to use a C/C++ compiler such asclangorgccto compile and execute a C/C++ program in the android phone, as on linux? I am not talking about android app development here, I mean a linux command line C/C++ program for android. Also, can I use the C standard library and linux system calls such asfork(),exec(),kill(), and working with file descriptors, in the androidadb shell, just as I would do it on linux?
|
Yes. You can . For that you need copy your compiler exe's to android file system. From there you can easily call. Same time make sure that all pre-builed libs in android PATH folder.
|
I am making a program for my arduino that needs to access a eeprom but I need to find a way to send it a address, I have a int I would like to convert into binary and send to the eeprom but I need to split it into a array so I can send the data to the eeprom.
I cant think of any way to do this and I have asked some people for help but they couldn't figure out how to ether.
|
```
void int_to_bin_array(unsigned int in, int count, int* out)
{
unsigned int mask = 1U << (count-1);
int i;
for (i = 0; i < count; i++) {
out[i] = (in & mask) ? 1 : 0;
in <<= 1;
}
}
int main(void)
{
int binary_array[8];
const int bin_size = 8;
int decimal = 15;
int_to_bin_array(decimal, bin_size, binary_array);
return 0;
}
```
|
This code below prints two characters HI using i=72 and j=73.Is there a similar method to print HI when k=7273?
```
#include <stdio.h>
int main() {
unsigned short i = 72;
unsigned short j = 73;
unsigned short k = 7273;
printf("%c%c",(char)i, (char)j);
return 0;
}
```
https://godbolt.org/z/8cGMMM156
|
You can simply do:
```
printf ("%c%c", k / 100, k % 100);
```
(you don't need any casts).
|
I found the following snippet of code .
```
#define f(g,g2) g##g2
main() {
int var12=100;
printf("%d",f(var,12));
}
```
I understand that this will translate f(var,12) into var12 .
My question is in the macro definition, why didn't they just write the following :
```
#define f(g,g2) gg2
```
why do we need ## to concatenate text, rather than concatenate it ourselves ?
|
If one writesgg2the preprocessor will perceive that as a single token. The preprocessor cannot understand that that is the concatenation ofgandg2.
|
I figured out why the following loop was giving mebad input, reWhy is “while ( !feof (file) )” always wrong?
```
do {
if (fread(buf, 1, siz, stdin) != siz) {
if (feof(stdin))
fputs("bad input\n", stderr);
else /* implying ferror(stdin) */
perror("fread() failed");
return EXIT_FAILURE;
}
use(buf);
} while (!feof(stdin));
```
Is it inevitable to write some auxiliary function/weird call for properly(?) checking EOF along the lines ofungetc(getchar(), stdin)or is there a better way?
|
I'd do something like
```
size_t nread;
while ((nread = fread(buf, 1, siz, stdin)) == siz) {
use(buf);
}
if (feof(stdin)) {
if (nread == 0) {
/* Normal EOF; do nothing. I would not actually
write this branch. :-) */
} else {
/* Short read. */
fputs("bad data\n", stderr); }
}
} else {
perror("fread");
}
```
|
My system is debian 10. I want to implement atomic operations, but I find that there are no header files and API functions for atomic operations. What's the matter? Isn't atomic operation a kernel level function? Why not?
test_atomic.c:
```
#include <stdio.h>
#include <asm/atomic.h>
int main(void)
{
printf("test atomic!\n");
return 0;
}
```
compile error:
```
# gcc test_atomic.c
test_atomic.c:2:10: fatal error: asm/atomic.h: No such file or directory
#include <asm/atomic.h>
^~~~~~~~~~~~~~
compilation terminated.
```
man atomic API error:
```
# man atomic_add
No manual entry for atomic_add
```
|
For using atomic operations you need to use#include <stdatomic.h>.
|
I'm working with a C-functionfoo(FILE* file)that outputs some text to a file.
Rather than write to a .txt file, I'd likefooto write to the console.
Is there a way to pass 'the console' as a FILE*? (And if so, how) ?
(foois part of a library and I can't edit the source code directly)
|
There's a special file object calledstdoutthat will write to the console (assuming the shell didn't redirect anything).
```
foo(stdout);
```
|
There is achar *strchr( const char *str, int ch )function defined in<string.h>.
It has no boundary, after which it stops the search.
Is there a similar function somewhere, which you can pass a boundary to?
Edit:
I have achar* posand a length of asubstringand I want to find a specific ASCII character in it, but I don't want it to search up to the very null-terminator, because I don't care for the second part of the character sequence.
|
You can try:
void* memchr( const void* ptr, int ch, size_t count )
|
```
#include <stdio.h>
int main ()
{
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
```
here in the code,the fgetc(fp) use the int as this return type,so why we use "printf("%c",c);" rather than "print("%d",c);"
|
In aprintfformat string,%cmeans “convert theintargument to anunsigned charand print the character it is the code for.”
%dmeans “convert theintargument to a decimal numeral and print that numeral.”
|
The C standard says that
All accessible objects have values, and all other components of the abstract machine218)have state, as of the time the longjmp function was called, except that the values of
objects of automatic storage duration that are local to the function containing the
invocation of the corresponding setjmp macro that do not have volatile-qualified type
and have been changed between the setjmp invocation and longjmp call are
indeterminate."218) This includes, but is not limited to, the floating-point status flagsand the state of open files.
(emphasis added)
What is the goal of this requirement, and how do implementations deal with it?
|
It says "as of the time thelongjmpfunction was called", not setjmp, so the requirement is simply tonotsave/restore too much state, which is easy. (I had to re-read this quite a few times to notice this...)
|
This question already has answers here:What is a bus error? Is it different from a segmentation fault?(17 answers)Closed2 years ago.
so I was playing with pointers because I didn't know what else to do and usually, I imagine what's going on under the hood after each instruction. But I recently came against an error that I don't really understand.
```
char *str = "test";
printf("%c", ++*str);
```
Output :
```
zsh: bus error
```
Expected output was a 'u' because as far as I know, it first dereference the first address of the variable 'str' wich is a 't' than increment it right ? Or am I missing something ?
Changing the code like so is not giving me any error but why ?
```
printf("%c", *++str);
```
Thank you !
|
You cannot modify the data in a string literal. What you expect will work if you do:
```
char buf[] = "test";
char *str = buf;
putchar(++*str);
```
because the content ofbufis writeable.
|
I'm working with a C-functionfoo(FILE* file)that outputs some text to a file.
Rather than write to a .txt file, I'd likefooto write to the console.
Is there a way to pass 'the console' as a FILE*? (And if so, how) ?
(foois part of a library and I can't edit the source code directly)
|
There's a special file object calledstdoutthat will write to the console (assuming the shell didn't redirect anything).
```
foo(stdout);
```
|
There is achar *strchr( const char *str, int ch )function defined in<string.h>.
It has no boundary, after which it stops the search.
Is there a similar function somewhere, which you can pass a boundary to?
Edit:
I have achar* posand a length of asubstringand I want to find a specific ASCII character in it, but I don't want it to search up to the very null-terminator, because I don't care for the second part of the character sequence.
|
You can try:
void* memchr( const void* ptr, int ch, size_t count )
|
```
#include <stdio.h>
int main ()
{
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
```
here in the code,the fgetc(fp) use the int as this return type,so why we use "printf("%c",c);" rather than "print("%d",c);"
|
In aprintfformat string,%cmeans “convert theintargument to anunsigned charand print the character it is the code for.”
%dmeans “convert theintargument to a decimal numeral and print that numeral.”
|
The C standard says that
All accessible objects have values, and all other components of the abstract machine218)have state, as of the time the longjmp function was called, except that the values of
objects of automatic storage duration that are local to the function containing the
invocation of the corresponding setjmp macro that do not have volatile-qualified type
and have been changed between the setjmp invocation and longjmp call are
indeterminate."218) This includes, but is not limited to, the floating-point status flagsand the state of open files.
(emphasis added)
What is the goal of this requirement, and how do implementations deal with it?
|
It says "as of the time thelongjmpfunction was called", not setjmp, so the requirement is simply tonotsave/restore too much state, which is easy. (I had to re-read this quite a few times to notice this...)
|
This question already has answers here:What is a bus error? Is it different from a segmentation fault?(17 answers)Closed2 years ago.
so I was playing with pointers because I didn't know what else to do and usually, I imagine what's going on under the hood after each instruction. But I recently came against an error that I don't really understand.
```
char *str = "test";
printf("%c", ++*str);
```
Output :
```
zsh: bus error
```
Expected output was a 'u' because as far as I know, it first dereference the first address of the variable 'str' wich is a 't' than increment it right ? Or am I missing something ?
Changing the code like so is not giving me any error but why ?
```
printf("%c", *++str);
```
Thank you !
|
You cannot modify the data in a string literal. What you expect will work if you do:
```
char buf[] = "test";
char *str = buf;
putchar(++*str);
```
because the content ofbufis writeable.
|
For example,
```
float f = 2.4;
int n = f + 1;
```
n = 3
variable f is 0x4019999a in memory,
So I thought f + 1 = 0x4019999a + 1
but Computer doesn't.
How to know f is 'float'? Even if f is just 0x4019999a in memory.
Is the type of variable stored somewhere?
|
Thetypeisn't stored explicitly (in an optimized production executable; debugging outputs have all sorts of extra information in them).
"So if the type isn't stored, how does it know how to handlef = f + 1differently fromn = n + 1?" I hear you ask. :-) The answer is that the compiler knew the type when it was compiling, and it output different CPU instructions for those operations. In thefcase, it output instructions that work with floating point values, but in thencase, it output instructions that work with two's complement integers.
|
This question already has answers here:gcc undefined reference to `std::ios_base::Init::Init()' [duplicate](3 answers)Closed2 years ago.
I am new to Linux and I am trying to learn how to run and debug my programs using GCC and GDB. I set my Visual Studio Code to run and debug C/C++ programs and I wrote a simple code that implements a list. When I hit Run>Start Debugging in VSC everything works fine and the output is as expected.
However I want to compile my code using gcc and to debug it using gdb. When trying to compile using gcc I get thefollowing.
|
Useg++to compile C++ code.gccis for C code. The undefined references are the result ofgccnot linking to the C++ standard library.
|
I would like to printf doubles such that the overall length is always the same and the number is rounded if too long.
For example, with overall length 7:
```
double a = 1.23456789;
double b = 12.3456789;
double c = 123.456789;
printf("a: %f\n", a);
printf("b: %f\n", b);
printf("c: %f\n", c);
```
would print:
```
a: 1.23457
b: 12.3457
c: 123.457
```
Is there a simple way to achieve this?
|
Yes, there is. See thespecificationsforprintfconversion specifiers. Use a#to select thealternative formto keep the trailing zeros. Use thegto obtain a representation with a fixed total number of digits. The.6specifies the exact number of digits.
```
printf("a: %#.6g\n", a);
printf("b: %#.6g\n", b);
printf("c: %#.6g\n", c);
```
A precision of 6 digits happens to be the default, so this works as well
```
printf("a: %#g\n", a);
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.