Hi I'm a newbie in C programming attending a night course. Right now I'm trying to learn about: arrays, calloc and pointers.
None of these things has truly sunken in yet, I'm still not comfortable using them.
Using:
* Windows Vista 32-bit
* Bloodshed Dev-C++ v.4.9.9.2
* 4 GB RAM
Example code 1: /* Complex_Numbers_01_INT.c */ - [ semi-OK ]
I have 2 example codes. The first works fine except it can't handle floating-point numbers properly so you can only test it using Integers.
Example code 2: /* Complex_Numbers_02_LF.c */ - [ BAD ]
The second example code I basically replaced all INT data types with DOUBLE data types and replaced most %d with %lf when using:
scanf() and printf()
The Crash / The Problem
Only when I run the second example code with the DOUBLE and %lf in the source code does the program crash. You have to run it around 6-10 times before it crashes.
I'm suspecting it's some kind of memory leak problem but I am too newbie to see it and handle it.
What am I doing wrong? What have I misunderstood?
Example code 1: - [ semi-OK ]
Code:
/* Complex_Numbers_01_INT.c */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int *tempPointer_a1;
int *tempPointer_b1;
int n,i,j;
printf("How many complex numbers do you want to input? --> "); scanf("%d",&n);
/* calloc = Memory allocation for array */
tempPointer_a1 = (int *) calloc(n,sizeof(int));
tempPointer_b1 = (int *) calloc(n,sizeof(int));
for(i=0 ; i<n ; i++){
printf("\n\nInput a complex number Re(a%d)+Im(b%d), for element number <%d>.", i, i, i);
printf("\ni.e. input 2 floating-point numbers: --> ");
scanf("%d %d", tempPointer_a1+i, tempPointer_b1+i );
}
for(i=0 ; i<n ; i++)
printf("\n< Element number %d > , Re(a%d)+Im(b%d) = %d + %d (j)", i, i, i, tempPointer_a1[i], tempPointer_b1[i] );
free(tempPointer_a1);
free(tempPointer_b1);
printf("\n\n");
system("PAUSE");
return 0;
}
Example code 2: - [ BAD ]
Code:
/* Complex_Numbers_02_LF.c */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
double *tempPointer_a1;
double *tempPointer_b1;
int n,i,j;
printf("How many complex numbers do you want to input? --> "); scanf("%d",&n);
/* calloc = Memory allocation for array */
tempPointer_a1 = (double *) calloc(n,sizeof(int));
tempPointer_b1 = (double *) calloc(n,sizeof(int));
for(i=0 ; i<n ; i++){
printf("\n\nInput a complex number Re(a%d)+Im(b%d), for element number <%d>.", i, i, i);
printf("\ni.e. input 2 floating-point numbers: --> ");
scanf("%lf %lf", tempPointer_a1+i, tempPointer_b1+i );
}
for(i=0 ; i<n ; i++)
printf("\n< Element number %d > , Re(a%d)+Im(b%d) = %lf + %lf (j)", i, i, i, tempPointer_a1[i], tempPointer_b1[i] );
free(tempPointer_a1);
free(tempPointer_b1);
printf("\n\n");
system("PAUSE");
return 0;
}