I'm attempting to modify an array using only pointers.
void modify(){
int *ptr = &b[2];
*ptr = 90;
}
//I have my main function
void main() {
int b[15];
//fill the array with values using loop..skipping this part
modify();
}
The error that its giving me is : error: use of undeclared identifier 'b'
Can anyone give me some insight as to why the compiler does not recognize the array b?
b is declared as a local variable in main(), and thus can only be accessed by main(). To make b visible to other functions, make it a global variable by declaring it outside of any functions:
int b[3];
void modify(){
int *ptr = &b[2];
*ptr = 90;
}
int main(void) { //This is one of the standard signatures of main
//Fill the array with values using a loop
modify();
return 0; //main returns an int
}
Related
I am trying to understand the passing pointer as an argument and pointer return type function. Similar concept works with string but not with integers. Could someone please find issue in the below code and correct it. The error message is
cannot convert 'int**' to 'int*
'
Many thanks in advance.
#include <stdio.h>
int *findMax(int *num1, int *num2)
{
if (*num1 > *num2)
{
return (num1);
}
else
{
return (num2);
}
}
int main(void)
{
int *_num1;
*_num1 = 10;
int *_num2;
*_num2 = 12;
int *bigger;
bigger = findMax(&_num1, &_num2);
return 0;
}
You create two int pointers - but they do not actually point at any ints so when you dereference them to assign values you get undefined behavior.
int main(void)
{
int _num1 = 10; // note: not a pointer
int _num2 = 12; // note: not a pointer
int *bigger;
bigger = findMax(&_num1, &_num2); // here you take the addresses of the int:s
printf("%d\n", *bigger);
}
cannot convert 'int**' to 'int*
That error saved you from a lot of pain. Since you declared the two variables as int*, taking the address of such a variable produces an int** which is not what your function accepts.
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int *arr;
}example;
void Create(example var){
var.arr = (int *)malloc(sizeof(int)*2);
}
int main(){
example var1, var2;
var1.arr = (int *)malloc(sizeof(int)*2);
var1.arr[0] = 11;
var1.arr[1] = 22;
printf("%d %d\n",var1.arr[0],var1.arr[1]);
Create(var2);
var2.arr[0] = 111;
var2.arr[1] = 222;
printf("%d %d\n",var2.arr[0],var2.arr[1]);
return 0;
}
OUT:
11 22
Segmentation Fault
My code is as above. I don't get any error when I do it manually as in var1. But if I do it inside a function as in var2, I get an error. How can I fix this. I want to do it inside the function.
EDIT:Thank you for your answers. It worked
The problem is that Create() is making a COPY of your struct. The original struct is unchanged.
If your program was C++, you'd want to pass a "reference".
Here, you want to pass a pointer:
void Create(example * mystruct){
mystruct->arr = (int *)malloc(sizeof(int)*2);
}
int main(){
example var1, var2;
...
Create(&var2);
you have to pass reference of var2:
Create(&var2);
The function parameter
void Create(example var){
var.arr = (int *)malloc(sizeof(int)*2);
}
is its local variable that is initialized by the passed argument and is not alive after exiting the function.
That is this call
Create(var2);
did not change the variable var2 declared in main.
As a result in these statements
var2.arr[0] = 111;
var2.arr[1] = 222;
there is used uninitialized pointer arr that has an indeterminate value that invokes undefined behavior.
You need to pass the variable by reference to the function. For example
void Create(example *var){
var->arr = (int *)malloc(sizeof(int)*2);
}
and the function is called like
Create( &var2 );
i am trying to call a function in main so that my code will execute through all parts of my code. Now when i call for compare_quads in main. i am getting an error code of a and b not being declared. but my problem is that i do not know how to get the variable declared because i have declared the function and variable at the top of the code i thought that would work. and if i try declaring the variable in main like
const void *a;
const void *b;
then when compiling i receive, warning a is used uninitialized in this function, and similarly with b.
here is my code,
//declare libraries
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
//declare other functions/files to be used in the program
void print_fun(void);
void read_fun(void);
static int compare(int arg, unsigned char networks[arg][4]);
int compare_quads(const void *a, const void *b);
//read command line input and store the information
int main(int argc, char** argv){
//declar variable
int arg = 0;
//make argv into an int
arg = atoi(argv[1]);
//assign size to networks
unsigned char networks[arg][4];
//assign input to networks
for (int j =0; j<1; ++j){
if(argc == 1)
{
printf("ERROR ERROR, you messed up\n");
}
else
{
// hold network addresses in a 2-d array, with 4 unsigned char
for(int k = 0; k<arg; k++){
for (int i =0; i<4; i++){
scanf("%hhu.", &networks[k][i]);
//checks to see if scanf was working properly
// printf(" %hhu",networks[k][i]);
}
//printf("\n");
}}}
compare_quads(a, b);
compare(arg, networks);
return(0);
}
int compare_quads( const void *a, const void *b) {
return memcmp (a, b, 4);
}
static int compare(int arg, unsigned char networks[arg][4])
{
qsort(networks, arg, sizeof(networks[0]), compare_quads);
for (int k = 0; k< arg; k++){
printf("%d.%d.%d.%d\n", networks[k][0],networks[k][1],networks[k][2],networks[k][3]);
}
return 0;
}
I am pretty new to c, so please let me know if you need any clarification. thank you.
the exact warnings are
unitilazed
main.c: In function ‘main’:
main.c:47:19: error: ‘a’ undeclared (first use in this function)
47 | compare_quads(a, b);
| ^
main.c:47:19: note: each undeclared identifier is reported only once for each function it appears in
main.c:47:22: error: ‘b’ undeclared (first use in this function)
47 | compare_quads(a, b);
| ^
when const void *a; is used to initalize.
main.c: In function ‘main’:
main.c:48:5: warning: ‘a’ is used uninitialized in this function [-Wuninitialized]
48 | compare_quads(a, b);
| ^~~~~~~~~~~~~~~~~~~
main.c:48:5: warning: ‘b’ is used uninitialized in this function [-Wuninitialized]
EDIT
I am taking in one input file that has, a various amount of lines with network address like
139.72.16.202
i am storing the values in an array of size [variable that is set by arg][4]
then after the main function the rest i am using to sort the code by column. the sorting function worked fine.
A pointer to the compare_quads function is getting passed to the qsort function as a comparison function, so it will get called internally by qsort.
Because of this, you don't need to call compare_quads in your main function. Passing it to qsort is enough.
I want to create an array of structs based on one struct definition, and initialize each one with a different int value.
Then, I want to print this value, using a function pointer that points to a print function.
Define a struct (includes an int and a function pointer).
create an array of 10 structs of the same definition.
set different values for each one of them.
send this value for a function that is pointed to by a function
pointer that is also located in the struct
This is my code:
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 10
void Print(int num);
typedef struct print_me
{
int x;
void (*Print)(int x);
};
struct print_me my_prints[ARRAY_SIZE];
int main()
{
size_t i = 0;
for (i = 0; i < ARRAY_SIZE; ++i)
{
my_prints[i].x = i;
my_prints[i].Print(my_prints[i].x);
}
return 0;
}
void Print(int num)
{
printf("%d\n",num);
}
I'm still learning the ideas of function pointer and structs , so I'll be glad to get some tips and suggestions that will help me to understand my mistakes here.
Thanks.
For starters there is no any sense to use the typedef specifier in this declaration
typedef struct print_me
{
int x;
void (*Print)(int x);
};
without specifying a typedef name. You could write for example
typedef struct print_me
{
int x;
void (*Print)(int x);
} print_me;
In the for loop you need to initialize the data member Print with the address of the function Print. For example
for (i = 0; i < ARRAY_SIZE; ++i)
{
my_prints[i].x = i;
my_prints[i].Print = Print;
}
then in a second for loop you could call the function like
for (i = 0; i < ARRAY_SIZE; ++i)
{
my_prints[i].Print( my_prints[i].x );
}
As with usual pointers, you have to set a pointer value before you can use it. So that it points somewhere.
Add:
my_prints[i].Print = &Print;
// or, it means the same, & is optional
// my_prints[i].Print = Print;
my_prints[i].Print(my_prints[i].x); // now ok
before calling my_prints[i].Print() so that the pointer will point to function Print before calling it.
Side note with a fun fact: because of the strange C rules, dereferencing the function pointer is not needed, and you can even like "dereference" the function pointer multiple times, like (****my_prints[i].Print)(). See ex this question.
my question is how does the function malloc_queue() can access variables from init_queue() without giving any arguments!
For example:
The main.c:
if (init_queue()) {
malloc_queue()
}
init_queue() creates the variable que:
int init_queue{
struct Queue *que;
return 1;
}
malloc_queue() want to do something with the variable que from init_queue():
void malloc_queue{
struct Queue *que = (struct Queue*)malloc(sizeof(struct Queue));
return;
}
but that doesnt work since malloc_queue doesnt know what que is. Are there any possible ways without giving any arguments?
Maybe you want a static variable outside functions, which has scope inside the residing file after its definition.
Check this code:
#include <stdio.h>
static int x = 0;
void a() {
x = 5;
}
void b() {
x*=2;
}
int main(int argc, char * argv[]) {
printf("%d\n", x);
a();
printf("%d\n", x);
b();
printf("%d\n", x);
return 0;
}
Just as the comments suggested, read about c scopes.
If you need to declare struct other than primary types, you might need to declare a pointer to structure as the static variable outside function, then allocate memory (e.g malloc()) inside one of your functions.