Dear all:
I would like to write a function that opens a file, reads and stores
data into an 2d array, and passes that array back to the caller
(=main). The size of the array is not known before opening to the
file.
I fail to write a function that allocates memory for a 2d array and
returns it to main. I was trying to pass a pointer to the array back
to main, but main cannot access the data. The simplified code (no
opening of file, but only allocation) is attached below along with the
output.
I will appreciate any comment on what is going wrong. Thank you for
your help.
Martin
#include <stdlib.h>
#include <stdio.h>
int create2DimArray (int nx,
int ny,
double ***pointerToMyA rray){
int i, j;
double **myArray;
// allocate memory for 2d array
myArray= (double **) malloc(nx* sizeof(double *));
for (i= 0; i< nx; i++){
myArray[i]= (double *) malloc(ny* sizeof(double)) ;
}
// fill array with funny numbers just for testing
for (i= 0; i< nx; i++){
for (j= 0; j< ny; j++){
myArray[i][j]= 1000.0* (double) i+ (double) j;
}
}
// print array to screen for testing/debugging
printf("in create2DimArray :\n");
for (i= 0; i< nx; i++){
for (j= 0; j< ny; j++){
printf(" i= %d, j= %d, %f\n", i, j, myArray[i][j]);
}
}
// return point er to array to caller
pointerToMyArra y= &myArray;
return 0;
}
int main(){
int nx, ny, i, j;
double ***pointerToMyA rray;
double **myArray;
nx= 3;
ny= 4;
// create 2d array
create2DimArray (nx, ny, pointerToMyArra y);
myArray= *pointerToMyArr ay;
// try to print array to screen
printf("in main:\n");
for (i= 0; i< nx; i++){
for (j= 0; j< ny; j++){
printf(" i= %d, j= %d, %f\n", i, j, myArray[i][j]);
}
}
return 0;
}
-----------------------------------------
output
-----------------------------------------
in create2DimArray :
i= 0, j= 0, 0.000000
i= 0, j= 1, 1.000000
i= 0, j= 2, 2.000000
i= 0, j= 3, 3.000000
i= 1, j= 0, 1000.000000
i= 1, j= 1, 1001.000000
i= 1, j= 2, 1002.000000
i= 1, j= 3, 1003.000000
i= 2, j= 0, 2000.000000
i= 2, j= 1, 2001.000000
i= 2, j= 2, 2002.000000
i= 2, j= 3, 2003.000000
in main:
Segmentation fault 8 3271
On Fri, 28 May 2004, M. Moennigmann wrote: Dear all: I would like to write a function that opens a file, reads and stores data into an 2d array, and passes that array back to the caller (=main). The size of the array is not known before opening to the file.
When it is known? If the file has the information as a header it makes it
easier. If the file just have raw data and you have to determine the size
at run time it would be more difficult.
I fail to write a function that allocates memory for a 2d array and returns it to main. I was trying to pass a pointer to the array back to main, but main cannot access the data. The simplified code (no opening of file, but only allocation) is attached below along with the output.
I will appreciate any comment on what is going wrong. Thank you for your help.
Here is one way to do it...
double **array;
allocate ROW * sizeof (double*), one pointer for each row of data
for each pointer
allocate COLUMN * sizeof double
return array
Even better would be, rather than the for each pointer code, allocate one
large block of memory (ROW*COLUMN*siz eof double) then have a for loop that
assigns a section of the memory to each pointer. This is better because
you only have two calls to malloc rather than ROW+1.
Martin
#include <stdlib.h> #include <stdio.h> int create2DimArray (int nx, int ny, double ***pointerToMyA rray){ int i, j; double **myArray;
// allocate memory for 2d array myArray= (double **) malloc(nx* sizeof(double *));
There is no need for the (double**) cast. It actually can hide mistakes.
If you forget to #include <stdlib.h> this could be a serious mistake.
Otherwise, this code corresponds to my allocating the ROW pointers.
By the way, what happens if malloc fails? Shouldn't you be checking for
this possibility and handling it. Both here and in all the calls below.
for (i= 0; i< nx; i++){ myArray[i]= (double *) malloc(ny* sizeof(double)) ; }
Again, lose the cast and check the results of th e malloc. This code is
more like the less efficient first method I presented.
// fill array with funny numbers just for testing for (i= 0; i< nx; i++){ for (j= 0; j< ny; j++){ myArray[i][j]= 1000.0* (double) i+ (double) j; } }
// print array to screen for testing/debugging printf("in create2DimArray :\n"); for (i= 0; i< nx; i++){ for (j= 0; j< ny; j++){ printf(" i= %d, j= %d, %f\n", i, j, myArray[i][j]); } }
// return point er to array to caller pointerToMyArra y= &myArray;
Not quite. Try:
*pointerToMyArr ay = myArray;
return 0; }
int main(){ int nx, ny, i, j; double ***pointerToMyA rray;
Nope. Try:
double **pointerToMyAr ray;
double **myArray;
nx= 3; ny= 4;
// create 2d array create2DimArray (nx, ny, pointerToMyArra y);
create2DimArray (nx, ny, &pointerToMyArr ay);
myArray= *pointerToMyArr ay;
// try to print array to screen printf("in main:\n"); for (i= 0; i< nx; i++){ for (j= 0; j< ny; j++){ printf(" i= %d, j= %d, %f\n", i, j, myArray[i][j]); } }
return 0; }
-----------------------------------------
output
----------------------------------------- in create2DimArray : i= 0, j= 0, 0.000000 i= 0, j= 1, 1.000000 i= 0, j= 2, 2.000000 i= 0, j= 3, 3.000000 i= 1, j= 0, 1000.000000 i= 1, j= 1, 1001.000000 i= 1, j= 2, 1002.000000 i= 1, j= 3, 1003.000000 i= 2, j= 0, 2000.000000 i= 2, j= 1, 2001.000000 i= 2, j= 2, 2002.000000 i= 2, j= 3, 2003.000000 in main: Segmentation fault
--
Send e-mail to: darrell at cs dot toronto dot edu
Don't send e-mail to vi************@ whitehouse.gov
In 'comp.lang.c', mm******@yahoo. com (M. Moennigmann) wrote: I would like to write a function that opens a file, reads and stores data into an 2d array, and passes that array back to the caller (=main). The size of the array is not known before opening to the file.
You can't 'pass (or return) an array' in C (And if you could, it would be
silly). You only can pass it's address and probaly interesting information
like its dimensions.
You probably need some structure to gather these information. A generic
dynamic 2D array could be :
typedef struct
{
/* array address */
void *a;
/* element size */
size_t es;
/* number of colomns */
size_t col;
/* number of lines */
size_t lin;
}
two_dim_s;
I fail to write a function that allocates memory for a 2d array and returns it to main.
On this basis, it's now quite simple :
#include <stdlib.h>
two_dim_s *two_dim_create (size_t es, size_t col, size_t lin)
{
/* allocates the object */
two_dim_s *this = malloc (sizeof *this);
if (this != NULL)
{
/* let's clear the object properly */
{
static two_dim_s z = {0};
*this = z;
}
/* allocates a linear array */
this->a = malloc (es * col * lin);
if (this->a != NULL)
{
/* stores the size information */
this->es = es;
this->col = col;
this->lin = lin;
}
else
{
/* memory error : delete the object and return NULL */
two_dim_delete (this);
this = NULL;
}
}
return this;
}
we also need the delete function :
void two_dim_delete (two_dim_s *this)
{
if (this != NULL)
{
/* free the array */
free (this->a);
/* debug purpose (and good manner too) */
this->a = NULL;
/* free the object */
free (this)
}
/* debug purpose (and good manner too) */
this= NULL;
}
Now, we need accessors. I give you the interfaces of the functions, but I let
you write the bodies.
The returned int is the error condition :
- 0 = OK
- <>0 = Error. Values to be defined.
int two_dim_write (two_dim_s *this, void const *p_value, size_t x, size_t y)
{
/* fill-in */
}
int two_dim_read (two_dim_s *this, void *p_value, size_t x, size_t y)
{
/* fill-in */
}
You'll need an 'internal' function that computes the address of an element
from its position. It's actually the 'heart' of the object :
static void *get_adddr (two_dim_s *this, size_t x, size_t y)
{
}
Important notice : None of the above code has been compiled or tested. It's
just a guideline.
--
-ed- get my email here: http://marreduspam.com/ad672570
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=c99
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
On 28 May 2004 11:41:53 -0700, mm******@yahoo. com (M. Moennigmann)
wrote: Dear all: I would like to write a function that opens a file, reads and stores data into an 2d array, and passes that array back to the caller (=main). The size of the array is not known before opening to the file.
I fail to write a function that allocates memory for a 2d array and returns it to main. I was trying to pass a pointer to the array back to main, but main cannot access the data. The simplified code (no opening of file, but only allocation) is attached below along with the output.
I will appreciate any comment on what is going wrong. Thank you for your help. Martin
#include <stdlib.h> #include <stdio.h> int create2DimArray (int nx, int ny, double ***pointerToMyA rray){
It would be much easier all around if the function returned the
address of the 2d array (or NULL in case of failure) rather than the
constant 0 and the use of the apparently confusing double***. int i, j; double **myArray;
// allocate memory for 2d array myArray= (double **) malloc(nx* sizeof(double *));
Don't cast the return from malloc. All you accomplish is suppressing
the diagnostic that would warn you about invoking undefined behavior
if you forget to include stdlib.h.
Always check the return from malloc for success before using it.
for (i= 0; i< nx; i++){ myArray[i]= (double *) malloc(ny* sizeof(double)) ; }
// fill array with funny numbers just for testing for (i= 0; i< nx; i++){ for (j= 0; j< ny; j++){ myArray[i][j]= 1000.0* (double) i+ (double) j;
Both casts are unnecessary.
} }
// print array to screen for testing/debugging printf("in create2DimArray :\n"); for (i= 0; i< nx; i++){ for (j= 0; j< ny; j++){ printf(" i= %d, j= %d, %f\n", i, j, myArray[i][j]); } }
// return point er to array to caller pointerToMyArra y= &myArray;
myArray is an automatic variable which will go out of existence as
soon as this function returns. Therefore, attempting to use its
address after that time would invoke undefined behavior.
pointerToMyArra y is a parameter of the function and will also
disappear at the end of the function. Assigning a value to it can
never have any affect on the calling function.
What you want here is
*pointerToMyArr ay = myArray;
return 0;
Why bother? It doesn't tell the calling function anything.
}
int main(){ int nx, ny, i, j; double ***pointerToMyA rray; double **myArray;
nx= 3; ny= 4;
// create 2d array create2DimArray (nx, ny, pointerToMyArra y); myArray= *pointerToMyArr ay;
As noted above, you did not change main's copy of pointerToMyArra y.
If you had, this attempt to dereference would invoke undefined
behavior.
You want to replace these two lines with
create2DimArray (nx, ny, &myArray);
Coupled with the change above, it will cause the function to store the
address IN function's myArray (not the address OF function's myArray)
in main's myArray so that main can then refer to the doubles using
normal subscript notation. // try to print array to screen printf("in main:\n"); for (i= 0; i< nx; i++){ for (j= 0; j< ny; j++){ printf(" i= %d, j= %d, %f\n", i, j, myArray[i][j]); } }
For completeness, you should free all the allocated memory. return 0; }
-----------------------------------------
output
----------------------------------------- in create2DimArray : i= 0, j= 0, 0.000000 i= 0, j= 1, 1.000000 i= 0, j= 2, 2.000000 i= 0, j= 3, 3.000000 i= 1, j= 0, 1000.000000 i= 1, j= 1, 1001.000000 i= 1, j= 2, 1002.000000 i= 1, j= 3, 1003.000000 i= 2, j= 0, 2000.000000 i= 2, j= 1, 2001.000000 i= 2, j= 2, 2002.000000 i= 2, j= 3, 2003.000000 in main: Segmentation fault
<<Remove the del for email>>
M. Moennigmann wrote: I would like to write a function that opens a file, reads and stores data into an 2d array, and passes that array back to the caller (=main). The size of the array is not known before opening to the file.
I fail to write a function that allocates memory for a 2d array and returns it to main. I was trying to pass a pointer to the array back to main, but main cannot access the data. The simplified code (no opening of file, but only allocation) is attached below along with the output.
I will appreciate any comment on what is going wrong. Thank you for your help.
cat main.c
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char* argv[]) {
int result = EXIT_SUCCESS;
if (1 < argc) {
FILE* fp = fopen(argv[1], "r");
if (NULL != fp) {
size_t m, n;
if (2 == fscanf(fp, "%u%u", &m, &n)) {
double A[m][n];
for (size_t i = 0; i < m; ++i)
for (size_t j = 0; j < n; ++j)
fscanf(fp, "%lf", &(A[i][j]));
fprintf(stdout, "A =\n");
for (size_t i = 0; i < m; ++i) {
for (size_t j = 0; j < n; ++j)
fprintf(stdout, " %f", A[i][j]);
fprintf(stdout, "\n");
}
}
else { // (2 != fscanf(fp, "%u%u", &m, &n))
fprintf(stderr, "Failed to read array dimensions!\n") ;
result = EXIT_FAILURE;
}
fclose(fp);
}
else { // (NULL == fp)
fprintf(stderr, "Failed to open file: %s\n", argv[1]);
result = EXIT_FAILURE;
}
}
else { // (argc <= 1)
fprintf(stderr, "Usage: %s <filename>\n" , argv[0]);
result = EXIT_FAILURE;
}
return result;
}
gcc -Wall -std=c99 -pedantic -o main main.c cat data
2 5
0 1 2 3 4
5 6 7 8 9
./main data
A =
0.000000 1.000000 2.000000 3.000000 4.000000
5.000000 6.000000 7.000000 8.000000 9.000000
On Tue, 01 Jun 2004 12:52:32 -0700, "E. Robert Tisdale"
<E.************ **@jpl.nasa.gov > wrote: > cat main.c #include <stdio.h> #include <stdlib.h>
int main(int argc, char* argv[]) { int result = EXIT_SUCCESS; if (1 < argc) { FILE* fp = fopen(argv[1], "r"); if (NULL != fp) { size_t m, n; if (2 == fscanf(fp, "%u%u", &m, &n)) {
m and n are not unsigned. You should be using %d.
double A[m][n];
This will only work for a C99 compiler.
for (size_t i = 0; i < m; ++i)
The declaration of i inside the for statement is a non-standard
extension.
for (size_t j = 0; j < n; ++j) fscanf(fp, "%lf", &(A[i][j])); fprintf(stdout, "A =\n"); for (size_t i = 0; i < m; ++i) { for (size_t j = 0; j < n; ++j) fprintf(stdout, " %f", A[i][j]); fprintf(stdout, "\n"); } } else { // (2 != fscanf(fp, "%u%u", &m, &n))
// comments are a C99 addition.
fprintf(stderr, "Failed to read array dimensions!\n") ; result = EXIT_FAILURE; } fclose(fp); } else { // (NULL == fp) fprintf(stderr, "Failed to open file: %s\n", argv[1]); result = EXIT_FAILURE; } } else { // (argc <= 1) fprintf(stderr, "Usage: %s <filename>\n" , argv[0]);
The angle brackets usually denote optional parameters. filename is
not optional.
result = EXIT_FAILURE; } return result; }
> gcc -Wall -std=c99 -pedantic -o main main.c > cat data 2 5 0 1 2 3 4 5 6 7 8 9
> ./main data A = 0.000000 1.000000 2.000000 3.000000 4.000000 5.000000 6.000000 7.000000 8.000000 9.000000
<<Remove the del for email>>
Slight modification to your code solves the problem.. mm******@yahoo. com (M. Moennigmann) wrote in message news:<98******* *************** ****@posting.go ogle.com>... #include <stdlib.h> #include <stdio.h> int create2DimArray (int nx, int ny,
+++++++++++++++ +++++++++++++ double ****pointerToMy Array){
+++++++++++++++ +++++++++++++++ int i, j; double **myArray;
// allocate memory for 2d array myArray= (double **) malloc(nx* sizeof(double *)); for (i= 0; i< nx; i++){ myArray[i]= (double *) malloc(ny* sizeof(double)) ; }
// fill array with funny numbers just for testing for (i= 0; i< nx; i++){ for (j= 0; j< ny; j++){ myArray[i][j]= 1000.0* (double) i+ (double) j; } }
// print array to screen for testing/debugging printf("in create2DimArray :\n"); for (i= 0; i< nx; i++){ for (j= 0; j< ny; j++){ printf(" i= %d, j= %d, %f\n", i, j, myArray[i][j]); } }
// return point er to array to caller
+++++++++++++++ +++++++++++++++ *pointerToMyArr ay= &myArray;
+++++++++++++++ +++++++++++++++ + return 0; }
int main(){ int nx, ny, i, j; double ***pointerToMyA rray; double **myArray;
nx= 3; ny= 4;
// create 2d array create2DimArray (nx, ny, pointerToMyArra y); myArray= *pointerToMyArr ay;
// try to print array to screen printf("in main:\n"); for (i= 0; i< nx; i++){ for (j= 0; j< ny; j++){ printf(" i= %d, j= %d, %f\n", i, j, myArray[i][j]); } }
return 0; }
On 2 Jun 2004 02:39:50 GMT, Barry Schwarz <sc******@deloz .net> wrote: On Tue, 01 Jun 2004 12:52:32 -0700, "E. Robert Tisdale" <E.************ **@jpl.nasa.gov > wrote:
double A[m][n];
This will only work for a C99 compiler.
Or gcc even before '99 as an extension. for (size_t i = 0; i < m; ++i)
The declaration of i inside the for statement is a non-standard extension.
Standard in C99, nonstandard before that.
// comments are a C99 addition.
Yes. Plus unwise in news, not that ERTroll is a paragon of netiquette. fprintf(stderr, "Usage: %s <filename>\n" , argv[0]);
The angle brackets usually denote optional parameters. filename is not optional.
*Square* brackets [] often indicate optional, although they are also
used for other things, like character classes. Angle brackets indicate
nonterminals in (some notations of) BNF; also HTML (and XML) tags,
often mandatory or at least necessary; and C++ template parameters, at
least some mandatory; and RFC822+ addresses and message-ids, and
RFC-I-forget delimited URLs, which are not at all optional; and the
same characters are used for I/O redirection in Unix and now other
(CUI) systems. (Angle and square brackets were also used for
directories in older DEC OSes, and the former for pathnames in Multics
and Stratus^WIBM VOS, but those aren't so relevant now.)
In theory argv[0] can be NULL, in which case this is undefined
behavior; or empty if the implementation can't provide it, in which
case the display is misleading, although in that circumstance there
isn't anything really much better we can do.
- David.Thompson1 at worldnet.att.ne t This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: deko |
last post by:
I need to create a basic one-dimensional array of strings, but I don't know
how many strings I'm going to have until the code is finished looping.
pseudo code:
Dim astrMyArray()
Do While Not rst.EOF
i = i + 1
If rst!Something = Then
astrMyArray(i) = rst!Something
|
by: gc |
last post by:
I am writing a function that given nx1 vector a and a nx1 b solves a
system of equations f(a,c)=b for a nx1 c.
While writing the function:
1] Should I allocate the memory for c within the function and return
the allocated memory?
something that leads to
double *solve(const double *a,const double *b,int n)
{
double *c;
|
by: slickn_sly |
last post by:
int find_index_of_min( float num, int arraySize )
{
int index, min;
min = 0;
for( index = 1; index < arraySize; index++ )
{
if( num > num )
{
min = index;
|
by: priya |
last post by:
Hi all,
I am new to this group.I am working in c language.I have dount
in pointer? how to retun array of pointer in function?
example
main()
|
by: Michel Rouzic |
last post by:
I had a program that worked perfectly, and that read .wav files. I
changed something so the tags of the wave file, instead of being each
in a different variable, are all in an array, called tag. i also set
macros such as #define bitspersample tag so when in my original
program it was written bitspersample now it acts like its tag, and
i also moved things that were in the main function into specific
functions. anyways, the program read the...
| |
by: Stijn van Dongen |
last post by:
A question about void*. I have a hash library where the hash create
function accepts functions
unsigned (*hash)(const void *a)
int (*cmp) (const void *a, const void *b)
The insert function accepts a void* key argument, and uses the
functions above to store this argument. It returns something (linked to
the key) that the caller can store a value in. The actual key argument
is always of the same pointer type (as seen in the caller,...
|
by: karthika.28 |
last post by:
Hi,
I am writing a function that needs to return an array of strings and I
am having some trouble getting it right. Can you help me answer the
following questions?
1. How does the function return the array?
2. How should the function be declared?
3. How is the return value captured by the calling program?
|
by: xhunga |
last post by:
I have try a new version of my work.
I have put the sizes of the matrix into the matrix.
A = number of rows
A = number of columns
The first element of the matrix is A
instead of A.
You can not use the row 0, and the column 0.
|
by: Samant.Trupti |
last post by:
HI,
I want to dynamically allocate array variable of type LPWSTR.
Code looks like this...
main() {
LPWSTR *wstr;
int count = Foo (wstr);
for (int i = 0; i < count; i++)
//print each element;
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |