프로그래밍/C2014. 5. 29. 09:32

strtok를 쓸 때, 왜 두번째 콜에서 NULL을 넘겨줄까? 그냥 그러려다 찾아보았다.


char str[] = "Hello World. How are you?";
        char delim[] = " ";
        char *ptr;

ptr = strtok(str, delim);
        printf("%s\n", ptr);
        while(ptr = strtok(NULL, delim))
            printf("%s\n", ptr);


다음은 strtok.c 의 내용이다.(glibc 2.19버전)


18 #include <string.h>
19 
20 
21 static char *olds;
22 
23 #undef strtok
24 
25 /* Parse S into tokens separated by characters in DELIM.
26  If S is NULL, the last string strtok() was called with is
27  used. For example:
28  char s[] = "-abc-=-def";
29  x = strtok(s, "-"); // x = "abc"
30  x = strtok(NULL, "-="); // x = "def"
31  x = strtok(NULL, "="); // x = NULL
32  // s = "abc\0=-def\0"
33 */
34 char *
36  char *s;
37  const char *delim;
38 {
39  char *token;
40 
41  if (s == NULL)
42  s = olds;
43 
44  /* Scan leading delimiters. */
45  s += strspn (s, delim);
46  if (*s == '\0')
47  {
48  olds = s;
49  return NULL;
50  }
51 
52  /* Find the end of the token. */
53  token = s;
54  s = strpbrk (token, delim);
55  if (s == NULL)
56  /* This token finishes the string. */
57  olds = __rawmemchr (token, '\0');
58  else
59  {
60  /* Terminate the token and make OLDS point past it. */
61  *s = '\0';
62  olds = s + 1;
63  }
64  return token;
65 }


41라인을 보면 NULL일 경우, static 변수 old로 대체한다. 아! 그래서 NULL을 써서 이어서 파싱이 되게 하는구나.  그리고 static변수라... 쓰레드 사용시에 문제가 있을 거 같다.

추가로 찾아본 내용을 보니,(http://ogoons.tistory.com/m/post/70) 다음과 같은 주의사항이 있다.


1. strtok()의 사용 후, 원본 문자열의 데이터를 보장할 수 없다.
2. visual studio 상위 버전에 문제가 있을 수 있다.
3. strtok()은 내부적으로 문자열 분리를 위해 static변수를 놓고 정적공유를 함으로 , thread-safe하지 않다.(음 역시)


따라서 위의 상황들을 개선한 strtok_s()를 쓰길 권장한다고 한다.


char str[] = "Hello World Good, Morning Sunshine";

char delim[] = " ,";

char *ptr;

char *context = NULL;

ptr = strtok_s(str, delim, &context);

printf("%s\n", ptr);

while(ptr = strtok_s(NULL, delim, &context))

printf("%s\n", ptr);


Posted by code cat
프로그래밍/C2014. 5. 7. 15:33


if 0로 묶여 있는 부분은 보통의 함수포인터를 부르는 방식이다.
하지만 이는 복잡해 보이고 혼란을 줄 수 있는 모양일 수 있다.  따라서 코드를 깔끔하게 보이기 위해 else로 묶여있는 부분을 보면 typedef를 통한 함수포인터 사용을 볼 수 있다.


typedef에 대한 부분이 혼란스러우면 아래와 같이 이해하면 좋다(출처:https://kldp.org/node/119822)

typedef를 빼면 변수 선언 붙이면 타입 선언이라고 이해하시면 편합니다.

unsigned int u32; // u32는 unsigned int 타입의 변수
typedef unsigned int u32; // u32는 unsigned int 타입

int (*func)(int, int); // func는 (int, int)를 받고 int를 리턴하는 함수에 대한 포인터 타입의 변수
typedef int (*func)(int, int); // func는 (int, int)를 받고 int를 리턴하는 함수에 대한 포인터 타입


'프로그래밍 > C' 카테고리의 다른 글

malloc 를 캐스팅 하지 말자.  (0) 2014.05.29
strtok에 NULL을 전달하는 이유  (0) 2014.05.29
ternary operator  (0) 2014.04.13
[visual studio] 에러 C2143 로컬변수 선언 위치  (0) 2013.11.24
c precedence table  (0) 2013.11.23
Posted by code cat
프로그래밍/python2014. 4. 24. 17:23

참조: 열혈강의 파이썬, 이강성 저

 

Class 는 하나의 이름 공간이며 기본적으로 다음과 같다.


위에서 상속도 나와있는데 OOP를 아는 사람이라면 쉽게 이해가 가능하다.

class Name:  #header
  pass          #body

class는 위와 같이 header와 body의 형태이며, header의 경우, :를 붙인다.  pass는 아무 일도 하지 않고 자리를 채우는 명령문이다.

 

method의 정의는 다음과 같다.

class MyClass:
  def set(self, v):
    self.value = v
  def put(self):
    print self.value

method를 정의하기 위해서는 def를 사용하며, 첫 인수로 self를 사용한다.  이는 자바에서 쓰는 'this'와 유사하다고 보면 된다.(자기자신의 인스턴스 객체를 가리킨다)

 

method 호출은 두가지 방법이 있다.

1. Unbound Class Method

>>> MyClass.set(c, 'egg')
>>> MyClass.put(c)

egg

2. Bound Instance Method

>>> c = MyClass()

>>> c.set('egg')

>>> c.put()

egg

 

class 내부에서의 method 호출은 self. 를 이용하여야 한다.

Posted by code cat
프로그래밍/C2014. 4. 13. 20:27

출처: http://en.wikipedia.org/wiki/%3F:

GNU확장은 다음과 같이 값을 프로세싱을 한번 이상 할 경우, 문제가 되는 경우를 대비해 다음과 같이 operand를 스킵할 수 있게 한다.


a = x ? : y;


상기 라인은 아래와 같다.

a = x ? x : y;


만일 x가 expression이라면, 한번만 프로세싱된다.


Posted by code cat
프로그래밍/C++2014. 2. 19. 08:51

jump to case label -fpermissive


라고 나오는 에러는 흔히 switch-case문에서 case안에서 변수 선언 & 초기화를 할 때 나올 수 있는 문제이다.  이는 언어에서 정한 standard를 벗어난 경우이며, -fpermissive를 써서 호환가능하게 해 줄 수는 있지만, 쓰지 말고, 코드를 fix하는 방향으로 가도록 하자.


'프로그래밍 > C++' 카테고리의 다른 글

[c++] UML autogenerator  (2) 2015.03.23
생성자 호출 방법  (0) 2015.03.19
[template]템플릿 예제  (0) 2013.08.04
null pointer vs stray pointer  (0) 2013.05.26
[c++] malloc/free 대신 new/delete을 쓰는 이유?  (0) 2013.05.18
Posted by code cat

push 된 tag를 지워야 할 때가 있는데...

다음과 같이 하면 된다.


repo forall –c git tag –d TAG_NAME

repo forall –c git push --tags


Posted by code cat


출처: http://stuff.mit.edu/afs/athena/astaff/project/opssrc/cups/autoconf-2.65/build-aux/git-version-gen


Git은 알다시피, hash 값을 기반으로 형상 관리를 한다.  따라서 svn처럼 revision number에 따른 가시적인 버전 차이점을 사람이 인식하기 힘들다.

tagging이라는 훌륭한 방법이 있지만, 각 tagging마다의 차이점라던가, 어느 tagging이 우선인지(직접 사람이 tagging에 적어주지 않으면 힘들다) 등에 대해서 알 방법이 명확하지 않다.

따라서 git에서도 개발 시에, 일종의 revision numbering이 필요 할 때가 있다.  

우선 간단하게 commit 카운트로 revision numbering을 하기로 했는데, 시간이 날 때 하기 코드를 참조해서 좀 더 포괄적인 numbering 관리 방법을 만들어야 겠다.


Posted by code cat
프로그래밍2013. 12. 24. 21:08

최신 버전은 아니지만 나름 재밌게 읽고 있는 중

Posted by code cat
프로그래밍2013. 12. 5. 09:24

코드 관련 체크툴을 검색하다가 cpplint라는 google coding style 체크를 해 주는 툴을 보게 되어 사용해 보았다.


사용법은 간단하여 다음과 같이 하면 된다.


$>python cpplint.py <directory>/example.cpp


시험삼아 안드로이드의 프레임 워크 쪽 수정한 부분에 대해서 돌려봤는데...


이건 내가 수정한 거보다 구글러 코드가 더 문제로 많이 잡혀서... 난감하네.




'프로그래밍' 카테고리의 다른 글

[Ruby] gem install 시에 에러  (0) 2014.09.06
[읽는중] 점프투파이썬  (0) 2013.12.24
db8 schema  (0) 2013.12.03
[일반][프로그래밍]비대칭경계  (0) 2013.10.26
pair coding 를 하기 위한 자세  (0) 2012.04.27
Posted by code cat
프로그래밍2013. 12. 3. 20:23


출처:https://developer.palm.com/content/api/reference/data-types/db8.html

db8 Data Types

 Date Type

Description 

Ref'd by 

Wrapper APIs 

Service APIs 
BatchOperation Method and parameters for operation in batch.     batch
BatchResponse Response to batch API call.     batch
CountResponse Number of objects affected by operation.   del
merge
del
merge
ErrResponse Standard error response, containing operation success or failure flag, error code and error message.   del
delKind
find
get
merge
put
putKind
reserveIds
batch
del
delKind
find
get
merge
put
putKind
reserveIds
search
watch
FindResponse Response to find operation.   find find
search
GetResponse Parameters for get objects operation response.   get get
IndexClause Used for creating indexes for kind object.   putKind
putKind
IndexPropClause Defines index property. IndexClause    
NotificationResponse Notifies caller of change in query results.   find find
search
watch
PutResponse Indicates success of operation and returns id and revfields for each object.   del
merge
put
del
merge
put
PutResult Contains id and revfield for JSON data object stored in put operation. PutResponse    
Query Defines db8 query.   del
merge
find
del
merge
find
watch
ReserveIdsResponse Contains operation success or failure flag and array of reserved db8 IDs.   reserveIds reserveIds
RevSetClause Defines a revision set for a kind. SeeUsing Revision Setsfor more information.     putKind
RevSetPropClause Defines a property in a revision set. RevSetClause    
SuccessResponse Indicates operation success or failure.   delKind
putKind
delKind
putKind
watch
WhereClause Defines SQL-like JSON where clause for query. Query    


 


BatchOperation

Method and params for batch operation.

Schema

{
   "method" : string,
   "params" : any
}

Elements

Element Required Type Description
method Yes string Operation to perform. Possible values: "del", "find", "get", "merge", or "put".
params Yes any Method parameters.


 


BatchResponse

Response to batch operation.

Schema

{
   "returnValue" : boolean,
   "responses"   : any array
}

Elements

Element Required Type Description
returnValue Yes boolean Success (true) or Failure (false).
responses Yes any array Array of responses for each of the operations in the batch.


 


CountResponse

Number of objects affected by operation.

Schema

{
   "returnValue" : boolean,
   "count"       : int
}

Elements

Element Required Type Description
returnValue Yes boolean true (success) or false (failure).
count Yes int Number of objects affected by operation.


 


ErrResponse

Standard error response, containing operation success or failure flag, error code and error message.

Schema

{
   "returnValue" : boolean,
   "errorCode"   : int,
   "errorText"   : string
}

Elements

Element Required Type Description
returnValue Yes boolean true (success) or false (failure).
errorCode Yes int Numeric error code.
errorText Yes string Error message.


 


FindResponse

Response to a find objects operation.

Schema

{
   "returnValue" : boolean,
   "results"     : any,
   "count"       : int,
   "next"        : string
}

Elements

Element Required Type Description
returnValue Yes boolean true (success) or false (failure).
results Yes any Array of db8 kind data objects. What is returned depends on the query and what is stored.
count No int Number of results that would have been returned if a limit had not been specified.
next No string Key to pass as query's "page" property when retrieving next page of results.


 


GetResponse

Parameters for get objects operation response.

Schema

{
      "returnValue" : boolean,
      "results"     : any
}

Elements

Element Required Type Description
returnValue Yes boolean true (success) or false (failure).
result Yes any object array Returns array of stored db8 data objects.


 


IndexClause

Used in the putKind call for creating kind object indexes. Note that indexes determine the type of queries your app can make. See Queries and Indexing for more information.

Set the "incDel" flag to true if you want future queries to return marked as deleted objects. Objects are not completely deleted until an administrative purge operation takes place.

Schema

{
   "name"    : string,
   "props"   : IndexPropClause,
   "incDel"  : boolean
}

Elements

Element Required Type Description
name Yes string Index name
props Yes IndexPropClause Array of properties to index together.
incDel No boolean Include deleted objects flag. Default is false.

Example

{
   "name"   : "state", 
   "props"  : [{"name": "state"}],
   "incDel" : false
}


 


IndexPropClause

Defines index property for IndexClause

Schema

{
   "name"     : string,
   "collate"  : string, 
   "default"  : any,
   "tokenize" : string,
   "type"     : string
}

Elements

Element Required Type Description
name Yes string Name of property being indexed.
collate   No string Indicates the string comparison routine used to order the index. Must be one of the following:
  • default—Does binary comparison.
  • primary—Compares base characters (for example, "a" < "b") without considering accents, case, or tone marks.
  • secondary—Accents in the characters are considered secondary differences (for example, "as" < "às" < "at"). Other differences between letters can also be considered secondary differences, depending on the language. A secondary difference is ignored when there is a primary difference anywhere in the strings.
  • tertiary—Upper and lower case differences in characters are distinguished at the tertiary level (for example, "ao" < "Ao" < "aò"). In addition, a variant of a letter differs from the base form on the tertiary level (such as "A" and "?"). A tertiary difference is ignored when there is a primary or secondary difference anywhere in the strings.
default No any Default value to set for this property at insertion time, if not present.
tokenize No string

Indicates if words in strings should be broken up, i.e., should "Hello World" become "Hello" and "World" for purposes of indexing.

Must be one of the following:

  • none—Does not tokenize.
  • default—Use the default for the locale (which may strip stop-words). Stop-words are common words that are stripped for purposes of indexing, i.e., "the", "a", "an", "is", etc.
  • all—Tokenizes all words.
type Yes string "single" or "multi". Single property or multiple properties.

 


NotificationResponse

Notifies caller of change in query results returned from a "find" call.

Schema

{
   "returnValue" : boolean,
   "fired"       : boolean
}

Elements

Element Required Type Description
returnValue No boolean true (success) or false (failure).
fired Yes boolean Change notification flag.


 


PutResponse

Indicates success of operation and returns id and rev fields for each object.

Schema

{
   "returnValue" : boolean,
   "results"     : PutResult 
}

Elements

Element Required Type Description
returnValue Yes boolean true (success) or false (failure).
results Yes PutResult Array of objects containing the id and rev of each object that was put.


 


PutResult

Contains "id" and "rev" fields in PutResponse for JSON data object.

Schema

{
   "id"    : any,
   "rev"   : any
}

Elements

Element Required Type Description
id Yes any ID of the object that was put.
rev Yes any Object's revision ID. Every db8 object has this ID field. db8 maintains a global rev id counter that is incremented every time a db8 object is created or updated.


 


Query

Defines a db8 query.

Schema

{
   "select"  : string array,
   "from"    : string,
   "where"   : WhereClause array,
   "orderBy" : string,
   "desc"    : boolean,
   "incDel"  : boolean,
   "limit"   : int,
   "page"    : string
}

Elements

Element Required Type Description
select No string array Array of property names to return.
from Yes string Name of kind to retrieve results from.
where No WhereClausearray Array of clauses to test.
orderBy No string Order results on this property.
desc No boolean Return results in descending order.
incDel No boolean Include deleted objects. Deleted objects have _del=true.
Note: You can only request this if the "incDel" field was true when you created your indexes during a "putKind" operation. Otherwise, the query fails with a "no index for this query" message.
limit No int Specifies maximum number of results to return (0-500). Default is 500.
page No string Page key returned by previous query.

Example

{
   "select"  : ["displayName", "state"],
   "from"    : "com.mystuff.contacts:1",
   "where"   : [{"prop":"state","op":"=","val":"CA"}], 
   "orderBy" : "displayName",
   "desc"    : true 
}

 


ReserveIdsResponse

Contains operation success or failure flag and array of reserved db8 IDs returned from "reserveIds" call.

Schema

{
   "returnValue" : boolean,
   "ids"         : string array
}

Elements

Element Required Type Description
returnValue Yes boolean true (success) or false (failure).
ids No string array Array of reserved IDs.


 


RevSetClause

Defines a revision set—subset of an object's properties that your app can be notified about when one of the properties is modified. See Using Revision Sets for more information.

Schema

{
   "name"  : string,
   "props" : RevSetPropClause array
}

Elements

Element Required Type Description
name Yes string Name of the revision set (unique to this kind).
props Yes RevSetPropClausearray Array of properties to include in revision set.

 


RevSetPropClause

A property in a RevSetClause.

Schema

{
   "name"  : string,
}

Elements

Element Required Type Description
name Yes string Name of property to include in revision set.


 


SuccessResponse

Indicates operation success or failure.

Schema

{
   "name"  : string,
}

Elements

Element Type Description
returnValue boolean true (success) or false (failure).

Example

{
   "returnValue": false
}

 


WhereClause

Defines a SQL-like JSON where clause for a db8 Query.

Schema

{
   "prop"    : string,
   "op"      : string, 
   "val"     : any,
   "collate" : string
}

Elements

Element Required Type Description
prop Yes string Name of property to test.
op Yes string Test operator. Must be one of the following:
"<", "<=", "=", ">=", ">", "!=", "%", "?"
(less than, less than or equal, equals, greater than or equal, greater than, not equal, wildcard, and full-text)
The "%" operator (aka - the prefix operator) will return all matches beginning with the value specified.
val Yes any Value to test against.
collate No any Indicates the string comparison routine used to order the results. See the collate field in the IndexPropClause data structure for more information.

Example

{
   "prop" : "state",
   "op"   : "=",
   "val"  : "CA"
}


'프로그래밍' 카테고리의 다른 글

[읽는중] 점프투파이썬  (0) 2013.12.24
cpplint 사용후기  (0) 2013.12.05
[일반][프로그래밍]비대칭경계  (0) 2013.10.26
pair coding 를 하기 위한 자세  (0) 2012.04.27
콘솔상 동작 상태 애니메이션  (0) 2012.04.12
Posted by code cat