question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
This question should've had an answer nowadays here, but there is nothing explaining what exactlyTCHARis on stackoverflow (all I found is an explanation of the difference betweenTCHARand_TCHAR).
All I know is thatTCHARand_TCHARare considered to be the same and on some platformsTCHARmay be the same asWCHAR. But all that is just a presumption.
What isTCHARand how does it differ fromWCHAR?
|
TCHARis eithercharorwchar_tdepending on whetherUNICODEis defined or not.
UsingTCHARandTCHAR-based types allow a library to work with programs that defineUNICODEand programs that don't alike.
|
I am using Qt 5 to send data via serial port. The problem comes from a conversion bewteen float and unsigned char [4] with union structure.
```
typedef union {
float df;
unsigned char uc4[4];
}fuc4;
fuc4 t1, t2;
t1 = (a+b)/c, t2 = -(a-b)/c;
```
Both is 0 as we can have a look at t1.df and t2.df with qDebug().
However, the last byte of them is quite different where t2.dc[3] is 0x80=128d.
On the other side, I have to use the bytes without any conversion. For example, I need t2.dc[2]*256+t2.dc[3] to get an integer number but it is clearly a mistake if I do so. How can I correct this or do it in a safe way.
|
I've always done this one:
```
float f = something;
unsigned char *uc4 = (unsigned char*)&f;
```
You don't need to go through an union for char or unsigned char, though you do for any other types.
|
This question should've had an answer nowadays here, but there is nothing explaining what exactlyTCHARis on stackoverflow (all I found is an explanation of the difference betweenTCHARand_TCHAR).
All I know is thatTCHARand_TCHARare considered to be the same and on some platformsTCHARmay be the same asWCHAR. But all that is just a presumption.
What isTCHARand how does it differ fromWCHAR?
|
TCHARis eithercharorwchar_tdepending on whetherUNICODEis defined or not.
UsingTCHARandTCHAR-based types allow a library to work with programs that defineUNICODEand programs that don't alike.
|
I'm trying to write a simple shell. I just want to change the color of the text the user types in which in the future will be used for stuff like syntax highlighting. Can I use the standard library for this or do I need to use something like ncurses. Its pretty easy to change the output color. Is there a similar solution?
Thanks in advance.
|
Have a look athereandhere.
I think this Sample Code should help you,
```
#include<stdio.h>
int main()
{
int num;
printf("%s", "\033[92mEnter Number : \033[34m");
scanf("%d", &num);
printf("%s", "\033[0m");
return 0;
}
```
Above coe will printEnter number :in green and typing number in blue,
Note : Make sure that your terminal supports ANSI escape color codesee herefor windows 10.
|
I am trying to use CAN J1939 standard on an embedded Linux system running Ubuntu 18.04, kernel 5.4.0-52-generic.
This elinux pageindicates that j1939.h "got in the mainline kernel since v5.4". Andkernel.org's documentation for j1939implies that it is in the main kernel.
Lastly, I do have can-utils installed.
When I compile a cpp file with#include <linux/can/j1939.h>, I get ano such file or directoryerror.
I've gone throughlinux/candirectory to confirm andj1939.his not there. Is there any reason why my v5.4 kernel wouldn't havej1939.h? How can I best usej1939.hin my program?
|
You need development packages for these headers. You can search for which package you need on the Ubuntu Packages site. I.e. in this casepackages containing j1939.h. You're probably looking forlinux-libc-devorlinux-headers-5.4.0-26.
|
So I'm trying to get the sum of the values in a buffer, however, the values need to be rearranged in order to do so. Essentially how do I get C to convert the values in this array:uint16_t inp[] = {0xFF,0x81,0xFD,0x00,0x00,0x00,0x00,0x08,0x00,0x00};to look like this array:uint16_t buff[] = {0x81FF,0x00FD,0x0000,0x0800,0x0000}
|
Thanks to @kaylum, I figured it out:
```
#include <stdio.h>
#include <stdint.h>
uint16_t inp[] = {0xFF,0x81,0xFD,0x00,0x00,0x00,0x00,0x08,0x00,0x00};
uint16_t buff[sizeof(inp)/2];
int main(){
int sum = 0;
for(int i = 0; i < sizeof(buff);i=i+2){
buff[i] = ((inp[i+1] | 0x00) << 8) | (inp[i] | 0x00);
//printf("%.4X\n",buff[i]);
}
for(int i = 0; i < sizeof(buff);i++){
sum = sum += buff[i];
}
printf("%u\n",sum);
return 0;
}
```
|
I am writing a kernel system call and I want to read the base pointer register (RBP) of the user. Maybe I can do that using thept_regsstruct that is passed for parameter, isn't it?
Example code:
```
unsigned long int data;
asmlinkage int my_read(int d)
{
get_rbp_of_userStack(&data);#or somthing like that
}
```
I know this data saved somewhere for the context switch, how can I get to it?
this is my user code
```
void rar()
{//rbp here should be rsp when it call so it basically the return addres of the main
char t[10];
getchar();
}
int main()
{
rar();
}
```
|
You can use thetask_pt_regs()macro to get thecurrenttask's user registers (saved at the moment of syscall entry):
```
#include <asm/processor.h>
SYSCALL_DEFINE1(foo, int, d)
{
const struct pt_regs *user_regs = task_pt_regs(current);
unsigned long rbp = user_regs->bp;
/* Do whatever you need... */
return 0;
}
```
|
As far as I know, ~0x00 equals to:
First step, change 0's to 1 and 1's to zero, Second step, add 1
Step 1: 11111111111111111111111111111 (count =32)
Step 2: 11111111111111111111111111111+1=0
Where am I doing wrong?
|
The~operator does not perform 2's complement negation. You can do that with the unary-operator (assuming your machine uses 2's complement representation).
What~does is invert all bits. That's all it does, no adding 1.
|
I have two files,main.candother.h. I declare a few global variables inmain.c, and most of them are fine. I can sayextern whateverinother.hand access those variables. However, I defined a struct like this (inmain.c):
```
struct LSA {
int myID;
int seqNum;
int neighborID[256];
int costs[256];
} local_LSA[256];
```
And when I try to access it inother.hlike this
```
extern struct LSA local_LSA[256];
```
I get this error message
```
other.h:27:19: error: array type has incomplete element type ‘struct LSA’
extern struct LSA local_LSA[256];
```
I've been playing around with for a while, but... I appreciate any help anyone is able to provide!
|
The structure type needs to be defined before any instances of it can be created.
You need to move the struct definition into other.h beforelocal_LSAis defined.
|
I am trying to compile zvfs.cherebut it gives me error when linking, that the following functions are unresolved external symbols
```
error LNK2001: unresolved external symbol _zp_init_keys
.........................................._zp_update_keys
.........................................._zp_decrypt_byte
.........................................._getPwdKey
.........................................._crc_32_tab
```
I am compiling it in windows Visual Studio. does anyone know please which library contains these functions. I can't find it anywhere.
|
Those symbols are only asked for ifZIPVFSCRYPTis defined — it requires manual source changes to make that happen — and that should only be defined if you supply a cryptography module. I believe that's a commercial product only; we don't have the source to that.
|
I want to create a Makefile, which compiles each .c file in the the directory to a .o file with the same name.
But for some reason, it does not work. I am not sure if I "call" the generic target properly. Can you help me?
```
CC = clang
CFLAGS = -std=c11 -pedantic -Wall -Wextra
.PHONY: clean all
all: *.o
clean:
rm -f *.o
%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $<
```
Greetings
|
As others commented, this line:
```
all: *.o
```
expands the right side just to theexistingfiles.
You can use these functions to "collect" all C sources, and exchange the extension:
```
all: $(patsubst %.c, %.o, $(wildcard *.c))
```
However, not every make will support these functions.
(Note: Why can't you explicitly list the object files you want generated?)
|
I have an algorithm which works perfectly withintbut my input needs to be an unsigned char:
```
unsigned char a;
printf("a:");
scanf("%c",&a);
```
and because of this the algorithm doesn't take the Input 4 as 4 but instead 52 (ASCII).
So my question: is there a way I can use the input 4 as a 4 in my calculations without changing the%cin the input code?
|
Since C99, use —length modifier"hh".
```
scanf("%hhu",&a);
```
Pre C-99, read via anunsigned
```
unsigned u;
scanf("%u",&u);
a = u;
```
|
As far as I know, ~0x00 equals to:
First step, change 0's to 1 and 1's to zero, Second step, add 1
Step 1: 11111111111111111111111111111 (count =32)
Step 2: 11111111111111111111111111111+1=0
Where am I doing wrong?
|
The~operator does not perform 2's complement negation. You can do that with the unary-operator (assuming your machine uses 2's complement representation).
What~does is invert all bits. That's all it does, no adding 1.
|
I have two files,main.candother.h. I declare a few global variables inmain.c, and most of them are fine. I can sayextern whateverinother.hand access those variables. However, I defined a struct like this (inmain.c):
```
struct LSA {
int myID;
int seqNum;
int neighborID[256];
int costs[256];
} local_LSA[256];
```
And when I try to access it inother.hlike this
```
extern struct LSA local_LSA[256];
```
I get this error message
```
other.h:27:19: error: array type has incomplete element type ‘struct LSA’
extern struct LSA local_LSA[256];
```
I've been playing around with for a while, but... I appreciate any help anyone is able to provide!
|
The structure type needs to be defined before any instances of it can be created.
You need to move the struct definition into other.h beforelocal_LSAis defined.
|
i will ask user for number of matrixes then randomize a 5x5 matrix for each one. Can i do this in a single struct. If so then how should i allocate memory for it, i try to do it this way but it didn't work.
```
struct Temp
{
int *mat[5][5];
}test;
int main(void)
{
int x;
printf("Enter the number of matrixes : ");
scanf("%d", &x);
test.mat= malloc( x* sizeof *test.mat);
if (test.mat== NULL) {
fprintf(stderr, "Malloc failed.\n");
exit(1);
}
```
|
```
int *mat[5][5];
```
is a 5x5 array ofint*.
To create a pointer to 5x5 array ofint, it should be
```
int (*mat)[5][5];
```
|
```
char str[] = "C:\\Users\\test\\Desktop\\folder\\test.txt";
char *ptr;
ptr = strchr(str, '\\');
if (ptr != NULL) {
*ptr = '\0';
}
```
How do I remove the last ' \ ' including test.txt so it is just "C:\Users\test\Desktop\folder"
Thanks
|
You wantstrrchr
Locate last occurrence of character in string
Returns a pointer to the last occurrence of character in the C
string str.The terminating null-character is considered part of the C string.
Therefore, it can also be located to retrieve a pointer to the end of
a string.
Also you need to escape the backslashes with\\:
```
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[] = "C:\\Users\\test\\Desktop\\folder\\test.txt";
char *ptr;
ptr = strrchr(str, '\\');
if (ptr != NULL) {
*ptr = '\0';
}
puts(str);
}
```
|
I have a task is to print the ASCII code number and the input:
Below is my code:
```
#include <stdio.h>
int main(void){
char ch;
printf("Whatever: ");
while((ch = getchar()) != 'q')
{
getchar();
printf("The char is %c and %d in ASCII.\n", ch, ch);
}
return 0;
}
```
What should I revise if I want to print the \n from the getchar() function?
```
Example:
The char is \n and 10 in ASCII.
```
|
Hope below helps
```
while((ch = getchar()) != 'q')
{
if(ch == '\n')
printf("The '\\n' ascii value is %d\n", ch);
else
printf("The '%c' ascii value is %d\n", ch, ch);
}
```
|
OK so i'm trying to build this project:https://github.com/flysands/injectorusing NDK, but i get this error:
No, its not my NDK, i've tried to build other projects and it worked before.
```
Android NDK: Trying to define local module 'payload' in jni/payload/Android.mk.
Android NDK: But this module was already defined by jni/payload/Android.mk.
```
Any help is appriciated!
| ERROR: type should be string, got "\nhttps://github.com/flysands/injector/blob/master/jni/Android.mkis wrong.subdirsis never initialized.ndk-buildevaluates eachAndroid.mkonce per ABI, so when it evaluates the file for the second ABI it adds the subdirectories tosubdirsa second time and causes the duplicate inclusion.\n\n```\nsubdirs := $(LOCAL_PATH)/payload/Android.mk $(LOCAL_PATH)/inject/Android.mk\n```\n" |
I want to write an wrapper around robocops that allows the program to be paused at any time? If I call the program over system(), how can I terminate and pause it?
|
You have some options:
You can use the "system" function call to use command prompt to call the function to pause, but the use may just click "enter" and it will keep moving -> system("pause");You may use threads in order to to stop your program from moving on but it is harder and you have to learn how to use them.
|
I have a queue that stores thread structures
```
struct x
{
int n;
char *c;
void *f;
};
```
The function below returns a structure defined as the following:
```
struct s {
void *data;
};
```
When I call*new = allocate(&x_ptr), how can I access the members ofx?
I tried the following but it does not work:
printf("%d\n", new ->data->n)
I get this error: request for member ‘n’ in something not a structure or union
|
datahas type ofvoid *, you need to cast it to the correct pointer type (assuming it is referencing a valid object of that type).
```
printf("%d\n", node->data->threadid);
```
---->
```
printf("%d\n", ((threaddesc *)(node->data))->threadid);
```
|
I want to add the value of a parameter to another parameter within a designated initializer, without having to define a separate variable to hold that value. Is this possible?
```
typedef struct {
int x;
int y;
} point;
int main() {
point p = {
.x = 1,
.y = x + 2 // I want to reference .x
};
}
```
|
This is not possible. The evaluation order of expressions in an initializer are not evaluated in any particular order, so there's no guarantee that.xwill be set to 1 before.yis set to.x + 2.
This is spelled out in section 6.7.9p23 of theC standard:
The evaluations of the initialization list expressions are
indeterminately sequenced with respect to one another andthus the order in which any side effects occur is
unspecified.152)
Where footnote 152 states:
In particular, the evaluation order need not be the same as the order
of subobject initialization.
|
I'm trying to read text from a file and store it into a string so that I can then encrypt and decrypt it using openssl. How can I do this?
|
You could use dynamic memory. My "skeleton" code for reading any type of file is this:
```
// Assumes: the file @ file name is a text file; ASCII or UTF-8 (no BOM)
void readwholefile(char *filename)
{
FILE *fp;
char *buffer = NULL;
size_t i, len;
fp = fopen(filename, "rb");
fseek(fp, 0, SEEK_END);
len = ftell(fp);
rewind(fp);
buffer = malloc(len + 1);
if (NULL == buffer)
{
// Handle malloc failure & exit
exit(-1);
}
fread(buffer, 1, len, fp);
fclose(fp);
buffer[len] = '\0';
// buffer now contains the content of your file; do what you want with it
free(buffer);
buffer = NULL;
}
```
|
This question already has an answer here:A couple of questions about [base + index*scale + disp] and AT&T disp(base, index, scale)(1 answer)Closedlast year.
I am doing a lab for my cs class and we are reverse engineering a "binary bomb". I am confused on a few assembler instructions. If anyone could explain what these do and how the work I would greatly appreciate it.
```
lea 0x10(%rbx), %rbp.
```
Im pretty sure rbx is supposed to hold the address of rbp, but im confused on the 0x10 argument.
```
mov 0x4(%rbx), %eax.
```
Same thing as above, don't understand what the 0x4 argument is.
|
These are offsets (0x10 = 16bytes and 0x4=4bytes) to the pointers in rbp and eax.
Most likely iterating over elements in an array/vector.
|
So I'm going through a piece of code in one of the programs and it uses an unlink function , where
```
hist_name = malloc(128)
```
However, I did notice that the program did not use a "free" to free the memory , but it did have the unlink function shown below, at the end of the program:
```
unlink(hist_name);
```
My question is , does the unlink function free memory in addition to deleting the link to the file, or do I still need to insert afree(hist_name)statement to free the memory?
|
unlinkdoes not free memory. If you want the memory pointed to byhist_namereleased, you should pass the address tofree.
|
I guess dynamically created variable has to be initialized separately and not at the time of allocating. Why the below line of code does not compile?
Why do I get the error message " expected ')' before 'p'".
*(int *p = malloc(sizeof(int))) = 23;
|
|
The definitionint *pcannot appear inside an expression, it is a syntax error. You must use a definition and a separate expression to initialize the contents:
```
int *p = malloc(sizeof(int));
*p = 23;
```
or
```
int *p;
*(p = malloc(sizeof(int))) = 23;
```
Note that both of the above forms have undefined behavior in case of memory allocation failure.
|
I guess dynamically created variable has to be initialized separately and not at the time of allocating. Why the below line of code does not compile?
Why do I get the error message " expected ')' before 'p'".
*(int *p = malloc(sizeof(int))) = 23;
|
|
The definitionint *pcannot appear inside an expression, it is a syntax error. You must use a definition and a separate expression to initialize the contents:
```
int *p = malloc(sizeof(int));
*p = 23;
```
or
```
int *p;
*(p = malloc(sizeof(int))) = 23;
```
Note that both of the above forms have undefined behavior in case of memory allocation failure.
|
How can i create text file with the cat command using the execl system call in c
i tried using
```
execl("/bin/cat", "cat", ">", "test.txt", NULL);
```
but it is giving me input output error
|
The problem is that redirection with>is handled by the shell that invokescat, not bycatitself. The simplest solution is to invokeshinstead, and let it invokecatand handle the redirection:
```
execl("/bin/sh", "sh", "-c", "/bin/cat > test.txt", (char *) NULL);
```
The alternative would be to open the file yourself (withopen), close standard output, duplicate the file descriptor onto fd 1 (by callingdup2), and finally close the first file descriptor. Then you could callexecl, lettingcatwrite to standard output. That's basically what the shell does, but it's much easier to letshdo it for you.
|
Trying to understand how to perform an arithmetic operation from arguments passed from terminal and use them in execve ?
```
./myProgram 'echo "$1+$2=$(($1+$2))"' 3 5
```
this is suppose to give me an output of 8
what i've tried manually without argv :
```
pid_t pid;
char *parmList[] = {"sh", "-c", "echo $0 $1 + $2 1 2", NULL};
char *envParms[3] = {"1=1", "2=2", NULL};
if ((pid = fork()) == -1)
perror("fork error");
else if (pid == 0)
{
execve("/bin/sh", parmList, envParms);
printf("Return not expected. Must be an execve error.n");
}
```
i get the $0 which is sh ✅
but $1 and $2 are not recognized ...what i am missing ?
|
You don't want to be passing 1 and 2 in the environment. The shell wants them as positional parameters. So you could do:
```
char *parmList[] = {"sh", "-c", "echo $0 $1 + $2 1 2", "sh", "1", "2", NULL};
```
|
So I want to do this:
```
struct element{
int t;
};
int main(int argc, char *argv[]) {
struct element arr[10];
arr[0]={3};
return 0;
}
```
But this gives me the following error:
```
test.c: In function ‘main’:
test.c:7:10: error: expected expression before ‘{’ token
7 | arr[0]={3};
| ^
```
To fix this, I will have to resort to writing:
```
int main(int argc, char *argv[]) {
struct element arr[10];
struct element tmp = {3};
arr[0]= tmp;
return 0;
}
```
But I think it is inelegant to write a tmp value when I just want to assign directly toelement{3}. How do I fix the syntax so that I do not need to create thistmpvalue?
|
What you want is acompound literal:
```
arr[0]=(struct element){3};
```
|
Which C compilers do support#pragma STDC FENV_ACCESS ON(or its equivalent)?
cl (19.25.28611): does support via#pragma fenv_access (on)
gcc (10.2.0): no support:warning: ignoring '#pragma STDC FENV_ACCESS'(https://gcc.gnu.org/bugzilla/show_bug.cgi?id=34678)
clang (11.0.0): no support:warning: pragma STDC FENV_ACCESS ON is not supported(it seems to be a patch:https://reviews.llvm.org/D69272)
icc: ??
Preferred target architecture: x86_64.
|
For C11:
clang 12.0.0+icc 16.0.3+
|
This is the exact error
```
incompatible integer to pointer conversion assigning to 'char *' from 'char'
```
This is my code in which I am trying to make str equal to hexarr2 but am unsure how to do so.
```
void int_to_hex(unsigned int x, char *str)
{
char hexarr2[9] = {'0','0','0','0','0','0','0','0',' '};
for (j = 0 ;j<9;j++){
str = hexarr2[j];
str++;
}
}
```
|
If you're trying to copy the characters fromhexarr2tostrthe easiest thing to do is:
```
void int_to_hex(unsigned int x, char *str)
{
char hexarr2[9] = {'0','0','0','0','0','0','0','0',' '};
for (j = 0 ; j < sizeof(hexarr2) ; j++)
str[j] = hexarr2[j];
str[sizeof(hexarr2)] = '\0';
}
```
This assumes that the buffer pointed to bystris large enough to accomodate all the characters inhexarr2.
|
I'm learning to build complex types. Here I defined a pointer to an array 5 of shorst usingtypedef:
```
typedef short (*mytype)[5];
```
I'm trying to find out how to to the same with the#definedirective and if it is even feasible. I tried this, but it does not work:
```
#define MYTYPE (short*)[5]
```
It seems like this directive cannot be applied for defining something more complex than a pointer or a struct. So, what is the point here?
|
How to define a [variable of a pointer to array type] with the #define directive?
You may just use a function macro.
```
#define MYTYPE(name) short (*name)[5]
int main() {
short arr[5];
MYTYPE(a) = &arr;
typedef MYTYPE(mytype);
}
```
what is the point here?
There's is no point - preprocessor is a string replacement tool that is generally not aware of C syntax. Use atypedefto define an alias for a type.
|
```
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,q;
printf("Enter elements of array\n");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
printf("enter number to search: ");
scanf("%d",&q);
for(i=0;i<10;i++)
{
if(q==a[i])
{
printf("Given number is at %dth place", i);
getch();
exit();
}
}
printf("Given number is not found");
getch();
}
```
Here I'm facing error " [Warning] incompatible implicit declaration of built-in function 'exit' " and " [Error] too few arguments to function 'exit' "
|
exit()takes one argumentstatusto determint the exit code of the program, so you have to provide that (one integer).
Also you should add#include <stdlib.h>to useexit()function because the header includes required declaration of the function.
|
I have learned from an online class that, bothchar **argvandchar *argv[ ]can be used as an argument tomain.
I also understand that they are effectively the same, they both declare argv as a "pointer (*) to a char pointer (char *)".
What makeschar argv[ ][ ]invalid as an argument tomain?
edit: Actually, ischar *argv[ ]declaring an array instead of a pointer? So argv only decays to a pointer but is not one itself?
|
This declaration of a parameter
```
char argv[ ][ ]
```
is invalid because the compiler needs to know the element type of the array that in this case is incomplete typechar[].
This declaration
```
char *argv[ ]
```
declares an incomplete array type with the element typechar *.
If such a declaration is used as a function parameter declaration then it is implicitly adjusted by the compiler to pointer to the element type that is to the declaration
```
char **argv
```
|
When I declarechar ch = 'ab',chcontains only 'b', why it is not storing 'a'?
```
#include <stdio.h>
int main()
{
char ch = 'ab';
printf("%c",ch);
return 0;
}
```
What is the actual process involved here?
|
When using the single quote marks'to contain theabstring, you have created what is known as a multi-character constant. The behaviour of your program is implementation-defined, meaning that if I have a different compiler or OS, I might see the valuea, even though you see the valueb.
This is not a good practice and the compiler should issue a warning.
If you do not see the warning, try compiling with warnings enabled by using the flags-Walland-Wextraif usinggccorclang.
You can read more about thishere in another answer.
|
I have learned from an online class that, bothchar **argvandchar *argv[ ]can be used as an argument tomain.
I also understand that they are effectively the same, they both declare argv as a "pointer (*) to a char pointer (char *)".
What makeschar argv[ ][ ]invalid as an argument tomain?
edit: Actually, ischar *argv[ ]declaring an array instead of a pointer? So argv only decays to a pointer but is not one itself?
|
This declaration of a parameter
```
char argv[ ][ ]
```
is invalid because the compiler needs to know the element type of the array that in this case is incomplete typechar[].
This declaration
```
char *argv[ ]
```
declares an incomplete array type with the element typechar *.
If such a declaration is used as a function parameter declaration then it is implicitly adjusted by the compiler to pointer to the element type that is to the declaration
```
char **argv
```
|
When I declarechar ch = 'ab',chcontains only 'b', why it is not storing 'a'?
```
#include <stdio.h>
int main()
{
char ch = 'ab';
printf("%c",ch);
return 0;
}
```
What is the actual process involved here?
|
When using the single quote marks'to contain theabstring, you have created what is known as a multi-character constant. The behaviour of your program is implementation-defined, meaning that if I have a different compiler or OS, I might see the valuea, even though you see the valueb.
This is not a good practice and the compiler should issue a warning.
If you do not see the warning, try compiling with warnings enabled by using the flags-Walland-Wextraif usinggccorclang.
You can read more about thishere in another answer.
|
I need to print the address of a pointer.
This is my code:
```
float arr[5] = {1.2 , 2.3 , 5 , 7.1 , 9.6};
float *ptrarr;
ptrarr = &arr[0];
printf("Address of ptrarr+2=%p,%p \n\n",ptrarr+2,&arr[2]);
```
I knew that pointer addresses have 8 bytes, but my output is always 16 bytes.
This is the output
```
Address od ptarr+2=000000000061FDE8,000000000061FDE8
```
Can someone please explain?
|
On a platform where the number of bits per byte is 8:
1 hexadecimal character represents 4 bits, i.e., "half a byte".
Hence 16 hexadecimal characters represent 8 bytes (not 16 bytes).
Note that generally, the number of bits per byte is define byCHAR_BIT.
So on the theoretical aspect, a byte can consist of something other than 8 bits.
|
When I use the following code I tried to replicate the idea thatsqrt(x)of something equalsX^(1/2)
```
pow(x, (1/2);
```
It returned 1 no matter what value I entered. I already solved this issue with the sqrt function but wanted to know why this is happening for the future.
|
In it's original form,1/2is integer division, producing a result of0.
Math 101: Anything raised 0, is 1.
|
is this loop statement is correct?
if not correct then what alternative way?
I am trying to o(n) loop statement like this-
```
for(int i=0 ; i<n ; i++ , j=n ; j<n*2 ; j++){
continue;
}
```
|
The construct is wrong, you cannot you two loops in one construct, but you can have more than one variable controlling the iteration.
For example, you can have
Two (or more) variables,iandj, initialized with certain values.A loop controlling statement, involving operation and condition check oniandj(and others, if defined).Finally, you can control the increment or decrement ofiandj(and others, if defined).
A sample construct can be:
```
for (int i = 0, j = n; i < n && j < n * 2; ++i, ++j)
|^^^^^^^| -------- variable modification
| | |^^^^^^^^^^^^^^^^^| ---------------- loop condition
|^^^^^^^^^^^^^^^|--------------------------------------- initialization
```
|
I want to verify whether entered number has 5 digit or not so I use while loop for this.
```
while(n>=10)
{
n = n/10;
count++;
}
if(count != 5)
return 0;
```
But next parts of my code are using updated n value and I don't want that.How can I say "use first n value" to my code?Here is all my code(It works smoothly when I delete configuration part):
```
#include <stdio.h>
int main(void)
{
int digit=0,n,count=0;
scanf("%d",&n);
while(n>=10)
{
n = n/10;
count++;
}
if(count != 5)
return 0;
for(int i=0; i<5; i++)
{
digit += n%10;
n /= 10;
}
printf("%d",digit);
}
```
|
Use different temporary variable for error checking.
This way your original variable will be intact.
```
int temp = n;
while(temp>=10)
{
temp = temp/10;
count++;
}
```
|
I'm using perror:
```
perror("Error message:");
```
When the above is used it displays the message passed to the string followed by the actual error that occurred. This is a standard function, however I want to log this to a file, how to I get the actual error that goes with this so I can log it?
|
You can use the code below:
```
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main() {
FILE* filePtr;
filePtr = fopen (logFilePath, "a");
//...
//some code
//...
if(critical_part){
fprintf(filePtr, "errno :%s Error in critical part - line 123\n",strerror(errno));
}
}
```
|
I'm using perror:
```
perror("Error message:");
```
When the above is used it displays the message passed to the string followed by the actual error that occurred. This is a standard function, however I want to log this to a file, how to I get the actual error that goes with this so I can log it?
|
You can use the code below:
```
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main() {
FILE* filePtr;
filePtr = fopen (logFilePath, "a");
//...
//some code
//...
if(critical_part){
fprintf(filePtr, "errno :%s Error in critical part - line 123\n",strerror(errno));
}
}
```
|
I keep getting an invalid initializer error in this line:
```
StackObject_t new = (StackObject_t*)malloc(sizeof(StackObject_t));
```
The StackObject_t type is defined as such:
```
typedef struct stackObject* pStackObject_t;
typedef struct stackObject
{
void* obj;
pStackObject_t next;
} StackObject_t;
```
and this is the exact error I get:
|
First of all,you should not cast the result of mallocas it can hide errors and C automatically castsvoid*to the correct pointer type. Secondly, your issue is because you haveStackObject_tas the type of the variable but malloc returns aStackObject_t*. You can fix this by changing your line toStackObject_t* new = ...so the types match up.
|
Say for instance I declare a char array with all values set to zero in the following fashion:
```
char array[4] = {0};
```
If I assign it values, for instance:
```
array[0] = 'A';
array[1] = 'B';
array[2] = 'C';
```
Do I need to null terminate the array like so?:
```
array[3] = '\0';
```
or does the operationchar array[4] = {0}null terminate previous to any assignment?
|
Do I need to null terminate the array like so?
No.'\0'is just a fancy way of writing0. It's a way to write self-documenting code referring to the null terminator specifically, out of tradition. (It's actually just a zero written as an octal escape sequence, of all things.)
Since you already set all items to0, there is no need for an extra\0.
|
In this code, I want to remove the newline. It means whenever I print this variable, it should give me a string without a newline but instead, the comma should replace it. I can directly add a comma when declaring but I want a separate result.
Expecting output
```
This,is,a,simple,sentence
```
Code
```
#include <stdio.h>
#include <string.h>
int main(){
char str[] = "This\nis\na\nsimple\nsentence";
printf("%s\n", str);
}
```
|
A simple for loop will do it:
```
for (int i = 0; i < sizeof(str); i++)
if (str[i] == '\n')
str[i] = ',';
```
This modifies the original string, rather than creating a new one.
|
In this code, I want to remove the newline. It means whenever I print this variable, it should give me a string without a newline but instead, the comma should replace it. I can directly add a comma when declaring but I want a separate result.
Expecting output
```
This,is,a,simple,sentence
```
Code
```
#include <stdio.h>
#include <string.h>
int main(){
char str[] = "This\nis\na\nsimple\nsentence";
printf("%s\n", str);
}
```
|
A simple for loop will do it:
```
for (int i = 0; i < sizeof(str); i++)
if (str[i] == '\n')
str[i] = ',';
```
This modifies the original string, rather than creating a new one.
|
I'm new to C, sorry if my question sounds dumb.
We know thatsem_postfunction unlock a semaphore, but why it is called in this way, isn't it more suitable to be calledsem_unlock, I don't think "post" has a meaning of "unlock"?
|
I've always thought of it as the word "post", as in "post a message", since you're effectively sending a signal to some process waiting to run, or possibly about to want to run.
Wikipedia attempts to explain the originalV(post) andP(wait) operation names; apparently, they're one-letter abbreviations for Dutch words but we're not really sure which words.Read it here, although it probably doesn't help much with the choice of English words.
|
I'm new to C, sorry if my question sounds dumb.
We know thatsem_postfunction unlock a semaphore, but why it is called in this way, isn't it more suitable to be calledsem_unlock, I don't think "post" has a meaning of "unlock"?
|
I've always thought of it as the word "post", as in "post a message", since you're effectively sending a signal to some process waiting to run, or possibly about to want to run.
Wikipedia attempts to explain the originalV(post) andP(wait) operation names; apparently, they're one-letter abbreviations for Dutch words but we're not really sure which words.Read it here, although it probably doesn't help much with the choice of English words.
|
I'm following a book on c programming and encountered this example:
```
a<=20?b=30:c=30;
```
I just have to use the number 30 one time. The solution in the book was
```
((a<=20)?&b:&c)=30);
```
When I try to run this I get the following error:
lvalue required as left operand of assignment.
It seems like one of the parenthesis is missing there, but I don't know where.
Can you please tell me how I can fix this?
|
supposingaandbare numbers of the same type, just do
```
*((a <= 20) ? &b : &c) = 30;
```
gettingaandbaddress it is needed to dereference (the '*') to have alvalue
from @Vrintle remark note you can also do in C++
```
((a<=20)?b:c)=30;
```
the compiler knows the form is alvalueso the value ofbandcare not used but their reference
It seems like one of the parenthesis is missing there, but I don't know where.
in((a<=20)?&b:&c)=30);the last ')' does not have corresponding '('
|
```
int n;
printf("How many?");
scanf("%d", &n);
int array[n];
```
These are the errors I get..error C2057: expected constant expressionerror C2466: cannot allocate an array of constant size 0
error C2133: 'array': unknown size
Any help would be appreciated.
|
Some compilers don't support variable-length array and unfortunately your compiler seems one of them.
You can usemalloc()fromstdlib.hto allocate arrays dynamically.
```
int n;
printf("How many?");
scanf("%d", &n);
int* array = malloc(sizeof(*array) * n);
```
|
In C, not C++, I tried to set a char array size using a strlen() contained in a const int.
```
char *input = "hello";
//now the integer that contains the lenght
static const int lengthA = strlen(input); //upto here, it works
char list_array[lengthA]; //here doesn't work, because the variable lengthA is not initialized
```
So, I want that the length ofinputis used as the length of thearray.
I already tried withsizeof, instead ofstrlen, but it returns the byte
Is this possible?
|
The feature you're using is called avariable length array, where the size of an array is determined at runtime. However, Visual Studio does not support this feature.
You'll need to allocate memory dynamically withmalloc:
```
char *input = "hello";
static const int lengthA = strlen(input);
char *list_array = malloc(lengthA);
```
|
I come across this from time to time in my operating systems class but the professor didn't explain it and I can't exactly find an explanation online. What exactly is the use of the offset inmmap? Also this is for linux
Thanks
|
It lets you map a section of a file that doesn't necessarily start at the beginning.
So
```
fd = open("/path/to/myfile", O_RDONLY);
ptr = mmap(NULL, 8192, PROT_READ, MAP_PRIVATE, fd, 4096);
```
would map bytes 4096-12287 of the file into memory, and return a pointer to the address where they are mapped.
This is useful, for instance, if you are loading a shared library. Some parts of the file may be headers or debug info that you don't need to map into memory.
|
```
int n;
printf("How many?");
scanf("%d", &n);
int array[n];
```
These are the errors I get..error C2057: expected constant expressionerror C2466: cannot allocate an array of constant size 0
error C2133: 'array': unknown size
Any help would be appreciated.
|
Some compilers don't support variable-length array and unfortunately your compiler seems one of them.
You can usemalloc()fromstdlib.hto allocate arrays dynamically.
```
int n;
printf("How many?");
scanf("%d", &n);
int* array = malloc(sizeof(*array) * n);
```
|
In C, not C++, I tried to set a char array size using a strlen() contained in a const int.
```
char *input = "hello";
//now the integer that contains the lenght
static const int lengthA = strlen(input); //upto here, it works
char list_array[lengthA]; //here doesn't work, because the variable lengthA is not initialized
```
So, I want that the length ofinputis used as the length of thearray.
I already tried withsizeof, instead ofstrlen, but it returns the byte
Is this possible?
|
The feature you're using is called avariable length array, where the size of an array is determined at runtime. However, Visual Studio does not support this feature.
You'll need to allocate memory dynamically withmalloc:
```
char *input = "hello";
static const int lengthA = strlen(input);
char *list_array = malloc(lengthA);
```
|
I come across this from time to time in my operating systems class but the professor didn't explain it and I can't exactly find an explanation online. What exactly is the use of the offset inmmap? Also this is for linux
Thanks
|
It lets you map a section of a file that doesn't necessarily start at the beginning.
So
```
fd = open("/path/to/myfile", O_RDONLY);
ptr = mmap(NULL, 8192, PROT_READ, MAP_PRIVATE, fd, 4096);
```
would map bytes 4096-12287 of the file into memory, and return a pointer to the address where they are mapped.
This is useful, for instance, if you are loading a shared library. Some parts of the file may be headers or debug info that you don't need to map into memory.
|
Suppose we declare an array of pointers to chars i.e.char *a[3];I know that char ** is a pointer to a pointer to a char, so it is legal to do something like:char ** c = arr;
We can also declare something likechar **b[3];, but I am confused about what this represents. I thought it would be a pointer to the pointer which points to the first element in b, but that would be the same thing as above. How do I initialize values in the array b and what are those values?
|
b is an array of char** that could store 3 elements of type char**. You could initialize as follows:
```
char **a1, **a2, **a3;
char **b[3] = {a1, a2, a3};
```
and when accessing b[0] it would give you a1, b[1] would give you a2 and b[2] would give a3.
|
Is it safe to useshm_unlinkeven there are other process currently open the shared memory?
For exmaple:
Process Bshm_openand then Process Ashm_unlink. Is it ok for Process B?
|
Yes, it is safe to call shm_unlink if another process has it opened. Per the man page for shm_unlink:
The operation of shm_unlink() is analogous to unlink(2): it removes a
shared memory object name, and, once all processes have unmapped the
object, de-allocates and destroys the contents of the associated
memory region. After a successful shm_unlink(), attempts to shm_open()
an object with the same name will fail (unless O_CREAT was specified,
in which case a new, distinct object is created).
|
Why does this work:
```
char Word[]="monkey";
for (int Index = 0; Word[Index] != '\0'; Index++)
{
printf("%c", Word[Index]);
}
```
while this does not?
```
char Word[]="monkey";
for (int Index = 0; Word[Index] < '\0'; Index++)
{
printf("%c", Word[Index]);
}
```
To be honest, I do not see any difference.
|
Whilecharis a signed type, ASCII characters arenon-negativeand go from 0 to 127. Therefore, in the second example, your condition will never evaluate to true since all characters in the string are ASCII characters.
If you really want to use something other than!=, your only option is>:
```
char Word[] = "monkey";
for (int Index = 0; Word[Index] > '\0'; Index++)
{
printf("%c", Word[Index]);
}
```
NOTE: while this works, it might be confusing and error prone, you should always prefer!= '\0'.
|
```
#include<stdio.h>
int main() {
int i = 3771717;
printf ("%c", i);
return 0;
}
```
The output isE. Isn't 69 the ASCII forE?
|
The%cformat specifier expects anintargument which is then converted to andunsigned charas printed as a character.
Theintvalue 3771717 gets converted to theunsigned charvalue 69 as per the conversion rules from a signed integer to unsigned integer. The C standard specifies this is done by repeatedly subtracting one more than the maximum value forunsigned charuntil it is in range. In practice, that means truncating the value to the low order byte. 3771717 decimal is 398D45 hex so that leaves us with 45 hex which is 69 decimal.
Then the character code for 69 i.e.'E'is printed.
|
Purpose of code is to create a 'n by n' block of "#"
How does indenting the 2nd 'for loop' create the rows and column necessary?
I noticed that 'print ("\n");' also will lead to the desired outcome to create a 'n by n' block of "#". How?
```
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int n;
do
{
n = get_int("Size: ");
}
while (n < 1);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
printf("#");
}
printf("\n");
}
}
```
|
Indenting code is just to make it more readable. you could put al this on one line and it would still run, but please don't.
'\n' is just to go to the next line.
I'm not sure if this answers you're questions, because you're kind of unclear.
|
I have a C project which i open in VisualStudio 2019 with the "Open folder" option. I added a CppProperties.json to get Intellisense running, but now it throws errors if i try to declare a variable in a for loop like this:
```
for (int i = 0; i < 10; i++)
{
}
error: E0029 expected an expression
error: E0020 identifier "i" is undefined
```
I searched StackOverflow already and foundthis threadwhere someone mentions that the declaration of variables in for loops was added in the C99 standard.
In the VisualStudio documentation it says you should add "-std=C99" to your project settings, but i have no project file (because I opened it with the "Open Folder" option) and therefore no project settings.
Is there a way to tell Intellisense what C standard to use anyways ?
Thanks in advance.
|
Found it: Just add
```
"compilerSwitches": "-std=c99",
```
to your CppProperties.json.
|
This question already has answers here:How the assignment statement in an if statement serves as a condition?(4 answers)Closed2 years ago.
I am aware that when a non zero value is provided as a condition in an if statement, the condition is evaluated to be true.
Yet, I'm wondering how anassignment(=)is evaluated to be true here, instead of a comparison(==), and runs without any errors in the below C program.
```
int main(){
int a, b =5;
if(a=10) {
("This works");
}
if(b=1){
("This works too");
} }
```
|
The assignment operator always returns the value that was assigned. So in your casea=10has the value10and the if statement is essentiallyif(10). Which is true.
|
Sometimes I come across functions that I want to call in my debugging that take a pointer as an argument and change the contents that are pointed to.
Example:
```
int doFoo(int a, double* b)
```
I would like to call this function from gdb, but don't have adouble*lying around. Is it possible to do this with convenience variables? Simply calling
```
set $foo = 1.0
call doFoo(0, &($foo))
```
does not work.
|
This appears to work:
```
set var $foo = &{1.0}
call doFoo(0, $foo)
p *$foo
```
Using{}makes GDB allocate a single item double array within the process's memory.
Note that without&in the assignment, evaluating$foowill return a new address every time.
|
Keep in mind that when usingfprintf()I'm aware that I need to pass the file descriptor for writing to the pipe. I just have the doubt and wish to know right now; I don't really have any kind of sample code.
In addition, I want to know if functions such as fputc(), fputs() will also work.
|
Usingfprintf()requires a file stream (FILE *). When you create a pipe, you get two file descriptors. File descriptors are not the same as streams.
You can use the POSIXfdopen()function to create a file stream from a file descriptor; you can then usefprintf()on that file stream — or any of the other standard I/O functions that take an explicit file stream argument and write to the stream. You can't usefseek(); you'll get an error (ESPIPE— illegal seek).
You can (in theory) use the POSIXdprintf()function to write directly to a file descriptor — if your system supports it.
|
Im trying to create an array of strings based on a variable like the following.
```
char* stringArray[3];
for(int i = 0; i < 3; i++) {
sprintf(stringArray[i], "string%d", i);
}
```
which would create the following array ["string0", "string1", "string2"].
However, it seems this isn't valid and gives me a memory error. What is the right way to accomplish this in C?
|
You have created the pointers but no storage for the content.
Either char
```
stringArray[3][100]; // 99 chars +1 null
```
or
```
for(int i = 0; i < 3; i++) {
stringArray[i]=malloc(100); // create memory
sprintf(stringArray[i], "string%d", i);
}
```
|
I thought whitespace effectively did not matter in C. Is this different for the preprocessor? Why do we need to use " \ " when creating multiline macros?
|
Preprocessor directives are terminated by a newline character, so in that context newlines are distinguished from other whitespace.
Newlines are also distinguished inside//comments and string literals. In both cases, line-splicing can be used to extend the lexeme, although it's not considered good style.
Equally, you can extend preprocessor lines using multiline comments, because comments are replaced with a space before preprocessing directives are recognised. That probably would also be discouraged by style guides if they thought of it.
|
In the C language, with this code snippet:
```
uint16_t a = 243;
uint16_t b = 65535;
uint16_t max = 65535;
if ((a + b) > max)
{
printf("Out of range!");
}
else
{
printf("Within range.");
}
```
The result will be "Out of range!". What type conversion rules apply in this case? Can someone point me to a documented source?
Thanks!
|
Ifintis wider than 17 bits,a,b, andmaxwill be converted toint.a + bwill not overflow and will yield a result greater thanmax.
Ifintis 17 bits wide,a,b, andmaxwill be converted toint.a + bwill overflow, and the behavior is not defined by the C standard.
Ifintis 16 bits wide,a,b, andmaxwill not be converted.a + bwill wrap and will yield a result less thanmax.
|
How does thestrideparameter of theglVertexAttribPointerfunction work?
Lets say I have a buffer which is 64 bytes large. I want to store 2 vertices which are 32 bytes large each. If the vertices start one after another, does the stride parameter need to be 0 or 32? What I'm trying to say is does the stride parameter count from the start of the last vertex or from the end of the last vertex?
|
It counts from the start of the previous vertex.
Butstride == 0is a special case, it means that your attributes are tightly packed. So e.g. if you're passing advec4(vector of 4 doubles) per vertex, it doesn't matter if you use0or32(ifsizeof(double) * 4 == 32).
|
I have a function using a pointer to a pointer to a structure:
```
int function(struct_A ** mystructA);
```
It worked when i used it with my declared struct:
```
struct_A *mystructA;
function(&mystructA);
```
however, impossible to use my structure throught another structure:
```
struct struct_B{
struct_A *mystructA;
}
struct_B mystructB;
function( (&mystructB)->mystructA ); //this line cause me a segfault
```
I am struggling here, any idea where it could come from?
|
```
struct struct_B{
struct_A *mystructA;
}
struct struct_B mystructB;
struct struct_B *mystructBptr;
/* .... */
function( &mystructB.mystructA );
function( &(&mystructB) -> mystructA );
function( &mystructBptr -> mystructA );
```
|
I am trying to find the number of digits in a given number through the use of pointers.
This code below will give the correct output,
```
void numDigits(int num, int *result) {
*result = 0;
do {
*result += 1;
num = num / 10;
} while (num > 0);
}
```
However, if I change the*result += 1;line to*result++;, the output will no longer be correct and only give 0.
What is going on here?
|
In C/C++, precedence of Prefix++(or Prefix--) has higher priority than dereference (*) operator, and precedence of Postfix++(or Postfix--) is higher than both Prefix++and*.
Ifpis a pointer then*p++is equivalent to*(p++)and++*pis equivalent to++(*p)(both Prefix++and*are right associative).
|
Within C how can I name a function? Just the name.
typedef strlen StringLengthfails to compile with:strlen does not name a type.
|
A function pointer is a solution
static Integer(*StringLength)(const Byte*) = strlen;
|
I have the following function and I am wondering if there is a way to passstringorchararray instead ofstdoutinto it so I can get the printed representation as a string.
```
void print_Type(Type t, FILE *f)
{
fprintf(f,"stuff ...");
}
print_Type(t, stdout);
```
I have already tried this:
```
int SIZE = 100;
char buffer[SIZE];
print_Type(t, buffer);
```
But this is what I am seeing:
```
�����
```
|
Something like this
```
FILE* f = fmemopen(buffer, sizeof(buffer), "w");
print_Type(t, f);
fclose(f);
```
Thefmemopen(void *buf, size_t size, const char *mode)function opens a stream. The stream allows I/O to be performed on the string or memory buffer pointed to bybuf.
|
#define EISDIR 21 /* Is a directory */
"Is a directory" isn't very helpful when the place I get this error is fromopen(destination, O_WRONLY);
Of course it's a directory that's why im trying to open it...
|
You cannot open directories for write mode (O_WRONLY), only read (O_RDONLY) or search (O_SEARCH). All modifications to directories take place through high level functions that either use a pathname or a file descriptor to the directory, but don't need it to be opened for write.
Here,EISDIRmeans "the operation you're trying to perform requires a non-directory, but you tried to perform it on a directory".
|
So this is the char buffer I have:
```
Manual: h:0147(0051.6) v:0842(0296.0) H:0114(0040.0) V:0697(0245.0)
```
Please note that this buffer isnot certain to be null terminated.
What I want to do is to get the last two numbers from the parentheses().
I was gonna use asscanf()like this:
```
sscanf(buffer, "H:%4d(%f) V:%4d(%f)", &num1, &num2, &num3, &num4);
```
But I believe that it is not possible, because it is not null terminated?
How could I possibly get these two float numbers out of it to use later?
One way would be, since the buffer is still the same size and format, only the numbers change, to just use index to get it, but I think there must be a better way.
|
Thanks @Barmar and @RemyLebeau for the help.
The solution to the problem is the following
```
sscanf(buffer, "%*[^H]H:%4d(%f) V:%4d(%f)", &num1, &num2, &num3, &num4);
```
Works like charm
|
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.Closed2 years ago.Improve this question
In C language, how to use printf to output such a format, for example,
unsigned long intunsigned long long intunsigned intlong long intlong int
How to calculate the bytes occupied by them?
I mainly want to know the output format of unsigned long int, but it seems that there is no introduction in the document, only some very similar. For example, unsigned long or unsigned long long.
This format is the type of uint64_t
|
sizeofgives you the size of any variable you wish.
For the list of every output format of printf, check themanual.
|
This question already has an answer here:Linking glade file with program g++(1 answer)Closed2 years ago.
I am programming something using C and Gtk+ library via Glade
I'm Compiling with a "makefile" methode and everything it is ok
but when I change the application.exe folder (like sending it to my friend) the application doesn't work
my question is there any way to compile it without needing to the glade file in the same folder?
|
Yes, check outGResource, which lets you embed files such as a Glade file into your executable.
|
This question already has an answer here:Linking glade file with program g++(1 answer)Closed2 years ago.
I am programming something using C and Gtk+ library via Glade
I'm Compiling with a "makefile" methode and everything it is ok
but when I change the application.exe folder (like sending it to my friend) the application doesn't work
my question is there any way to compile it without needing to the glade file in the same folder?
|
Yes, check outGResource, which lets you embed files such as a Glade file into your executable.
|
I understand that, given the code never enters the loop, would give me the error.
However, given thatris equal to1, it should return it,i.e., it would always enter it.
```
int arroz() {
int r = 1;
while (r) {
return r;
}
}
```
So, why does this code give me the warning control reaches end of non-void function?
|
The compiler correctly assumes thatris a variable value, it does not process it as a constant, that being the case it cannot be sure what the value is going to be and therefore if the body of the cycle will or will not be executed.
If you use a constant the warning goes away because the compiler will assemble the code using a constant value.
You can check this behaviorhere.
|
How to implement the following formula in any programming language:
1/sin(1) + 1/(sin(1)+sin(2)) + ... + 1/(sin(1) + sin(2) + ... +
sin(N))
That's the best I did.
```
#include <stdio.h>
#include <math.h>
int main()
{
float a, c, s;
printf("N = ");
scanf("%f", &n);
s = 1 / sin(1);
for (a = 2; a <= n; a++)
{
c = s + (1/(sin(a-1)+sin(a)))
}
printf("%f", s);
}
```
|
In C#:
```
public double getFormula(int n)
{
double sum = 0;
for (int i = 1; i <= n; i++)
{
double denom = 0;
for (int j = 1; j <= i; j++)
{
denom += Math.Sin(j);
}
sum += 1 / denom;
}
return sum;
}
```
|
Currently i am dynamically allocating memory for a structure, after which i am dynamically allocating memory for one of its members. My question is should i free the member too, or only the structure and why?
```
#include <stdlib.h>
struct test{
char *test_member;
};
int main(){
struct test *new_test;
// Allocating memory for structure and its member
new_test = (test*)malloc(sizeof(test));
new_test->test_member = (char*)malloc(80);
// Freeing struct member and struct
free(new_test->test_member);
free(new_test);
return 0;
}
```
|
Since variables in the structure are allocated, you need to free them first, and free the structure.
It is same as dynamic allocate of 2D array A. when you wanna free 'A' you need to free A[i] first and then free A to prevent memory leak..
So your code is correct
|
I'm currently new to C so how things work is still slightly alien to me as I come from an OOP background of Java. I'm trying to get an input from the terminal and then turn it into all lowercase letters however it seems the function isn't working. Any tips if possible?
```
#include <stdio.h>
int lower(int c){
if (c >= 'A' && c <= 'Z')
return c + 'a' - 'A';
else
return c;
}
int main(){
int c;
while ((c = getchar()) != EOF){
lower(c);
putchar(c);
}
}
```
|
The code should use the return values oflower:
```
putchar(lower(c));
```
You may also like to use the standard library functiontolower.
|
```
typedef struct ELEMENT
{
int addr;
int size;
struct ELEMENT * next;
} ELEMENT;
int freeMemory (ELEMENT ** freeList, ELEMENT ** allocList, int addr)
/* pre: Parameter addr must match the start of an allocated memory block.Otherwhise return -1.
* post: If addr is a part of allocated memory of allocList then the memory from this address
* with registered nrofBytes should be removed from the *allocList and added to the *freeList
*
* freeMemory(freeList,allocList,addr) returns number of bytes belonging to the address addr
* In all other cases freeMemory(freeList,allocList,addr) returns -1.
*/
```
I am assuming that I have to check something like if(node -> addr == addr), but I am not sure if that is what they are reffering to. (It is an assignment)
|
Yes, you have to check thataddrparameter must mactch one of theaddrvalue in theallocListelements.
|
So let's say I have code similar to something like this.
```
#define DATA 0x67
char *mydata = malloc(1);
mydata = DATA
```
Line 3 is invalid, of course, but what I am looking of is to take 0x67 and read it into that memory location. It must be obvious, but I don't know what that would be called to ask the question properly.
|
Dereference the pointer is equivalent to access the first indice of an array (in this case an array of char) which is maybe more easily understandable :
```
#define DATA 0x67
char *mydata = malloc(1);
mydata[0] = DATA
```
If you would have allocated more memory you could access all bytes of this memory this way.
|
Can I use pointers to static functions like pointers to non-static functions?
Lets say I have:
```
void (*fp_some_event_handler)(void);
void KeyEventHandler(void){
// not static
}
static void KeyEventHandlerStatic(void){
// static
}
```
Can I use static function pointer just like non-static?
```
void main() {
// now I have something like this
fp_some_event_handler = KeyEventHandler;
// and I want to change some function to static and end with this
fp_some_event_handler = KeyEventHandlerStatic;
}
```
|
Whether a function isstaticis not part of its type but is instead astorage class specifier.
So you can assign either of the two functions in your sample code to the function pointerfp_some_event_handler.
|
Why am I getting an error when using theatoi()function?
```
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10], s2[10];
int x=5, y=6, z;
sprintf(s1, "%d", x);
sprintf(s2, "%d", y);
strcat(s1, s2);
z = atoi(s1);
printf("%d, %s", z, s1);
return 0;
}
```
|
```
#include <stdlib.h>
```
Will fix it.
|
I'm currently new to C so how things work is still slightly alien to me as I come from an OOP background of Java. I'm trying to get an input from the terminal and then turn it into all lowercase letters however it seems the function isn't working. Any tips if possible?
```
#include <stdio.h>
int lower(int c){
if (c >= 'A' && c <= 'Z')
return c + 'a' - 'A';
else
return c;
}
int main(){
int c;
while ((c = getchar()) != EOF){
lower(c);
putchar(c);
}
}
```
|
The code should use the return values oflower:
```
putchar(lower(c));
```
You may also like to use the standard library functiontolower.
|
```
typedef struct ELEMENT
{
int addr;
int size;
struct ELEMENT * next;
} ELEMENT;
int freeMemory (ELEMENT ** freeList, ELEMENT ** allocList, int addr)
/* pre: Parameter addr must match the start of an allocated memory block.Otherwhise return -1.
* post: If addr is a part of allocated memory of allocList then the memory from this address
* with registered nrofBytes should be removed from the *allocList and added to the *freeList
*
* freeMemory(freeList,allocList,addr) returns number of bytes belonging to the address addr
* In all other cases freeMemory(freeList,allocList,addr) returns -1.
*/
```
I am assuming that I have to check something like if(node -> addr == addr), but I am not sure if that is what they are reffering to. (It is an assignment)
|
Yes, you have to check thataddrparameter must mactch one of theaddrvalue in theallocListelements.
|
You can see that in my code I just writeintk and and its printingk=-4. why not -3 becausekis an integer so it will store -3 from -3.53.
```
{
int a,b,c,k;
int *x, *y, *z;
a=10, b=15, c=-5;
x = &a;
y = &b;
z= &c;
*z= *z +1;
*x = *x + (-2);
k = ((*z)++) - ((*x) / (*y));
printf("%d %d %d %d",*x, c, *z, k);
}
```
|
Insert a print just before the interresting line - like:
```
printf("%d %d %d\n", *z, *x, *y);
k = ((*z)++) - ((*x) / (*y));
```
Output:
```
-4 8 15
```
Since*xis less than*ythe integer division((*x) / (*y))will give zero. So the calculation is just:
```
k = ((*z)++)
```
Here the++is apostincrement of*z. That is: the value of*zis returned andafterwards*zwill be incremented. Thereforekwill get the value-4and*zwill become-3
|
I am not able to predict the answer of this problem and not able get a solution logically? though it may be a bit simple but as a beginner, I am not able to get it?
```
int main()
{
int array[5][5];
printf("%d",( (array == *array) && (*array == array[0]) ));
return 0;
}
```
|
Basically its a simple addressing question.
Is the address ofarraythe same as the address of*array? (Yes, though they differ in type - different arrays)Is Is the address of*arraythe same as the address ofarray[0]? (Yes, they are the same - the 1st int array insidearray)Now1 && 1evaluates to 1 (Boolean condition evaluates to 1 or 0)
PS. As @Lundin says, this question is not valid C
|
I have a file test.txt
```
$cat text.txt
0xee8745a2
0xfec6a2ea
0x0ae45a4b
```
Which is created using echo in linux
Ex:
```
echo 0xee8745a2 > text.txt
echo 0xfec6a2ea >> text.txt
```
When i usefgets(),I am getting length of the buffer 11.
What "echo" is appending to each line when writing to file.
|
echooutputs its argument followed by a newline character (\naka LF aka 0x10). So that's the extra character you're seeing. To suppress this, useecho -n 0xfec6a2ea > test.txt, but then of course all the text will be on the same line.
|
Is there a way to include the memory address whenever printing something in gdb. For example:
```
>>> p __libc_argc
$4 = 1
```
Instead, I'd like to have:
```
>>> p __libc_argc
$4 = 0x7fffffffec63 1
```
|
To print the memory address of a variable just add&before its name. If you often want to print both the variable address and its value it might be worth creating a command for that. For instance, add the code below to your.gdbinitfile
```
define pwa
print &$arg0
print $arg0
end
```
With this, you will have apwacommand (short for "print with address") that you can use instead of the standardprintcommand whenever you want both the address and the value to be printed.
|
Is there a way to include the memory address whenever printing something in gdb. For example:
```
>>> p __libc_argc
$4 = 1
```
Instead, I'd like to have:
```
>>> p __libc_argc
$4 = 0x7fffffffec63 1
```
|
To print the memory address of a variable just add&before its name. If you often want to print both the variable address and its value it might be worth creating a command for that. For instance, add the code below to your.gdbinitfile
```
define pwa
print &$arg0
print $arg0
end
```
With this, you will have apwacommand (short for "print with address") that you can use instead of the standardprintcommand whenever you want both the address and the value to be printed.
|
Do we need tomemsetglobal C style strings or is it initiated to'\0'on its own?
for example:
```
char c_string[10];
```
OR
```
struct node
{
int x;
char y[10];
};
```
|
Global variables having arithmetic types (includingchar) are initialized to zero, so you don't usememset()for the first initialization.
Quote fromN15706.7.9 Initialization 10:
If an object that has static or thread storage duration is not initializedexplicitly, then:— if it has pointer type, it is initialized to a null pointer;— if it has arithmetic type, it is initialized to (positive or unsigned) zero;— if it is an aggregate, every member is initialized (recursively) according to these rules,and any padding is initialized to zero bits;— if it is a union, the first named member is initialized (recursively) according to theserules, and any padding is initialized to zero bits;
|
Here's my code:
```
#include <openssl/bio.h>
int main (void)
{
BIO* bo = BIO_new(BIO_s_mem());
}
```
I'm compiling my code by doinggcc -lcrypto test.c.
Any idea what's wrong?
|
You have the arguments in the wrong order, trygcc test.c -lcrypto
Seewhy order matters
|
How to read mmap function from specific address, if knew it (0x6A6F7444)?
I tried:
```
mmap(0x6A6F7444, 100, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0)
```
But it doen't works. Compile says:
```
warning: passing argument 1 of ‘munmap’ makes pointer from integer without a cast [-Wint-conversion]
```
|
```
#include <stdint.h> // for uintptr_t
uintptr_t addr = 0x6A6F7444;
mmap((void *)addr, 100, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
```
will disable the warning.
|
I'm writing a program that takes 2 command line arguments which are each pointers to strings. I call them str and except. If there's a lower case letter in str then it's an error and the program ends. If a char is in str but not in except then it prints. I'm getting this error message when I run my code: “./a.out” terminated by signal SIGSEGV (Address boundary error)
|
SIGSEGV will be shown when you don't put argv[2] or argv[1].
Please test
./a thistest et
And, your code means if there are lower case letters, it will pass.(your task is to except if there are lower case letters)
please repair :if((str[i] < 'A')||(str[i] > 'Z')){
|
```
int (*a)[10] = NULL; // initilaized to NULL pointer
printf("a :: %p\n", a); // print nil
printf("*a :: %p\n", *a); // seg fault??
return 0;
```
I executed this code on my x86 code using gcc, and it compiles without any error.I expected something like
a :: (nil)Segmentation Fault
but it actually prints out
a :: (nil)*a :: (nil)
Why here referencing null pointer does not cause seg fault?
|
The reason in general is that dereferencing a pointer to array does not read any memory, the result is an array havingsame address- the result is just a different type.
The behaviour is undefined nevertheless.
Note that you used%pbut you could have used%sfor the second one (withchar (*a)[10] = NULL;) which would have even more undefined behaviour, and yet still GCC/Glibcprintfwouldoftenprint(nil)instead of crashing.
|
I was writing an algorithm in C/++ and when I was debugging using a print statement (very professional, I know), I saw an odd value:-0. Does this mean the same thing as a regular 0 or could this cause bugs? If so, how can I fix those bugs?
|
In both languages-0is the unary negation of theintconstant / literal0.
If yourintis 2's complement (most likely in C, and must be from C++20), then it's exactly the same as0, and no sane formatter would ever print-0for0.
If yourintis 1's complement or signed magnitude then-0is asigned negative zero. It will compare numerically equal to 0 but its bit patternwillbe different.
You can convert a signed negative zero to a zero by adding zero!
Most likely, your print statement is outputting a slightly negative floating point value, which your formatting is rounding towards zero and therefore you have nothing really to worry about.
|
Please help me understand this:
I have a pointer to a pointerchar** word_array = NULL;Then I dynamically allocate memory in my code:n = 6;
word_array = (char *) malloc(n* sizeof(char*));How do I delete all the memory allocated for the "array" of pointers? Is this call tofreeright?free(word_array);Or should I make a loop:for(int i = 0 ; i < n; i++) free(word_array + i);
|
You used onemalloc, so you should use onefree.
Also the cast tochar*is nonsense:word_arrayhas typechar**, notchar*, and casting result ofmalloc()isdiscouraged.
So the entire flow will be like this:
```
int n;
char** word_array = NULL;
n = 6;
word_array = malloc(n* sizeof(char*));
if (word_array == NULL) {
/* handle allocation error */
} else {
/* do some work with word_array */
/* free pointers stored in word_array if they are dynamically allocated
and not freed yet */
free(word_array);
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.