Casting Void Pointers in C Programming [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am reading a book called head first c and they told me a concept about casting pointers. I understand why I would do it but what I want to know is how to do it? Like what is the syntax?
int compare_names(const void* a, const void* b)
{
const char** sa = (const char**)a;
const char** sb = (const char**)b;
//why would, in the return section, we use normal pointers instead of **?
return strcmp(*sa, *sb);
}
I get that on the left side we are using 2 asterisks because sa/sb are pointers to pointers but on the right side, I have absolutely no idea what is going on. Are we making an assignment from pointer to a pointer?
Also please explain everything about the return line.
**One final question I have is when I write the a statement like (char*)a or (int*)a am I making "a" into an integer or a char?**

Well the simple thing is here you would be good to go even if you didn't use casting in these 2 statements
char** sa = (char**)a;
char** sb = (char**)b;
Because conversion from void* to char** is implicit. This would also be fine (provided you assign it to correctly qualified variable name).
const char** sa = a;
The thing is, here we need to do this (assignment) so that the address contained in a and b are considered as char** and dereferenced value of them are used in strcmp. You can also do this alternatively
return strcmp(*((const char**)sa), *((const char**)sb));
without using any extra variables.
Again more importantly, one thing to note is that - here you are violating the constraint that is there due to use of the const in the parameters. You would be good to go
const char** sa = (const char**)a;
const char** sb = (const char**)b;
The return line is basically returning the result of the comparison of two strings - which may result in -1,1 or 0 based on the compared values. This can be used as a comparator function to the standard library sorting qsort.

Related

Looking for answers to an old test that I took, trying to learn what I should have done.(Malloc Function Maybe?) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Old Test
I'm going over a test I took and am trying to figure out what the answer was to these questions. I was wondering if anyone could help me? As you can probably see I did not really understand how to answer them at the time but I would like to learn. I believed the answer has something to do with Malloc, but was unsure exactly how.
Thank you!
Edit : Is this how you do it?
#include <stdio.h>
#include <stdlib.h>
float* func();
int main(void)
{
float *x;
x = func();
printf("%f\n", *x);
return 0;
}
float* func(void){
float * z;
z = malloc(sizeof(float));
* z = 11.2;
return z;
}
malloc is related to allocating memory.
When we talk about array and pointer in c, we can seperate it into static array and dynamic array. For static array, we use array, for example,
char arr[10];
which means declare char type array named arr with length of 10.
For Dynamic array, we use pointer, for example, char *arr. This means char type pointer of arr. Pointer is very flexible; therefore, you must command to use it properly.
Assume
char *arr = (char *) malloc (sizeof (char) * 10);
This means you have a pointer and will allocate the memory with the size of char type with length of 10 you can also re allocate memory with realloc with different length. At the end of using it you must
free(arr);
To add, this is benefit of C language and I believe it is harder to use than other languages but more flexibility. On the other hand, you must be very very careful using it. Unproperly used pointer could cause entire software failure.
As float z is defined locally in fucntion, it's allocated on stack.
As a result it memory allocation is destroyed when function exits.
As a result you will have a runtime error cause you are accesing a memory that do not belongs to you.

What does &struct_name and sometype ** variable_name do exactly? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I come from a Java background and I started reading K&R, but the progress is extremely slow, because I know most of it, but still have to read everything again. So, I was thinking that I could maybe ask here some things about the C programming language to learn things a lot faster.
What I want to know is
What happens when I pass a struct variable with a &-prefix as an argument to a function? The code sample that I am trying to understand is:
struct somestruct st;
somefunction(&st);
1.1. What kind of signature does somefunction need to have and what exactly is passed?
1.2. A pointer to the struct variable would be *st instead, right?
What does it mean when a function has as a parameter sometype ** variable_name? The code that I want to understand is:
int main(int argc, char **argv)
The whole code that I want to understand is here: https://stackoverflow.com/a/35355069/3668527
Please no explanations of the code. I know what it does. I just need to know what those strange new C operators & and ** mean.
Edit: Oh, and please tell me how these operators are called!
& get pointer to that variable.
The function signature should be: void somefunction(struct somestruct *st), i.e. it will accept pointer to that structure.
strct * means pointer to strct, strct ** means pointer to pointer to strct etc.
What happens when I pass a struct variable with a &-prefix as an argument to a
function? The code sample that I am trying to understand is:
The & operator returns the adress of an object.
What kind of signature does somefunction need to have and what exactly is passed?
void somefunction(struct somestruct *pointer);
You can put in "const" in a few places to tell the compiler that you don't want to allow the method to do any changes.
1.2 A pointer to the struct variable would be *st instead, right?
Depends in which context "*st" is used, if you just want to create a pointer do it that way:
somestruct *pointer = NULL; // or init it somehow
Edit: Oh, and please tell me how these operators are called! Thanks!
They are called adress operators.
What does it mean when a function has as a parameter sometype ** variable_name
That means that the parameter is a pointer pointing to another pointer.

A function that takes string parameter and returns integer pointer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am wondering,How to write a function in c that return int pointer for any string input
The below function is my attempt to solve the requirment
int* methodname(char* param)
{
int *a;
int b=3;
a=&b;
return a;
}
Please correct me for any mistakes.
Within the definition of the question, which places no functionality on the function, the following would be a proper implementation without mallocs or undefined behavior:
int* methodname(char* param)
{
return ((int *)param); // just return the param as a pointer to int
}
Returning local address is undefined, refer below code.
int* methodname(char* param)
{
int *p = malloc(5*sizeof(int));
. . .
return p;
}
Your declaration is ok but definition makes no sense, if any interviewer asked such kind of question their main intention is to check your programming skills, but your definition will not impress him, just write rough body(mainly concentrate on syntax, how you are returning and no undefined behavior) instead of implementing useless code.
According to what you asked. This code takes in a char* (char pointer), and returns a int* (pointer to int).
int* methodname(char* param)
{
int* b = malloc(sizeof(int));
*b = 3;
return b;
}
NOTE
The difference between your code and this one is, your code was returning int pointer to a local variable. The local variable will be destroyed after the function exits. In this example, the variable is allocated through malloc(). The memory allocated through malloc() is retained between function calls.
I would suggest going through scope rules in C.
Edit
There is nothing called string* in C. An array of chars with a terminating '\0' (NUL) is treated as a string.
Since the memory for the int is allocated by malloc(), it has to be freed to avoid any memory leaks. This can be done when the memory is not needed anymore.

when you declare a static variable in c [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
when you are declaring static variables in C,
say you wrote a program as such:
int *c;
void foo(){
c = (int *) malloc (10*sizeof(int));
c = &c[3];
*c = *&c[3];
}
What does it mean to have *c? I mean I understand that * means that it points to something but what does *c do?
and also, why do you need to cast (int *) the return value of malloc()?
when you are declaring static variables in C
Not related to this question, or atleast to the code you've shown.
but what does *c do?
Assuming your question related to the statement *c = *&c[3];, it refers to the object at address held by c.
why did you have to cast (int *) in front of malloc?
You should not. Please do not cast the return value of malloc() [and family].
Note: You code snippet is very poor and bad practice, most likely to be invalid. c = &c[3]; obvious memory leak.
I mean I understand that * means that it points to something but what does *c do?
The * does not always mean that it point to something.
Example:
If you write this:
int* c;
It means c is a pointer points to an int variable.
When you do like this:
int* c = &x;
*c = 5;
The second * is pointer c dereference.

typecasting a pointer to a multidimensional array in C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
# include <stdio.h>
# include <stdlib.h>
int main(int argc, char *argv[])
{
int a[5][10][2];
int *p;
p = (int(*)[10][2])p;//Gives error!
return EXIT_SUCCESS;
}
I want to type cast p to type so that it can act as a pointer to the given 3-d array?Is there a way to do so.I am applyindg the idea that the type of a variable is everything except variable name.
Why are you trying to "typecast" anything? Why would you expect a value "typecasted" to (int(*)[10][2]) to be compatible with an int * pointer? And why does your original code assigns p to p, completely ignoring a?
This is what you can do
int a[5][10][2];
int (*p)[10][2] = a;
Now p is a pointer that can be used to access a, i.e. p[i][j][k] is equivalent to a[i][j][k]. No typecasting necessary.
If you write p = (int(*)[10][2])a; it won't give you any errors, may be a warning. You are thinking that p will be converted to pointer to a 3-D array, which is wrong. Try this statement after assigning a to p.
printf("addresses %u %u",p,p+1);
According to you, output should be something similar to this(lets say) "addresses 9990000 99940000", because you are thinking p is pointing to 3-D array. However you will get similar to "addresses 9990000 9990004", proving that p is a pointer to an integer.

Resources