#include <stdio.h>
#include <stdlib.h>
void set(int **arr, int *data, int rows, int cols) {
int i;
for(i=0; i<rows*cols; ++i) {
arr[((i+1)/rows) % rows][(i+1) % cols]=data[i];
}
}
int main() {
int rows=3, cols=3, sum=0;
int i;
int **arr;
int data[ ]={5, 2, 7, 4, 1, 8, 3, 6, 9};
arr= (int**)malloc(sizeof(int*) * rows);
for(i=0; i<rows; i++) {
arr[i]= (int *) malloc(sizeof(int) * cols);
}
set(arr, data, rows, cols);
for(i=0; i<rows*cols; i++) {
sum+=arr[i / rows][i % cols] * (i %2 == 0 ? 1: -1);
}
for(i=0; i<rows; i++) {
free(arr[i]);
}
free(arr);
printf("%d", sum);
return 0;
}
오랜만에 malloc과 free의 사용예시를 볼 수 있었다.
#include <stdio.h>
char Data[5]={'B', 'A', 'D', 'E'};
char c;
int main(){
int i, temp, temp2;
c = 'C';
printf("%d\n", Data[3]-Data[1]);
for(i=0;i<5; ++i){
if(Data[i]>c)
break;
}
temp=Data[i];
Data[i]=c;
i++;
for(; i<5; ++i){
temp2=Data[i];
Data[i]=temp;
temp=temp2;
}
for(i=0; i<5; i++){
printf("%c", Data[i]);
}
return 0;
}
printf는 파이썬 print와 다르게 end=’’라는 거.! 파이썬 보다가 C 보면 기초적인 건데 헷갈릴 수 있다.
처음 Data[4]는 ‘\0’으로 채워진다. 이것은 escape character + ASCII 코드 8진수이다.
예를 들면
‘\n’은 ASCII 코드 10, 8진수로는 12이므로,
‘\12’ 혹은 ASCII 코드 16진수로 ‘\x0A’이다.
#include <stdio.h>
#include <stdlib.h>
typedef struct Data {
int value;
struct Data *next;
} Data;
Data *insert(Data *head, int value) {
Data *new_node=(Data *)malloc(sizeof(Data));
new_node->value= value;
new_node->next= NULL;
if (head== NULL)
return new_node;
new_node->next= head;
head=new_node;
return head;
}
Data *reconnect(Data *head, int disconnect_count) {
if(head==NULL || head->value==disconnect_count)
return head;
Data *prev=head, *curr=head->next;
while(curr&& curr->value!=disconnect_count) {
prev=curr;
curr= curr->next;
}
if(curr==NULL) return head;
prev->next= curr->next;
curr->next=head;
return curr;
}
int main(){
Data *head=NULL, *curr=NULL, *tmp=NULL;
int i;
for (i=1; i<=5; i++)
head=insert(head, i);
head= reconnect(head, 3);
for(curr=head; curr != NULL; curr=curr->next)
printf("%d", curr->value);
while(head){
tmp= head;
head= head->next;
free(tmp);
}
return 0;
}