Skip to content

Instantly share code, notes, and snippets.

@TerryJung
Created September 18, 2014 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TerryJung/79f53d39fb391a1fbd02 to your computer and use it in GitHub Desktop.
Save TerryJung/79f53d39fb391a1fbd02 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
int **memoryAllocation(int **A, int n);
void initOnes(int **A, int n);
void printA(int **A, int n);
int **memoryFree(int **A, int n);
int countOnes(int **A, int n);
int main()
{
int **A = NULL;
int n;
int count=0;
srand(time(NULL));
n = 10;
A = memoryAllocation(A, n);
initOnes(A, n);
printA(A, n);
count = countOnes(A, n);
A = memoryFree(A, n);
n = 50;
A = memoryAllocation(A, n);
initOnes(A, n);
printA(A, n);
// count = countOnes(A, n);
A = memoryFree(A, n);
n = 100;
A = memoryAllocation(A, n);
initOnes(A, n);
printA(A, n);
// count = countOnes(A, n);
A = memoryFree(A, n);
}
int **memoryAllocation(int **A, int n)
{
int i,j;
// 2차원 포인터의 동적할당
A = (int **)malloc(sizeof(int)*n); // 2차원 메모리 할당
for (i=0; i<n; i++) // 각 행(1차원) 메모리 할당
*(A+i) = (int *)malloc(sizeof(int)*n);
// 초기화
for (i=0; i<n; i++)
for (j=0; j<n; j++)
A[i][j] = 0;
return A;
}
void initOnes(int **A, int n)
{
int i,j;
int preNumber, randomNumber, oneNumber;
preNumber = n;
for (i=0; i<n; i++) {
randomNumber = rand()%n + 1;
oneNumber = (randomNumber>preNumber) ? preNumber : randomNumber;
for (j=0; j<oneNumber; j++) A[i][j] = 1;
preNumber = oneNumber;
}
}
void printA(int **A, int n)
{
int i,j;
printf("A[%d][%d]\n",n,n);
for (i=0; i<n; i++) {
for (j=0; j<n; j++) {
printf("%d",A[i][j]);
}
printf("\n");
}
printf("\n");
}
int **memoryFree(int **A, int n)
{
int i;
for (i=0; i<n; i++) free (*(A+i));
free(A);
return A;
}
int countOnes(int **A, int n)
{
int i = 0;
int j = 0;
int num = 0;
clock_t start, finish;
double duration;
start = clock();
for(j=0;j<n;j++) {
if(A[i][j]=1) {
num++;
continue;
}
if(A[i][j]=0) {
i++; j=0;
if(i==n+1)
break;
}
}
return num;
printf("1의 개수 : %d", num);
finish = clock();
duration = (double)(finish - start); // ms
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment