Is it possible to select a function inside an array and return it using a link?

I tried using a triplex pointer, but it continues to fail. Code:

#include <stdlib.h> #include <stdio.h> int set(int *** list) { int count, i; printf("Enter number:\n"); scanf("%d", &count); (*list) = (int **) malloc ( sizeof (int) * count); for ( i = 0; i<count;i++ ) { (**list)[count] = 123; } return count; } int main ( int argc, char ** argv ) { int ** list; int count; count = set(&list); return 0; } 

Thanks for any advice.

+4
source share
3 answers

What you call a list is actually an array. You can do it as follows:

 #include <stdlib.h> #include <stdio.h> ssize_t set(int ** ppList) { ssize_t count = -1; printf("Enter number:\n"); scanf("%zd", &count); if (0 <= count) { (*ppList) = malloc(count * sizeof **ppList); if (*ppList) { size_t i = 0; for (; i < count; ++i) { (*ppList)[i] = 42; } } else { count = -1; } } return count; } int main (void) { int * pList = NULL; size_t count = 0; { ssize_t result = set(&pList); if (0 > result) { perror("set() failed"); } else { count = result; } } if (count) { /* use pList */ } ... free(pList); return 0; } 
+6
source

As far as I understand your question, you want to return an array that is allocated in another function: here is a simple version of this

 #include<stdio.h> #include<stdlib.h> int* set(int *list) { int count, i; printf("Enter number:\n"); scanf("%d", &count); list = (int *) malloc ( sizeof (int) * count); for ( i = 0; i<count;i++ ) { list[i] = 123; } return list; } int main ( int argc, char ** argv ) { int *list; list = set(list); //Use whatever you want to do with that array free(list); // don't forget to free return 0; } 
+2
source

you have an array of integer arrays. Let's take a close look at your dialing function:

 for (i = 0; i < count;i++ ) { (**list)[count] = 123; } 

As you can see, you are processing each array object as an integer value. This should be a nested loop:

 for (i to n) // allocate each array for (k to m) // assign value for each value of array 
+1
source

Source: https://habr.com/ru/post/1443810/


All Articles