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
i have watched tutorial that explain how to return array from function
and this is similar code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *grn();
int main()
{
int *a;
a=grn();
for(int i = 0;i<10;i++){
printf("%d\n",a[i]);
}
return 0;
}
int *grn(){
static int arrayy[10];
srand((unsigned) time(NULL));
for(int i=0;i<10;i++){
arrayy[i]=rand();
}
return arrayy;
}
and i have some questions about it..
it is work fine and generate random values inside the array but
why the function grn is pointer
and why a variable in the main function is pointer ?
why the arrayy array is static?
and why should i make the grn function pointer?
when i try to run this code but the arrayy variable is not static i get segmentation fault
The function isn't the pointer. The return value is int * since it returns an array of int.
You need a pointer to access an array. If it's not a pointer, then you are expecting a single int variable.
If it's not static, then the array will be deallocated and gone when the function reached to return. The array is neither a global variable, nor an allocated memory in heap, so it will be deallocated when the function reached to return. If you make it static, it works like a global variable (not exactly) and will not be deallocated when the function reaches to the end.
Read number 1.
Lastly, you get segmented fault because the function returned a dangling pointer because the array is not static therefore deallocated when the function reached to the end.
Related
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 1 year ago.
Improve this question
I like to know is this code wrong. reasons pleasec
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void func(char **c)
{
strcpy(c[0],"he");
strcpy(c[1],"h");
// memcpy(*c[2],"hell",sizeof("hell"));
// c[0]="hello";
//c[1]="hi";
}
int main()
{
char *arr[2];
arr[0]=malloc(sizeof(char[3]));
arr[1]=malloc(sizeof(char[2]));
func(arr);
printf("%s\n",arr[0]);
printf("%s\n", arr[1]);
return 0;
}
this line seems to allocate 3 * sizeof(char)
arr[0]=malloc(sizeof(char[3]));
this line seems to allocate 2 * sizeof(char)
arr[1]=malloc(sizeof(char[2]));
can array of pointers point to variable sized strings?
Yes.
is this code wrong.
func() is brittle in that it may exhibit undefined behavior depending on value of input.
No information about how many c[] may be indexed.
No information about how many bytes are available for strcpy(c[i], ....) to copy.
func() is OK in main() as it passes in a value that happens to not exceed the function limitations in OP's case.
func() is a wrong design in that is lacks parameters to guide its limitations and lacks null pointer error detection.
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.
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
if the given function is as exp:then how to calculate no of rows in the given 2d array input2
void fun(char *input2[])
{
//calculate no of rows and in each row no of column
}
In general no. In C, it's not possible to calculate the size of an array using only a pointer to it.
However, if you're given a limitation, that the array is terminated by zero(^), then you can count the number of values before the zero using a loop. If it is an array of pointers (such as you have), then the terminator could be a pointer to a specific value. For example, a pointer to zero(^).
Without that limitation, you must store the length in a variable.
(^) you may use any specific value, but zero is a good choice for pointers and characterstrings.
In C, array parameters decay into simple pointers, so you have to design your function to also accept the length of the array:
void fun(char *input2[], int input2Len);
If you also define an array length macro you can call fun like this:
#define LEN(arr) ((int) (sizeof (arr) / sizeof (arr)[0]))
char *strings[10];
...
fun(strings, LEN(strings));
it is impossible to know the size of an array passed to function as argument, in form of type function(type array[]), that because array is a pointer to the first element of it. but there is no information about the last element.
to get over this issue. there are many solutions that we can implement. some of them may alter the implementation of the function itself as passing the size of the array in a second parameter. but if we want to keep function definition untouched. leaves to two possibilities:
1) setting the number of elements on the first item;
2) marking the end of the array (usually is an empty item)
it is almost the second one which is most adopted, here is the code to illustrate that:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int mySizeOfArray(char *input[]){
char **p=input; //p point to the first element of array
while(*p){
p++;//int crementing the pointer
}
return p-input;//return the difference between them
}
/*__________________________________________________________
*/
int main(){
char *input2[]={"First","Second","Third",/*Last*/NULL};
printf("Size of input=%d\n",mySizeOfArray(input2));
return 0;
}
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.
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
my program
#include<stdio.h>
#include<conio.h>
char* mystrcat(char* , char* );\\ function declared as global
main()
{
char dest[50]="hello"; \\destination string
char src[50]="readers"; \\source string
clrscr();
mystrcat(dest,src);\\function calling but does not have receiving array
puts("after concatenation"); \\ of strings
puts(dest);\\shows "helloreaders"<-- how?
getch();
return 0;
}
char* mystrcat(char* des, char *sr)\\for concatenating two strings
{
int i=0,j=0;
while(des[i]!='\0')
{ i++;}
while(sr[j]!='\0')
{
des[i]=sr[j];
i++;j++;
}
des[i]='\0';
puts(sr);\\"readers"
puts(des);\\"helloreaders"
return sr;\\returning source string
}
output:
readers
helloreaders
after concatenating:
helloreaders
I am returning only source string from mystrcat(). But how compiler knows the modified destination string? Since I declare the function globally the compiler knows the modified string?
It is not because of return sr, rather it is because char* mystrcat(char* des, char *sr) modified its argument ( des ). Even if you change the return value to just an int, the result will be same. The reason is when you pass a char[] variable to a function, you just pass a pointer, anything you did inside the function to the variable will be reflected to the caller.
When you called function
mystrcat(dest,src);\\function calling but does not have receiving array
you passed as arguments two arrays that are implicitly converted to pointers to first elements of each array.
So inside the function you deal with addresses of the memory extents occupied by the arrays. And you write in the memory occupied by the destination array elements of the source array
while(sr[j]!='\0')
{
des[i]=sr[j];
i++;j++;
}
des[i]='\0';
because des and sr hold addresses of first elements of the arrays.
So the memory occupied by array dest was overwritten.
You are giving mystrcat() a pointer to dest and when it writes through that pointer, it changes dest directly. It doesn't matter what the function returns. des[] in mystrcat() is not a copy of dest[] in the main program, it's the same thing.
because parameters you pass to the function are points,arrays they point to are changed, but these points are not changed