i want to assign value of an integer array to integer pointer. The pointer takes a different value of assignment. Please help me on this.
I have assigned 2 for port_val variable. But, after assigning that to ofport_request var, the value becomes different.
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
int main ()
{
printf("INSIDE MAIN..\n");
int64_t of_port[100];
int count=2;
int i;
int port_val = 2;
int port_next_val = 4;
size_t n_ofport_request = 1;
int64_t *ofport_request = malloc(sizeof *ofport_request * (n_ofport_request));
for(i=0;i<count;i++) {
if(i == 0) {
of_port[i] = port_val;
} else {
of_port[i] = port_next_val;
}
ofport_request[0] = of_port[i];
printf("OFPORT VAL = %d\n",ofport_request);
}
return 0;
}
If you want to print the pointer variable, you have to use the * before the variable name.
Use the below printf statement it will work.
printf("OFPORT VAL = %lld\n",*ofport_request);
Related
I am trying to use the WaitOnAddress() function to achieve read-write synchronization.
According to MSDN, WaitOnAddress() has the following declaration:
BOOL WaitOnAddress(
volatile VOID *Address,
PVOID CompareAddress,
SIZE_T AddressSize,
DWORD dwMilliseconds
);
and the following parameter definition:
CompareAddress
A pointer to the location of the previously observed value at Address. The function returns when the value at Address differs from the value at CompareAddress.
According to the definition, I should store and pass the current value of the watched address, so when the watch value changes, WaitOnAddress() will return. But this function does not work as I expected, so I wrote the following test code for WaitOnAddress() in Visual Studio (and also included linker library Synchronization.lib):
#include <stdio.h>
#include <stdlib.h> // atoi
#include <string.h>
// include these two files after including winsock2.h
#include <process.h>
#include <Windows.h>
#include <synchapi.h>
void* threads(void* num) {
int* number = (int*)num;
for (int i = 0; i < 10; i++) {
printf("number = %d\n", *number);
}
int catch = *number; // will be passed as CompareAddress
WaitOnAddress((int*)num, &catch, sizeof(int), INFINITE);
for (int i = 0; i < 10; i++) {
printf("number2 = %d, %d\n", catch, *(int*)num);
}
return NULL;
}
int main() {
int int_list[10];
for (int i = 0; i < 10; i++) {
int_list[i] = i;
_beginthread(threads, 0, (void*)&int_list[i]);
}
printf("hello\n");
Sleep(1000);
for (int i = 0; i < 10; i++) {
int_list[i] = 10 - i;
}
printf("changed\n");
Sleep(1000);
return 0;
}
In above code, WaitOnAddress() never returns even though the value it watches changes. But, if I change
int catch = *number;
to:
int catch = 10 - *number;
then WaitOnAddress() returns and the rest of the output is printed, as if it returns ONLY when the watched value matches the compared value.
But, I want to used the described behavior so my thread is released whenever the watched variable is changed.
According to the documentation:
Parameters
Address
The address on which to wait. If the value at Address differs from the
value at CompareAddress, the function returns immediately. If the
values are the same, the function does not return until another thread
in the same process signals that the value at Address has changed by
calling WakeByAddressSingle or WakeByAddressAll or the timeout
elapses, whichever comes first.
Although you modify the value of the original array in the second loop, the catch and num are always the same when calling WaitOnAddress in the thread, so the WaitOnAddress function will not return.
You can try to modify it to:
#include <stdio.h>
#include <stdlib.h> // atoi
#include <string.h>
// include these two files after including winsock2.h
#include <process.h>
#include <Windows.h>
void* threads(void* num) {
int* number = (int*)num;
printf("number = %d\n", *number);
int catch = *number; // will be passed as CompareAddress
WaitOnAddress((int*)num, &catch, sizeof(int), INFINITE);
printf("number2 = %d, %d\n", catch, *(int*)num);
return NULL;
}
int main() {
int int_list[10];
for (int i = 0; i < 10; i++) {
int_list[i] = i;
_beginthread(threads, 0, (void*)&int_list[i]);
}
printf("hello\n");
Sleep(1000);
printf("changed\n");
for (int i = 0; i < 10; i++) {
int_list[i] = 10 - i;
WakeByAddressSingle(&int_list[i]);
}
Sleep(1000);
return 0;
}
And it works for me:
I am new to coding in the C language. I am trying to make a program that detects when the RobloxPlayerBeta.exe is being run, but upon compiling it says that "passing argument 1 of 'strcmp' makes pointer from integer without a cast".
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int logout();
char retrieve();
int main(){
char value;
while(1){
system("cmd.exe /C tasklist > Tasks.txt");
value = retrieve();
printf("%d\n",value);
int thing;
thing = strcmp(value,"1");
printf("%d",thing);
if (thing == 0){
int x = logout();
}
sleep(10);
}
return 0;
}
int logout(){
system("c:\\windows\\system32\\shutdown /l");
return 0;
}
char retrieve(){
system("cmd.exe /C start C:\\Users\\chall\\Documents\\Ccode\\Logout\\dist\\FindTask\\FindTask.exe");
FILE *f;
f = fopen("Tasks.txt","r");
int number = fgetc(f);
return number;
}
FindTask.exe is an exe made with the following python code:
with open(r"C:\Users\chall\Documents\Ccode\Logout\Tasks.txt","r") as db:
dataset = db.readlines()
for data in dataset:
if(data[:20].strip().lower() == "robloxplayerbeta.exe"):
with open("Tasks.txt","w") as f:
f.write("1")
I would like to know what a cast is and why I need one.
Cast is to tell the system convert data of one type to another type.
Example:
#include <stdio.h>
int main(void) {
int a = 10;
double b = (double)a; /* cast is used here */
printf("%f\n", b);
return 0;
}
In this case you don't need cast. strcmp() is for compareing strings. You should use operators to deal with numbers to compare single character.
Wrong:
thing = strcmp(value,"1");
Correct:
thing = value - '1';
How can I do global constant initialization like this? Is it possible at all? Or there is another way to do what I want? I mean I need global parameters gained from main() and they must be constants.
#include <stdio.h>
#include <stdlib.h>
const int var;
int main(int argc, char *argv[]) {
var = atoi(argv[1]);
/* ... */
return 0;
}
I need global parameters gained from main() and they must be constants.
No portable way to do directly as OP wants.
Code needs different access for reading and writing. Effectively hiding the access to the true data.
A close solution it to set and get data via functions defined in another file. Then no way to change data once set and only settable once.
main_var.h
int main_var_get(void);
void main_var_set(int v);
main_var.c
#include <stdlib.h>
#include "main_var.h"
static int var; // This could instead be a struct of many members.
// Or a pointer to a struct with many members.
static int var_init;
int main_var_get(void) {
if (!var_init) {
// Handle call of get before set, perhaps exit or return default value
exit(EXIT_FAILURE);
}
return var;
}
void main_var_set(int v) {
if (var_init) {
// Handle 2nd set, perhaps exit or ignore
exit(EXIT_FAILURE);
}
var = v;
var_init = 1;
}
main.c
#include <stdio.h>
#include "main_var.h"
int main(void) {
main_var_set(42);
...
printf("%d\n", main_var_get());
}
Another is to use a const int *. Access before setting is the same no-no as dereferencing NULL. Attempting to write *main_var_addr is UB like writing any const object.
main_var.h
extern const int *main_var_addr;
void main_var_set(int v);
main_var.c
#include <stdlib.h>
#include "main_var.h"
const int *main_var_addr = NULL;
static int var;
void main_var_set(int v) {
if (main_var_addr) {
// Handle 2nd set attempt, perhaps exit or ignore
exit(EXIT_FAILURE);
}
var = v;
main_var_addr = &var
}
main.c
#include <stdio.h>
#include "main_var.h"
int main(void) {
main_var_set(42);
...
printf("%d\n", *main_var_addr);
}
I don't think C allows you to initialize a constant variable elsewhere. However, you can just change var from const to static.
This is not possible, actually const doesn't mean the variable is constant in C, it's only mean that you are not allowed to change the value of the variable, but someone else could.
Global value are initialize before the main run, that mean you can't initialize at runtime, how this initialization is done is implementation behavior so there is no "pure C" way to do what you ask.
However, I don't see why you could not encapsulate your global:
my_var.h:
int init_my_var(int argc, char **argv);
int get_my_var(void);
my_var.c
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
static int var;
int init_my_var(int argc, char **argv) {
#ifndef NDEBUG
#include <stdbool.h>
#include <assert.h>
{
static bool first = true;
assert(first);
first = false;
}
#endif
if (argc < 2) {
return 1;
}
errno = 0;
long ret = strtol(argv[1], NULL, 10);
if (errno || (ret < INT_MIN || ret > INT_MAX)) {
return 2;
}
var = (int)ret;
return 0;
}
int get_my_var(void) {
return var;
}
main.c:
#include <stdio.h>
int main(void) {
printf("%d\n", get_my_var());
if (init_my_var(2, (char *[]){"", "42"})) {
return EXIT_FAILURE;
}
printf("%d\n", get_my_var());
if (init_my_var(2, (char *[]){"", "0"})) {
return EXIT_FAILURE;
}
}
I'm trying to pass a custom type object to a function by reference, and I can't figure out what I could be doing wrong. I read How do you pass a typedef struct to a function? as well as other references and could swear I'm already doing exactly that. I cleared out everything else I'm doing and even this spartan code throws 5 errors. Help me, Stackexchange; You're my only hope!
The goal is simply to be able to alter the values in the array in the object.
#include <stdio.h>
#include <math.h>
typedef struct structure {
char byte[10];
char mod;
} complex;
void simpleInit (complex *a, char value) {//put the value in the first byte and zero the rest
a.byte[0] = value;
char i;
for (i = 1; i < 10; ++i) {
a.byte[i] = 0;
}
a.mod = 1;
}
void main () {
complex myNumber;
char value = 6;
simpleInit (myNumber, value);
}
When I attempt to run this I get this error and 4 similar:
test2.c:10:3: error: request for member ‘byte’ in something not a structure or union
a.byte[0] = value;
a is a pointer type, so you need to de-reference it to use it. Typically that's done with the arrow operator:
a->byte[i] = 0;
Since this is just an array of bytes you can also quickly "zero" it:
memset(a, 0, 10);
Though given how important 10 is in your code you should codify that in a constant or a #define.
When you pass a value by reference you need to use asterisk to access al fields of the structure, for example:
(*a).byte[0] = value;
Happily you have -> as a shortcut, so this will be:
a->byte[0] = value;
Also do not forget to call the & (address of) operator when you call simpleInit.
#include <stdio.h>
#include <math.h>
typedef struct structure
{
char byte[10];
char mod;
} complex;
void simpleInit (complex *a, char value)
{
char i;
a->byte[0] = value;
for (i = 1; i < 10; ++i) {
a->byte[i] = 0;
}
a->mod = 1;
}
int main()
{
complex myNumber;
char value = 6;
simpleInit (&myNumber, value);
}
I keep geeting a segfault in the main function. I create a pointer to a struct I created and I pass it's reference to another function which allocates and reallocates memory. Then accessing it in the main function (where it was originally defined) causes a segfault.
Here is my test code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct {
char desc[20];
int nr;
} Kap;
void read(Kap *k);
int main(void) {
Kap *k = NULL;
read(k);
printf("__%s %d\n", k[4].desc, k[4].nr);
return 0;
}
void read(Kap *k) {
int size = 3;
k = (Kap*) calloc(size, sizeof(Kap));
k[0].nr = 1;
k[1].nr = 2;
k[2].nr = 3;
strcpy(k[0].desc, "hello0");
strcpy(k[1].desc, "hello1");
strcpy(k[2].desc, "hello2");
size *= 2;
k = (Kap*) realloc(k, sizeof(Kap)*size);
if(k == NULL) {
printf("ERROR\n");
exit(EXIT_FAILURE);
}
k[3].nr = 4;
k[4].nr = 5;
k[5].nr = 6;
strcpy(k[3].desc, "hello3");
strcpy(k[4].desc, "hello4");
strcpy(k[5].desc, "hello5");
}
What am I doing wrong?
Here's a simplified version of the problem you are having:
#include <stdio.h>
void func(int x)
{
x = 10;
}
int main()
{
int x = 5;
printf("x = %d\n", x);
func(x);
printf("x = %d\n", x);
}
The same reason x does not change is the reason that k does not change in your program. A simple way to fix it is this:
Kap *read()
{
Kap *k = calloc(...);
...
k = realloc(k, ...);
...
return k;
}
int main()
{
Kap *k = read();
...
}
The problem is you're not passing the pointer back to main(). Try something like this instead:
Kap * read();
int main(void) {
Kap *k = read();
printf("__%s %d\n", k[4].desc, k[4].nr);
return 0;
}
Kap * read() {
... everything else you're already doing ...
return k;
}
The code you showed passes a pointer by value into read(). The subroutine can use that pointer (though it's kind of useless since its local copy is immediately changed), however changes made within read() do not bubble back to its caller.
My suggestion is one method of allowing read() to send the new pointer back up, and it's probably the right method to choose. Another method is to change read()s signature to be void read(Kap **);, where it will receive a pointer to a pointer -- allowing it to modify the caller's pointer (due to being passed by reference).