Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Initializing arrays

Status
Not open for further replies.

volgadev

Programmer
Mar 16, 2005
10
FR
Hello,

I am completely new to C programming. I use to be a Java programmer but I need to write a program in C. I am looking for a way to initialize an array with a computed length and didn't find any example in all the tutorials I found. The problem could be simplified to the following : ask the user to enter the length of the array, intialize the array to that length. How can one intialize an array with a length that is unkown at compile time ?
 
Simply.
Code:
#include <stdio.h>
#include <stdlib.h>

#define MAX 1000000
#define MIN 1

int main(void) {
int len;
char *ptr;

                while (1) {   
                   printf("Please enter length of array: ");
		   scanf(" %d",&len);
		   if (len < MIN || len > MAX) {return -1;}
		   if( (ptr = malloc(len * sizeof(len))) == NULL) {
		       printf("Could not malloc() for array\n");
		       return -1;
                   }
		   printf("Memory at %p\n",ptr);
		   free(ptr);
                  }
return 0;
}
 
Initializing an array as jstreich in a function doesn't accomplish anything if you want results in main().
Thus my example.
 
Thank you very much for your help. As I need to create the array in a function and access it in main, I guess I must use the solution proposed by marsd. Thanks again ! (I see that I have much to learn in C !)
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top