C: lenght of array


 
Thread Tools Search this Thread
Top Forums Programming C: lenght of array
# 1  
Old 05-17-2013
C: lenght of array

Doing some training code with arrays i run into the following issue: If i ask the user how long the array is supposed to be, malloc it and then ask for the values inside the array and return the list to main and assing it to a pointer to list of integers:

Code:
#include <stdio.h>
#include <stdlib.h>

int *make_list(void); 
void get_num(int *); 
void print_reverse(int *, int); 

int main(void)
{
    int *v = NULL; 

    
    v = make_list(); 

    return 0; 
}

int *make_list(void)
{
    int n = 0; 
    int i = 0; 
    int *tmp = NULL; 
    
    printf("how long? "); 
    get_num(&n); 
    tmp = (int *) malloc(n * sizeof(int)); 

    for (i = 0; i < n; i++) {
        printf("value "); 
        get_num(tmp+i); 
    }
    return tmp; 
}


void get_num(int *n)
{
    char buf[BUFSIZ]; 

    printf("number: "); 
    fgets(buf, sizeof(buf), stdin); 
    *n = atoi(buf); 
}

i lost all ways to find out how much elements that list has, right?

And the other way around: If i have a list of integers and add it as an argument to a fucntion:
print_list(v)
there is no way to find out how long the list is inside the function called print_list() ?

If both is true, would using a global variable for the length be a good solution?

Last edited by tornow; 05-17-2013 at 09:08 PM.. Reason: error with malloc
# 2  
Old 05-17-2013
Yes, you have to keep a variable wich keeps number of elements in your array.

In many situations I find it convenient to hold ptr to array and counter together in one simple structure. If element of an array is a struct itself then I add another int to my structure to hold sizeof of one element. This way you can have a lib function to init an array, to add an element to it etc...
This User Gave Thanks to migurus For This Post:
# 3  
Old 05-17-2013
Thanks for your answer. I like the idea.
The following is how i implemented it, asking if that would be the way you proposed it:

Code:
#include <stdio.h>
#include <stdlib.h>


struct numlist {
    int *v; 
    int n; 
}; 


struct numlist make_list(void); 
void print_list(struct numlist list); 
void get_num(int *); 

int main(void) 
{
    struct numlist numbers; 


    numbers = make_list(); 
    print_list(numbers);     

    return 0; 
}


struct numlist make_list(void)
{
    struct numlist tmp; 
    int n = 0; 
    int i = 0; 

    printf("list len "); 
    get_num(&n); 

    tmp.n = n; 
    tmp.v = (int *) malloc(tmp.n * sizeof(int)); 
    if ( tmp.v == NULL ) {
        fprintf(stderr, "memory error\n"); 
        exit(-1); 
    }


    for (i = 0; i < n; i++) {
          printf("list element "); 
          get_num(tmp.v + i); 
    }


    return tmp; 
}


void print_list(struct numlist list)
{
    int i = 0; 
    
    printf("\n\tresulting list\n"); 
    for (i = 0; i < list.n; i++) {
        printf("element with index %d has value: %d\n",
                i, list.v[i]); 
    }
}


void get_num(int *x)
{
    char buf[BUFSIZ]; 

    printf("number: "); 
    fgets(buf, sizeof(buf), stdin); 
    *x = atoi(buf); 
}

I mainly got two questions:
1) I was not sure if to use a "struct numlist numbers" or a pointer to a numlist: "struct numlist *numbers"

2) I am not sure if memory for the structure (numbers in main) is set up correctly.
# 4  
Old 05-20-2013
I have no system available to test your code.

For your Q.1 I'd use "struct numlist *numbers" in main and change make_list to return pointer to structure.

The Q.2 is not clear to me, what does not look right to you?
# 5  
Old 05-20-2013
Quote:
Originally Posted by migurus
I have no system available to test your code.

For your Q.1 I'd use &quot;struct numlist *numbers&quot; in main and change make_list to return pointer to structure.

The Q.2 is not clear to me, what does not look right to you?
Q.1: ok, thanks. y

Q.2: Inside of the function make_list() i declare a struct num_list tmp, but i don't allocate any memory. I allocate memory to the list, depending how much elements it will contain. Will the struct num_list tmp have enough memory to store the list, no matter how much elements the list contains? (The question reveals that memory allocation is not always clear to me).
# 6  
Old 05-20-2013
Quote:
Originally Posted by tornow
Q.2: Inside of the function make_list() i declare a struct num_list tmp, but i don't allocate any memory. I allocate memory to the list, depending how much elements it will contain. Will the struct num_list tmp have enough memory to store the list, no matter how much elements the list contains? (The question reveals that memory allocation is not always clear to me).
numlist holds two and only two things:
1) A pointer to memory
2) An integer

Does a pointer get bigger or smaller? No... A pointer is just a number, always the same size.
This User Gave Thanks to Corona688 For This Post:
# 7  
Old 05-20-2013
Your Q.2 is now clear - yes, the tmp structure has a pointer *v which will hold address of the beginning of the array of integers, which you malloc'ed. Corona clarified it already.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Bash 3.2 - Array / Regex - IF 3rd member in array ends in 5 digits then do somthing...

Trying to do some control flow parsing based on the index postion of an array member. Here is the pseudo code I am trying to write in (preferably in pure bash) where possible. I am thinking regex with do the trick, but need a little help. pesudo code if == ENDSINFIVEINTS ]]; then do... (4 Replies)
Discussion started by: briandanielz
4 Replies

2. UNIX for Advanced & Expert Users

how to find lenght of fixed width file record?

actually i am trying to find the lenght of fixed width file record reading from teradata db but its not working can u guys help me out? code which i wrote--- colmn_lngth=`cat $RPT_FILE | awk -F~ '{print $1}'` rm $RPT_FILE while read line do result=`echo $line | wc -m` ... (4 Replies)
Discussion started by: Seshendranath
4 Replies

3. Shell Programming and Scripting

Check input for lenght, special characters and letter case

I made menu script for users so they can run other script without going in shell just from menu. But i must control their input. These are criteria: Input must have 4 signs First two signs are always lower case letters Input shall not have some special signs just letters and numbers ... (1 Reply)
Discussion started by: waso
1 Replies

4. Shell Programming and Scripting

korn shell display lenght problem!!! i got stuck on this

Using the KSH, write a shell script called display_by_length, which takes an absolute pathname to a directory and displays all ordinary files in the directory ordered by their length; for each file listed, display the name of the file and its length - nothing else. Extend this script to take an... (1 Reply)
Discussion started by: babuda0059
1 Replies

5. UNIX for Advanced & Expert Users

NIS username max lenght

Hi I want to know the maximum length of user name under NIS? I tried googling but it didnt help :(. If there is any command to find out this please let me know. I know on unix user name should be 8 characters long but just i want to know if i can have 9 letter user under mapped under NIS. (1 Reply)
Discussion started by: zedex
1 Replies

6. Shell Programming and Scripting

Sort based on string lenght.

I'm not familiar with find. If i use find in a certain directory i want it to show based on hierarchy. find . type d fol1 fol1/subfol1 fol1/subfol1/subfol1 fol2 fol2/subfol2 i want it to show like this fol1/subfol1/subfol1 fol1/subfol1 fol1 fol2/subfol2 fol2 do i need to use... (5 Replies)
Discussion started by: ryandegreat25
5 Replies

7. Programming

Creating an array to hold posix thread ids: Only dynamic array works

I am facing a strange error while creating posix threads: Given below are two snippets of code, the first one works whereas the second one gives a garbage value in the output. Snippet 1 This works: -------------- int *threadids; threadids = (int *) malloc (num_threads * sizeof(int)); ... (4 Replies)
Discussion started by: kmehta
4 Replies

8. Shell Programming and Scripting

Can we convert a '|' file into a fixed lenght???

Hi All, I have a pipe separated flat file.But there is often some problem with the records.So is it possible to convert the '|' separated file into a fixed length file by means of some script. The file has 11 columns which means 10 pipes.Your help is appreciated. i'm using Sun OS Version... (2 Replies)
Discussion started by: kumarsaravana_s
2 Replies

9. UNIX for Dummies Questions & Answers

How to remove files with zero lenght

How to remove files with zero lenght with one or more commands from the same directory? Thanks. (2 Replies)
Discussion started by: GNMIKE
2 Replies

10. IP Networking

how can change udp lenght?

How can change udp lenght? Hello. I have FreeBsd 4.7 and i want to change udp datagramm lenght. Where it can be? What i must do? I can rebuild my core but it is not good for me. Thanks! (4 Replies)
Discussion started by: Vvlad
4 Replies
Login or Register to Ask a Question