/*
* Author: MH
* Since 2020/03/17
* Toolkit: GDB Online
*/
#include <stdio.h>
int main()
{
int min=1;
int max=100;
int num;
for(num=min; num<=max; num++)
{
if((num&(num-1))==0)
{
printf("%d is power of 2\n", num);
}
}
return 0;
}
搜尋此網誌
[C/C++][找出2的冪次方]
注意括弧的位置
[C/C++][pass array of character pointers]
主要是想傳遞 argv
/*
* Author: MH
* Since 2018/04/26
* Toolkit: Code::Block 16.01
*/
#include <stdio.h>
#include <stdlib.h>
int printArrayOfCharPointers (int argc, char *argv[])
{
int i;
for (i=0; i<argc; i++)
{
printf("argv[%d] %s\n", i, argv[i]);
}
/*
print the following messages
argv[0] abc123
argv[1] mh-resource
argv[2] ##**##
*/
return 0;
}
int main(int argc, char *argv[])
{
int argc_tmp = 3;
char *argv_tmp[3];
char p1[256];
char p2[256];
char p3[256];
memcpy(p1, "abc123", sizeof("abc123"));
argv_tmp[0] = p1;
memcpy(p2, "mh-resource", sizeof("mh-resource"));
argv_tmp[1] = p2;
memcpy(p3, "##**##", sizeof("##**##"));
argv_tmp[2] = p3;
printArrayOfCharPointers(argc_tmp, argv_tmp);
return 0;
}
[C/C++][實作strcmp]
/*
* Author: MH
* Since 2017/11/24
* Toolkit: Code::Block 16.01
*/
int strcmp_implementation(char *source, char *dest)
{
while (*source!='\0' || *dest!='\0')
{
if (*source!=*dest)
return -1;
source++, dest++;
}
return 0;
}
int main()
{
char *source = "abc";
char *dest1 = "abc";
char *dest2 = "abd";
printf("ret1: %d\n", strcmp_implementation(source, dest1)); // return 0
printf("ret2: %d\n", strcmp_implementation(source, dest2)); // return -1
system("pause");
return 0;
}
[C/C++][印出不同字體顏色與背景]
/*
* Author: MH
* Since 2014/11/11
* Toolkit: Code::Block 13.12
*/
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
int colorIndex;
for(colorIndex=0; colorIndex<255; colorIndex++)
{
SetConsoleTextAttribute(hConsole, colorIndex);
printf("%3d %s\n", colorIndex, "Hello World!");
}
SetConsoleTextAttribute(hConsole, 15);
system("PAUSE");
return 0;
}
[C/C++][回傳陣列]
/*
* Author: MH
* Since 2014/09/30
* Toolkit: Code::Block 13.12
*/
#include <iostream>
using namespace std;
int *returnArray() {
static int ra[5];
int arrayIndex;
for ( arrayIndex=0; arrayIndex<5; arrayIndex++ ) {
ra[arrayIndex] = arrayIndex;
}
return ra;
}
int main()
{
int *getArray = returnArray();
int ii;
for (ii=0; ii<5; ii++) {
cout << *(getArray+ii) << endl;
}
return 0;
}
[C/C++][找出最大最小值]
在C語言中,要比較兩個數值誰大誰小應該是非常簡單的
1. 用 if 判斷式與大於、小於,這應該是最直接也是最容易想到的方法
2. 用三元運算子,其實也是一樣意思,只是看起來比較簡潔
3. bitwise 運算,這是本篇文章主要要討論的
首先我們要先知道,在 bitwise 運算下,兩數值可不必透過第三個數值做交換的動作,詳細請看以前的文章:[C/C++][不透過第三個變數做兩數值交換],既然可透過 bitwise 運算交換兩數值,那接下來就要做判斷了
在上述程式碼中,有個特別的地方,就是 -(a<b),比方說當 a=1, b=2 時,-(a<b) 就會是 -1,轉換成二進制來看的話就是全部都是 1,跟 (a^b) 做 AND operation 後還是 (a^b),套用上述的"不透過第三個變數做兩數值交換"的結果可知,(b^((a^b) & (-(a<b)))) = (b^(a^b)) = a;那如果 a=2, b=1 時,-(a<b) 就會是 0,跟 (a^b) 做 AND operation 後還是 0,(b^((a^b) & (-(a<b)))) = (b^0) = b,即是找出較小的值
那如果要找最大值呢?很簡單,只要改最前面的 b 就好了,如下
1. 用 if 判斷式與大於、小於,這應該是最直接也是最容易想到的方法
2. 用三元運算子,其實也是一樣意思,只是看起來比較簡潔
(a<b)?a:b
3. bitwise 運算,這是本篇文章主要要討論的
首先我們要先知道,在 bitwise 運算下,兩數值可不必透過第三個數值做交換的動作,詳細請看以前的文章:[C/C++][不透過第三個變數做兩數值交換],既然可透過 bitwise 運算交換兩數值,那接下來就要做判斷了
#include <iostream>
using namespace std;
int main () {
int a = 1;
int b = 2;
cout << (b^((a^b) & (-(a<b)))) << endl; // min(a, b)
return 0;
}
在上述程式碼中,有個特別的地方,就是 -(a<b),比方說當 a=1, b=2 時,-(a<b) 就會是 -1,轉換成二進制來看的話就是全部都是 1,跟 (a^b) 做 AND operation 後還是 (a^b),套用上述的"不透過第三個變數做兩數值交換"的結果可知,(b^((a^b) & (-(a<b)))) = (b^(a^b)) = a;那如果 a=2, b=1 時,-(a<b) 就會是 0,跟 (a^b) 做 AND operation 後還是 0,(b^((a^b) & (-(a<b)))) = (b^0) = b,即是找出較小的值
那如果要找最大值呢?很簡單,只要改最前面的 b 就好了,如下
#include <iostream>
using namespace std;
int main () {
int a = 1;
int b = 2;
cout << (a^((a^b) & (-(a<b)))) << endl; // max(a, b)
return 0;
}
[C/C++][strlen實作]
/*
* Author: MH
* Since 2013/10/29
* Toolkit: Code::Block 12.11
*/
#include <stdio.h>
int strlen_implementaion (const char *str) {
int countStr = 0;
while (*(str+countStr)!='\0')
countStr++;
return countStr;
}
int main () {
char *str = "abcde";
printf("%d", strlen_implementaion(str)); // 5
return 0;
}
[C/C++][實作strcpy與strncpy]
/*
* Author: MH
* Since 2013/10/28
* Toolkit: Code::Block 12.11
*/
#include <stdio.h>
char *strcpy_implementation(char *strDst, const char *strSrc) {
char *newStr = NULL;
int strCount = 0;
if ((strDst==NULL) || (strSrc==NULL)) {
return NULL;
}
newStr = strDst;
while (*(strSrc+strCount)!='\0') {
*newStr = *(strSrc+strCount);
newStr++;
strCount++;
}
*newStr = '\0';
return strDst;
}
int main () {
char *str1 = "Sample string";
char str2[20];
strcpy_implementation (str2, str1);
printf ("str1: %s\n", str1);
printf ("str2: %s\n", str2); // str2: Sample string
return 0;
}
網路上還有看到比較簡潔的寫法
/*
* Author: MH
* Since 2013/10/28
* Toolkit: Code::Block 12.11
*/
#include <stdio.h>
void strcpy_implementation2 (char x[], char y[]) {
int i = 0;
while ((x[i]=y[i])!='\0') {
i+=1;
}
}
int main () {
char *str1 = "Sample string";
char str2[20];
strcpy_implementation2 (str2, str1);
printf ("str1: %s\n", str1);
printf ("str2: %s\n", str2); // str2: Sample string
return 0;
}
/*
* Author: MH
* Since 2013/10/28
* Toolkit: Code::Block 12.11
*/
#include <stdio.h>
char *strncpy_implementation(char *strDst, const char *strSrc, int strLength) {
char *newStr = NULL;
int strCount = 0;
if ((strDst==NULL) || (strSrc==NULL)) {
return NULL;
}
newStr = strDst;
while ((*(strSrc+strCount)!='\0') && (strCount<strLength)) {
*newStr = *(strSrc+strCount);
newStr++;
strCount++;
}
*newStr = '\0';
return strDst;
}
int main () {
char *str1 = "Sample string";
char str2[20];
strncpy_implementation (str2, str1, 4);
printf ("str1: %s\n", str1);
printf ("str2: %s\n", str2); // str2: Samp
return 0;
}
[C/C++][傳遞與回傳字串]
/*
* Author: MH
* Since 2013/10/21
* Toolkit: Code::Block 12.11
*/
#include <stdio.h>
void returnString(char **str2)
{
printf("before: %s\n", *str2); // before: abc
*str2 = "def";
printf("after: %s\n", *str2); // before: def
}
int main()
{
char *str1 = "abc";
printf("before returnString: %s\n", str1); // before returnString: abc
returnString(&str1);
printf("after returnString: %s\n", str1); // before returnString: def
return 0;
}
[C/C++][不同欄位的動態二維陣列]
要特別注意的是 p 的產生方法,最後 deallocate 可簡單的用剛好可 deallocate 最大 column 數即可,當然也可依每個 row 的不同 column 去 deallocate
/*
* Author: MH
* Since 2013/10/21
* Toolkit: Code::Block 12.11
*/
#include <iostream>
using namespace std;
int main() {
int i, r=3;
// generate rows
int **p = new int *[r];
// generate columns
p[0] = new int[1]; // columns for the 1st row
p[1] = new int[2]; // columns for the 2nd row
p[2] = new int[3]; // columns for the 3rd row
// assign values
p[0][0] = 1;
p[1][0] = 2; p[1][1] = 2;
p[2][0] = 3; p[2][1] = 3; p[2][2] = 3;
// output the value
cout << p[0][0] << endl;
cout << p[1][0] << " " << p[1][1] << endl;
cout << p[2][0] << " "<< p[2][1] << " "<< p[2][2] << endl;
// deallocate
for (i=0; i<r; i++) {
delete []p[i]; // delete columns
}
delete []p;
return 0;
}
[C/C++][Structure Pointer]
對變數 student 其中的成員取用為 s.name
若用指標方法存取 student *ps,則必須使用箭頭 ps->name
若用指標方法存取 student *ps,則必須使用箭頭 ps->name
/*
* File Name: StructurePointer.cpp
* Author: MH
* Since 2013/04/01
* Toolkit: Dev C++ 4.9.9.9
*/
#include <stdio.h>
struct student{
char name[4];
int id;
float gpa;
};
int main(){
struct student s = {"Sam", 9732, 3.5};
struct student *ps = &s;
// ps: a pointer pointing to structure variable s
struct student &rs = s;
// rs: a reference variable, it is an alias of s
printf("%s %d %f\n", s.name, s.id, s.gpa);
printf("%s %d %f\n", ps->name, ps->id, ps->gpa);
printf("%s %d %f\n", rs.name, rs.id, rs.gpa);
return 0;
}
[C/C++][別名]
/*
* File Name: AliasUsingDereference.c
* Author: MH
* Since 2013/04/01
* Toolkit: Dev C++ 4.9.9.9
*/
#include <stdio.h>
int main(){
int x = 5;
int *p;
p = &x;
printf("*p = %d\n", *p);
*p = 6;
printf("x = %d", x);
return 0;
}
/*
* File Name: AliasUsingReference.c
* Author: MH
* Since 2013/04/01
* Toolkit: Dev C++ 4.9.9.9
*/
#include <stdio.h>
int main(){
int a = 5;
int &b = a;
printf("b = %d\n", b);
b = 6;
printf("a = %d", a);
return 0;
}
[C/C++][傳遞字串]
簡單的範例
/*
* File Name: StringAsParameters.c
* Author: MH
* Since 2013/03/25
* Toolkit: Dev C++ 4.9.9.9
*/
#include <stdio.h>
int main(){
void change(char *);
char s[] = "abcdefg";
char t[] = "ijklmnop";
change(s);
change(t);
puts(s); // ab$de+g
puts(t); // ij$lm+op
return 0;
}
void change(char *x){
*(x+2) = '$'; // x[2]='$';
*(x+5) = '+'; // x[5]='+';
}
[C/C++][幻方]
幻方,有時又稱魔方,可參考動畫圖

Source:http://en.wikipedia.org/wiki/File:SiameseMethod.gif
Source:http://en.wikipedia.org/wiki/File:SiameseMethod.gif
/*
* File Name: MagicSquare.c
* Author: MH
* Since 2013/03/10
* Toolkit: Dev C++ 4.9.9.9
*/
#include <stdio.h>
#define max_n 20
int main(){
int x[max_n][max_n];
int i, j, k, n;
do{
printf("Enter odd array size (3~19): ");
scanf("%d", &n);
}while((n>19) || (!(n%2)) || (n<3));
// fill zero into array
for (i=0; i<n; i++)
for (j=0; j<n; j++)
x[i][j] = 0;
// by placing a 1 in the middle location of top row
i = 0;
j = (n-1)/2; // find the central position
x[i][j] = 1;
for (k=2; k<=n*n; k++){
// write successive integers in an upward-right diagonal path;
i--;
j++;
// if the row and column indices all out of bound
// the next location will be at the second row
// the (n-1)th column
if ((i<0) && j>n-1){
i = 1; // second row
j = n-1; // (n-1)the column
}
// if the row index out of bound (i<0)
// use the maximum row index
else if (i<0)
i = n-1;
// if the column index out of bound (j>n-1)
// use the minimum column index
else if (j>(n-1))
j = 0;
if (x[i][j]!=0){
i += 2;
j--;
}
x[i][j] = k;
}
for (i=0; i<n; i++){
for (j=0; j<n; j++){
printf("%4d", x[i][j]);
}
printf("\n");
}
return 0;
}
[C/C++][動態二維陣列的使用]
/*
* File Name: Dynamic2DimentionalArray.cpp
* Author: MH
* Since 2013/03/03
* Toolkit: Dev C++ 4.9.9.9
*/
#include <iostream>
using namespace std;
int main(){
int r, c, **p, i, j;
cout << "enter the row: ";
cin >> r;
cout << "enter the column: ";
cin >> c;
cout << endl;
p = new int *[r]; // generating rows
for (i=0; i<r; i++) // generating columns
p[i] = new int[c]; // Not new int *[c]!!
for (i=0; i<r; i++) // accessing: assigning values
for (j=0; j<c; j++)
p[i][j] = i;
for (i=0; i<r; i++){ // accessing: printing values
for (j=0; j<c; j++)
cout << p[i][j] << " ";
cout << endl;
}
for (i=0; i<r; i++) // deallocate the memory
delete []p[i]; // delete columns
delete []p;
return 0;
}
[C/C++][動態一維陣列的使用]
/*
* File Name: Dynamic1DimentionalArray.cpp
* Author: MH
* Since 2013/03/03
* Toolkit: Dev C++ 4.9.9.9
*/
#include <iostream>
using namespace std;
int main(){
int size, i, *q;
cout << "enter the size: ";
cin >> size;
q = new int [size]; // generating
for (i=0; i<size; i++) // accessing: assigning values
q[i] = i;
for (i=0; i<size; i++) // accessing: printing values
cout << q[i] << " ";
// deallocate the memory when no longer needed
delete []q;
return 0;
}
[C/C++][動態變數的使用]
/*
* File Name: DynamicVariable.cpp
* Author: MH
* Since 2013/03/03
* Toolkit: Dev C++ 4.9.9.9
*/
#include <iostream>
using namespace std;
int main(){
int *s;
s = new int;
cout << "intput int *s " << endl;
cin >> *s; // generating
cout << "*s = " << *s << endl;
// deallocate the memory when no longer needed
delete s;
return 0;
}
[C/C++][Bubble Sort]
/*
* File Name: BubbleSort.c
* Author: MH
* Since 2013/02/22
* Toolkit: Dev C++ 4.9.9.9
*/
#include <stdio.h>
#include <stdlib.h>
void swap (int *a, int *b){
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
int main(int argc, char *argv[]){
int i, j, n=5;
int list[5] = {10, 7, 19, 5, 6};
printf("Before Bubble Sort\n");
for (i=0; i<n; i++)
printf("list[%d] = %d\n", i, list[i]);
for (i=0; i<n-1; i++)
for (j=0; j<n-i-1; j++)
if (list[j]>list[j+1])
swap(&list[j], &list[j+1]);
printf("\nAfter Bubble Sort\n");
for (i=0; i<n; i++)
printf("list[%d] = %d\n", i, list[i]);
system("PAUSE");
return 0;
}
[C/C++][Selection Sort]
/*
* File Name: SelectionSort.c
* Author: MH
* Since 2013/02/22
* Toolkit: Dev C++ 4.9.9.9
*/
#include <stdio.h>
#include <stdlib.h>
void swap (int *a, int *b){
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
int main(int argc, char *argv[]){
int i, j, n=5;
int list[5] = {10, 7, 19, 5, 6};
printf("Before Slelction Sort\n");
for (i=0; i<n; i++)
printf("list[%d] = %d\n", i, list[i]);
for (i=0; i<n; i++)
for (j=i+1; j<n; j++)
if (list[i]>list[j])
swap(&list[i], &list[j]);
printf("\nAfter Slelction Sort\n");
for (i=0; i<n; i++)
printf("list[%d] = %d\n", i, list[i]);
system("PAUSE");
return 0;
}
[C/C++][實作memset、memcpy與memcmp]
memset請參考:http://www.cplusplus.com/reference/cstring/memset/
memcpy請參考:http://www.cplusplus.com/reference/cstring/memcpy/
memcmp請參考:http://www.cplusplus.com/reference/cstring/memcmp/
void *memset(void *s, char c, unsigned long n){
unsigned long i;
char *ss = (char *)s;
for (i=0; i<n; i++)
ss[i] = (char)c;
return s;
}
memcpy請參考:http://www.cplusplus.com/reference/cstring/memcpy/
void *memcpy(void *dest, const void *src, unsigned long count){
char *tmp = dest;
const char *s = src;
while (count--)
*tmp++ = *s++;
return dest;
}
memcmp請參考:http://www.cplusplus.com/reference/cstring/memcmp/
int memcmp(const void *cs, const void *ct, unsigned long count){
const unsigned char *su1, *su2;
int res = 0;
for (su1=cs, su2=ct; 0<count; ++su1, ++su2, count--)
if ((res = *su1 - *su2) != 0)
break;
return res;
}
訂閱:
意見 (Atom)