Science says lasting relationships come down to—you guessed it—kindness and generosity.
Every day in June, the most popular wedding month of the year, about
13,000 American couples will say “I do,” committing to a lifelong
relationship that will be full of friendship, joy, and love that will
carry them forward to their final days on this earth.
Except, of course, it doesn’t work out that way for most people.
The majority of marriages fail, either ending in divorce and separation or devolving into bitterness and dysfunction.
Of all the people who get married, only three in ten remain in
healthy, happy marriages, as psychologist Ty Tashiro points out in his
book "The Science of Happily Ever After," which was published earlier
this year.
Social scientists first started studying marriages by observing them
in action in the 1970s in response to a crisis: Married couples were
divorcing at unprecedented rates. Worried about the impact these
divorces would have on the children of the broken marriages,
psychologists decided to cast their scientific net on couples, bringing
them into the lab to observe them and determine what the ingredients of a
healthy, lasting relationship were.
Was each unhappy family unhappy in its own way, as Tolstoy claimed,
or did the miserable marriages all share something toxic in common?
Psychologist John Gottman was one of those researchers. For the
past four decades, he has studied thousands of couples in a quest to
figure out what makes relationships work. I recently had the chance to
interview Gottman and his wife Julie, also a psychologist, in New York
City. Together, the renowned experts on marital stability run The
Gottman Institute, which is devoted to helping couples build and
maintain loving, healthy relationships based on scientific studies.
John Gottman began gathering his most critical findings in
1986, when he set up “The Love Lab” with his colleague Robert Levenson
at the University of Washington. Gottman and Levenson brought newlyweds
into the lab and watched them interact with each other.
With a team of researchers, they hooked the couples up to electrodes
and asked the couples to speak about their relationship, like how they
met, a major conflict they were facing together, and a positive memory
they had. As they spoke, the electrodes measured the subjects' blood
flow, heart rates, and how much they sweat they produced. Then the
researchers sent the couples home and followed up with them six years
later to see if they were still together.
From the data they gathered, Gottman separated the couples into two major groups: the masters and the disasters.
The masters were still happily together after six years. The disasters
had either broken up or were chronically unhappy in their marriages.
When the researchers analyzed the data they gathered on the couples,
they saw clear differences between the masters and disasters. The
disasters looked calm during the interviews, but their physiology,
measured by the electrodes, told a different story. Their heart rates
were quick, their sweat glands were active, and their blood flow was
fast. Following thousands of couples longitudinally, Gottman found that
the more physiologically active the couples were in the lab, the quicker
their relationships deteriorated over time.
But what does physiology have to do with anything? The problem
was that the disasters showed all the signs of arousal — of being in
fight-or-flight mode — in their relationships. Having a conversation
sitting next to their spouse was, to their bodies, like facing off with a
saber-toothed tiger.
Even when they were talking about pleasant or mundane facets of
their relationships, they were prepared to attack and be attacked. This
sent their heart rates soaring and made them more aggressive toward
each other. For example, each member of a couple could be talking about
how their days had gone, and a highly aroused husband might say to his
wife, “Why don’t you start talking about your day. It won’t take you
very long.”
The masters, by contrast, showed low physiological arousal. They felt
calm and connected together, which translated into warm and
affectionate behavior, even when they fought. It’s not that the masters
had, by default, a better physiological make-up than the disasters; it’s
that masters had created a climate of trust and intimacy that made both
of them more emotionally and thus physically comfortable.
Gottman wanted to know more about how the masters created that
culture of love and intimacy, and how the disasters squashed it. In a
follow-up study in 1990, he designed a lab on the University of
Washington campus to look like a beautiful bed and breakfast retreat.
He invited 130 newlywed couples to spend the day at this retreat and
watched them as they did what couples normally do on vacation: cook,
clean, listen to music, eat, chat, and hang out. And Gottman made a
critical discovery in this study — one that gets at the heart of why
some relationships thrive while others languish.
Throughout the day, partners would make requests for
connection, what Gottman calls “bids.” For example, say that the husband
is a bird enthusiast and notices a goldfinch fly across the yard. He
might say to his wife, “Look at that beautiful bird outside!” He’s not
just commenting on the bird here: he’s requesting a response from his
wife — a sign of interest or support — hoping they’ll connect, however
momentarily, over the bird.
The wife now has a choice. She can respond by either “turning toward”
or “turning away” from her husband, as Gottman puts it. Though the
bird-bid might seem minor and silly, it can actually reveal a lot about
the health of the relationship. The husband thought the bird was
important enough to bring it up in conversation and the question is
whether his wife recognizes and respects that.
People who turned toward their partners in the study responded by
engaging the bidder, showing interest and support in the bid. Those who
didn’t — those who turned away — would not respond or respond minimally
and continue doing whatever they were doing, like watching TV or reading
the paper. Sometimes they would respond with overt hostility, saying
something like, “Stop interrupting me, I’m reading.”
These bidding interactions had profound effects on marital
well-being. Couples who had divorced after a six-year follow up had
“turn-toward bids” 33 percent of the time. Only three in ten of their
bids for emotional connection were met with intimacy. The couples who
were still together after six years had “turn-toward bids” 87 percent of
the time. Nine times out of ten, they were meeting their partner’s
emotional needs.
By
observing these types of interactions, Gottman can predict with up to
94 percent certainty whether couples — straight or gay, rich or poor,
childless or not — will be broken up, together and unhappy, or together
and happy several years later. Much of it comes down to the spirit
couples bring to the relationship. Do they bring kindness and
generosity; or contempt, criticism, and hostility?
“There’s a habit of mind that the masters have,” Gottman
explained in an interview, “which is this: they are scanning social
environment for things they can appreciate and say thank you for. They
are building this culture of respect and appreciation very purposefully.
Disasters are scanning the social environment for partners’ mistakes.”
“It’s not just scanning environment,” chimed in Julie Gottman. “It’s scanning the partner for what the partner is doing right or scanning him for what he’s doing wrong and criticizing versus respecting him and expressing appreciation.”
Contempt, they have found, is the number one factor that tears
couples apart. People who are focused on criticizing their partners miss
a whopping 50 percent of positive things their partners are doing and
they see negativity when it’s not there.
People who give their partner the cold shoulder — deliberately
ignoring the partner or responding minimally — damage the relationship
by making their partner feel worthless and invisible, as if they’re not
there, not valued. And people who treat their partners with contempt and
criticize them not only kill the love in the relationship, but they
also kill their partner's ability to fight off viruses and cancers. Being mean is the death knell of relationships.
Kindness, on the other hand, glues couples together. Research
independent from theirs has shown that kindness (along with emotional
stability) is the most important predictor of satisfaction and stability
in a marriage. Kindness makes each partner feel cared for, understood,
and validated—feel loved. “My bounty is as boundless as the sea,” says
Shakespeare’s Juliet. “My love as deep; the more I give to thee, / The
more I have, for both are infinite.” That’s how kindness works too:
there’s a great deal of evidence showing
the more someone receives or witnesses kindness, the more they will be
kind themselves, which leads to upward spirals of love and generosity in
a relationship.
There are two ways to think about kindness. You can think about it as
a fixed trait: either you have it or you don’t. Or you could think of
kindness as a muscle. In some people, that muscle is naturally stronger
than in others, but it can grow stronger in everyone with exercise.
Masters tend to think about kindness as a muscle. They know that they
have to exercise it to keep it in shape. They know, in other words, that
a good relationship requires sustained hard work.
“If your partner expresses a need,” explained Julie Gottman, “and you
are tired, stressed, or distracted, then the generous spirit comes in
when a partner makes a bid, and you still turn toward your partner.”
In that moment, the easy response may be to turn away from your
partner and focus on your iPad or your book or the television, to mumble
“Uh huh” and move on with your life, but neglecting small moments of
emotional connection will slowly wear away at your relationship. Neglect
creates distance between partners and breeds resentment in the one who
is being ignored.
The hardest time to practice kindness is, of course, during a
fight—but this is also the most important time to be kind. Letting
contempt and aggression spiral out of control during a conflict can
inflict irrevocable damage on a relationship.
“Kindness
doesn’t mean that we don’t express our anger,” Julie Gottman explained,
“but the kindness informs how we choose to express the anger. You can
throw spears at your partner. Or you can explain why you’re hurt and
angry, and that’s the kinder path.”
John Gottman elaborated on those spears: “Disasters will say things
differently in a fight. Disasters will say ‘You’re late. What’s wrong
with you? You’re just like your mom.’ Masters will say ‘I feel bad for
picking on you about your lateness, and I know it’s not your fault, but
it’s really annoying that you’re late again.’”
For the hundreds of thousands of couples getting married each June —
and for the millions of couples currently together, married or not — the
lesson from the research is clear: If you want to have a stable,
healthy relationship, exercise kindness early and often.
When people think about practicing kindness, they often think about
small acts of generosity, like buying each other little gifts or giving
one another back rubs every now and then. While those are great examples
of generosity, kindness can also be built into the very backbone of a
relationship through the way partners interact with each other on a
day-to-day basis, whether or not there are back rubs and chocolates
involved.
One way to practice kindness is by being generous about your
partner’s intentions. From the research of the Gottmans, we know that
disasters see negativity in their relationship even when it is not
there. An angry wife may assume, for example, that when her husband left
the toilet seat up, he was deliberately trying to annoy her. But he may
have just absent-mindedly forgotten to put the seat down.
Or say a wife is running late to dinner (again), and the husband
assumes that she doesn’t value him enough to show up to their date on
time after he took the trouble to make a reservation and leave work
early so that they could spend a romantic evening together. But it turns
out that the wife was running late because she stopped by a store to
pick him up a gift for their special night out.
Imagine her joining him for dinner, excited to deliver her gift, only
to realize that he’s in a sour mood because he misinterpreted what was
motivating her behavior. The ability to interpret your partner’s actions
and intentions charitably can soften the sharp edge of conflict.
“Even in relationships where people are frustrated, it’s almost
always the case that there are positive things going on and people
trying to do the right thing,” psychologist Ty Tashiro told me. “A lot of times, a partner is trying to do the right thing even if it’s executed poorly. So appreciate the intent.”
Another powerful kindness strategy revolves around shared joy. One of
the telltale signs of the disaster couples Gottman studied was their
inability to connect over each other’s good news. When one person in the
relationship shared the good news of, say, a promotion at work with
excitement, the other would respond with wooden disinterest by checking
his watch or shutting the conversation down with a comment like, “That’s
nice.”
We’ve all heard that partners should be there for each other when the going gets rough. But research shows that being there for each other when things go right is
actually more important for relationship quality. How someone responds
to a partner’s good news can have dramatic consequences for the
relationship.
In one study from 2006, psychological researcher Shelly Gable and her
colleagues brought young adult couples into the lab to discuss recent
positive events from their lives. They psychologists wanted to know how
partners would respond to each other’s good news. They found that, in
general, couples responded to each other’s good news in four different
ways that they called: passive destructive, active destructive, passive constructive, and active constructive.
Let’s say that one partner had recently received the excellent news
that she got into medical school. She would say something like “I got
into my top choice med school!”
If her partner responded in a passive destructive manner, he
would ignore the event. For example, he might say something like: “You
wouldn’t believe the great news I got yesterday! I won a free t-shirt!”
If her partner responded in a passive constructive way,
he would acknowledge the good news, but in a half-hearted, understated
way. A typical passive constructive response is saying “That’s great,
babe” as he texts his buddy on his phone.
In the third kind of response, active destructive, the
partner would diminish the good news his partner just got: “Are you sure
you can handle all the studying? And what about the cost? Med school is
so expensive!”
Finally, there’s active constructive responding. If her
partner responded in this way, he stopped what he was doing and engaged
wholeheartedly with her: “That’s great! Congratulations! When did you
find out? Did they call you? What classes will you take first semester?”
Among the four response styles, active constructive responding
is the kindest. While the other response styles are joy-killers, active
constructive responding allows the partner to savor her joy and gives
the couple an opportunity to bond over the good news. In the parlance of
the Gottmans, active constructive responding is a way of “turning
toward” your partners bid (sharing the good news) rather than “turning
away” from it.
Active constructive responding is critical for healthy relationships.
In the 2006 study, Gable and her colleagues followed up with the
couples two months later to see if they were still together. The
psychologists found that the only difference between the couples who
were together and those who broke up was active constructive responding.
Those who showed genuine interest in their partner’s joys were more
likely to be together. In an earlier study,
Gable found that active constructive responding was also associated
with higher relationship quality and more intimacy between partners.
There are many reasons why relationships fail, but if you look at
what drives the deterioration of many relationships, it’s often a
breakdown of kindness. As the normal stresses of a life together pile
up—with children, career, friend, in-laws, and other distractions
crowding out the time for romance and intimacy—couples may put less
effort into their relationship and let the petty grievances they hold
against one another tear them apart.
In most marriages, levels of satisfaction drop dramatically within
the first few years together. But among couples who not only endure, but
live happily together for years and years, the spirit of kindness and
generosity guides them forward.
Wednesday, November 12, 2014
Wednesday, October 22, 2014
Data Frame Column Vector
We reference a data frame column with the double square bracket "[[]]" operator.
For example, to retrieve the ninth column vector of the built-in data set mtcars, we write mtcars[[9]].
We can retrieve the same column vector by its name.
We can also retrieve with the "$" operator in lieu of the double square bracket operator.
Yet another way to retrieve the same column vector is to use the single square bracket "[]" operator. We prepend the column name with a comma character, which signals a wildcard match for the row position.
Sunday, September 21, 2014
It is not the will to win that counts, it is the will that prepare to win that makes the difference
If you want change the unsatisfied status quo, go and work for it, fight for the change, work hard to make it happen. Change will never be possible if you just sit there and think how much you want to change, you have to move out of the comfort zone and enduring the harsh of labor and the bitterness of fight.
Happiness, Respects, Securities and Successes are earned, you have to fight for it.
It is not the will to win that counts, it is the will that prepare to win that makes the difference.
Happiness, Respects, Securities and Successes are earned, you have to fight for it.
It is not the will to win that counts, it is the will that prepare to win that makes the difference.
Friday, September 19, 2014
txStart and txEnd
txStart, txEnd: These columns contain the start and end coordinates for
transcription of the gene.
cdsStart, cdsEnd: These columns contain the start and end coordinates for
the coding region of the gene.
transcription of the gene.
cdsStart, cdsEnd: These columns contain the start and end coordinates for
the coding region of the gene.
Tuesday, September 9, 2014
安全驾乘 幸福一生
又是开学季节,中国留学生陆续返校, 学校周边车行老板笑逐颜开, 因近年来中国学生购车代步已成普遍现象,而且购买豪车、 租车出游也越来越多。小编目睹了这几年中国留学生群体的变化, 也听闻不少中国留学生车祸惨案和相关案例,深有感触, 有几点驾乘经验在此分享。
小编希望所有人提高安全意识,安全驾乘,远离猛虎,幸福一生!
先考驾照再上路。6月初, 一名中国留学生无证醉酒超速驾驶发生严重车祸,送医急救, 虽生命无虞却留下身体残疾,还要面临危险驾驶等指控,教训惨痛。 考取驾照是一个学习驾驶的过程,期间需学习驾乘的法律法规, 掌握很多安全驾驶和处理应急情况的技巧。一般而言, 新手需要几个月的时间才可以通过法律法规测试和路考。 这几个月是一个熟悉车辆性能、掌握驾驶技巧、积累经验的过程。“ 十次车祸九次快”。但是新手对于车速的感觉往往不得要领, 需要长期积累才能形成。正如飞行员需要累积飞行小时一样, 驾驶汽车也需要累积驾驶里程, 建议新生到校后先考上驾照后再开车。
合理合规驾乘。某年春节前,麻州一留学生在纽约完成节目排练后, 深夜驾车返回波士顿。途中因疲劳驾驶致车毁人亡, 给家庭带来无尽伤痛。车祸往往都是因为麻痹大意和疏忽引发, 新手老手都需要有良好的交通安全意识,时刻警惕预防事故。 小编特别提醒大家:出行前检查车辆情况,规划好线路; 提前准备拐弯和并线,变换方向前要打转向灯;不超速, 不疲劳驾驶,不开夜车,不酒后驾驶。所有驾乘人员系好安全带, 以免发生意外时造成二次伤害。
租车有讲究。一中国留学生与朋友租车外出, 朋友小李未在租车合同上签字。途中小李驾驶时发生车祸, 租车公司向租车人要求高额赔偿。小编提醒: 租车时所有驾车人须向租车行申请并获认可,而且购买足额保险。
冷静处理事故及警察询问。高速路上发生一般事故及意外时, 应迅速打开应急灯,将车停靠路边, 在车后方100米架设反光三脚架警示后车, 然后迅速到路边安全地带等待救援和处理。 行驶途中如被警察要求靠边停车(Pull Over), 必须打开应急灯,缓慢靠路边应急道停车、熄火,然后掏出驾照, 将双手放在方向盘上,坐在车内等警察过来。 任何其他动作都会被视为威胁,警察可以采取暴力措施。 一中国女留学生因超速被警察追到路边停车后,下车找警察理论, 结果当即被捕并被拘留一晚。
人们常说:车祸猛于虎!人祸猛于虎!Monday, September 8, 2014
I am the lucky one cherish and fight
Heard the sad story from a friend fighting to find a job but can't, knowing that life here can be very very hard.
Cherish and Fight for my Happiness and American Dream.
Cherish and Fight for my Happiness and American Dream.
Monday, September 1, 2014
Install and Configure Apach
Download | $ lynx http://httpd.apache.org/download.cgi
|
Extract | $ gzip -d httpd-NN.tar.gz |
Configure | $ ./configure --prefix=PREFIX
|
Compile | $ make |
Install | $ make install |
Customize | $ vi PREFIX/conf/httpd.conf |
Test | $ sudo PREFIX/bin/apachectl -k start |
In many cases, the testing would have some problem mostly because people just forget the "sudo" .
Saturday, August 30, 2014
New Era of Self-Discipline
New Era of Self-Discipline starts now!
Monday, August 18, 2014
Persistence
Persistence is the common trait of anyone who has had a significant impact on the world.
坚持是世界上成功人士共有的品质。
如果在被银行拒绝了242次之后,霍华德-舒尔茨放弃了,就不会有星巴克;如果在被出版社拒绝了数年之后,J.K.罗琳放弃了,就不会有《哈利波特》;如果他的主题公园被否定了302次之后,华特·迪士尼放弃了,就不会有迪士尼乐园……嗯,像傻逼一样坚持,才会有牛逼的结果。
坚持是世界上成功人士共有的品质。
如果在被银行拒绝了242次之后,霍华德-舒尔茨放弃了,就不会有星巴克;如果在被出版社拒绝了数年之后,J.K.罗琳放弃了,就不会有《哈利波特》;如果他的主题公园被否定了302次之后,华特·迪士尼放弃了,就不会有迪士尼乐园……嗯,像傻逼一样坚持,才会有牛逼的结果。
Wednesday, August 13, 2014
Tuesday, August 12, 2014
B1/B2签证有效期和在美停留时间的问题
一、关于签证有效期
首先我们要知道当我们历经困难从签证官手里拿到自己的签证的时候,签证上面有个时间
这个我们叫做签证有效期。
B1/B2一般是一年多次往返的,这个只跟你申请的签证类型有关,与你填表的时候写的预计赴美时间和在美停留时间实际上关系不大!
当B1/B2签证被美国外交部批准,一般来说会是一年多次往返(visa上会注明multiple)。这个一年是指从签证获准之日起后的365天,都是签证有效期。
在这个有效期内,你有权选择任何日子来美,也可以放弃这项权利。
多次往返理论上讲可以是今天飞来美国,明天飞回中国,第三天又飞来美国,... ..., 直到签证过期。
二、关于在美停留时间或者又叫有效居留期,停留时间
当我们历尽千辛飞到美国的第一站后,首先要同美国国土安全部(不同于之前的美国外交部,他们工作独立,无权互相干涉)的官员会面,由他们来决定父母在美国的居留时间,也就是通常所说的过海关。这之后才是正真意义上的踏上了美国国土。
对于B1/B2签证,停留期最长不超过183天。绝大多数情况下(人权上和道义上),会给到这个上限,即使是父母在同一个签证有效期内多次来美国。另外这个居留到期日理论上可以比签证到期日还晚。
例如父母在签证到期日前一天到达美国,也可以获得183天的居留权。
美国国土安全部的官员会将I-94出入境记录卡附在父母的护照上,离境时必须归还此卡。
总结,在签证有效期内,想什么时候来美国就什么时候来,想来几回就来几回,如同走大路。而居留时间长短则由不得你,从0天(遣返)到183天不等,天知道,如果你对美国国土安全或美国国家利益构成威胁,往少了数数,否则,往大了数。
首先我们要知道当我们历经困难从签证官手里拿到自己的签证的时候,签证上面有个时间
这个我们叫做签证有效期。
B1/B2一般是一年多次往返的,这个只跟你申请的签证类型有关,与你填表的时候写的预计赴美时间和在美停留时间实际上关系不大!
当B1/B2签证被美国外交部批准,一般来说会是一年多次往返(visa上会注明multiple)。这个一年是指从签证获准之日起后的365天,都是签证有效期。
在这个有效期内,你有权选择任何日子来美,也可以放弃这项权利。
多次往返理论上讲可以是今天飞来美国,明天飞回中国,第三天又飞来美国,... ..., 直到签证过期。
二、关于在美停留时间或者又叫有效居留期,停留时间
当我们历尽千辛飞到美国的第一站后,首先要同美国国土安全部(不同于之前的美国外交部,他们工作独立,无权互相干涉)的官员会面,由他们来决定父母在美国的居留时间,也就是通常所说的过海关。这之后才是正真意义上的踏上了美国国土。
对于B1/B2签证,停留期最长不超过183天。绝大多数情况下(人权上和道义上),会给到这个上限,即使是父母在同一个签证有效期内多次来美国。另外这个居留到期日理论上可以比签证到期日还晚。
例如父母在签证到期日前一天到达美国,也可以获得183天的居留权。
美国国土安全部的官员会将I-94出入境记录卡附在父母的护照上,离境时必须归还此卡。
总结,在签证有效期内,想什么时候来美国就什么时候来,想来几回就来几回,如同走大路。而居留时间长短则由不得你,从0天(遣返)到183天不等,天知道,如果你对美国国土安全或美国国家利益构成威胁,往少了数数,否则,往大了数。
Thursday, August 7, 2014
Wednesday, August 6, 2014
Delete columns of data frame in R
> head(data)
chr genome region
1 chr1 hg19_refGene CDS
2 chr1 hg19_refGene exon
3 chr1 hg19_refGene CDS
4 chr1 hg19_refGene exon
5 chr1 hg19_refGene CDS
6 chr1 hg19_refGene exon
and I want to remove the 2nd column.E3Cfc<-E3Cfc[,!(names(E3Cfc)=="pk.bound")]
> Data$genome <- NULL
> head(Data)
chr region
1 chr1 CDS
2 chr1 exon
3 chr1 CDS
4 chr1 exon
5 chr1 CDS
6 chr1 exon
As pointed out in the comments, here are some other possibilities:Data[2] <- NULL # Wojciech Sobala
Data[[2]] <- NULL # same as above
Data <- Data[,-2] # Ian Fellows
Data <- Data[-2] # same as above
You can remove multiple columns via:Data[1:2] <- list(NULL) # Marek
Data[1:2] <- NULL # does not work!
Be careful with matrix-subsetting though, as you can end up with a vector:Data <- Data[,-(2:3)] # vector
Data <- Data[,-(2:3),drop=FALSE] # still a data.frame
Delete a list of elements from data frame in R
This might be an easy question but i still need some help for using R.
I have a data.frame (main_data), lets say..
I have a data.frame (main_data), lets say..
NAMES AGE LOC
Jyo 23 Hyd
Abid 27 Kar
Ras 24 Pun
Poo 25 Goa
Sus 28 Kar
I wish to remove a few rows based on a list of names. So lets say I have another list of table as follows:NAMES_list
Jyo
Ras
Poo
So based on this list, if any of the names match to my above
"main_data" table, then I would like to remove the whole row contianing
them, so the result should be as followsNAMES AGE LOC
Abid 27 Kar
Sus 28 Kar
Solution:
Use
%in% :
|
Monday, August 4, 2014
Resolve Problem in Installing RCurl
Resolve Problem in Installing RCurl, Problem stated as below.
> install.packages("RCurl")
Installing package into ‘/home/hufeng/R/x86_64-pc-linux-gnu-library/3.0’
(as ‘lib’ is unspecified)
trying URL 'http://cran.rstudio.com/src/contrib/RCurl_1.95-4.3.tar.gz'
Content type 'application/x-gzip' length 879143 bytes (858 Kb)
opened URL
==================================================
downloaded 858 Kb
* installing *source* package ‘RCurl’ ...
** package ‘RCurl’ successfully unpacked and MD5 sums checked
checking for curl-config... no
Cannot find curl-config
ERROR: configuration failed for package ‘RCurl’
* removing ‘/home/hufeng/R/x86_64-pc-linux-gnu-library/3.0/RCurl’
Warning in install.packages :
installation of package ‘RCurl’ had non-zero exit status
The downloaded source packages are in
‘/tmp/RtmpDnCukv/downloaded_packages’
I installed libcurl4-gnutls-dev and the problem was solved.
In your shell:
> install.packages("RCurl")
Installing package into ‘/home/hufeng/R/x86_64-pc-linux-gnu-library/3.0’
(as ‘lib’ is unspecified)
trying URL 'http://cran.rstudio.com/src/contrib/RCurl_1.95-4.3.tar.gz'
Content type 'application/x-gzip' length 879143 bytes (858 Kb)
opened URL
==================================================
downloaded 858 Kb
* installing *source* package ‘RCurl’ ...
** package ‘RCurl’ successfully unpacked and MD5 sums checked
checking for curl-config... no
Cannot find curl-config
ERROR: configuration failed for package ‘RCurl’
* removing ‘/home/hufeng/R/x86_64-pc-linux-gnu-library/3.0/RCurl’
Warning in install.packages :
installation of package ‘RCurl’ had non-zero exit status
The downloaded source packages are in
‘/tmp/RtmpDnCukv/downloaded_packages’
I installed libcurl4-gnutls-dev and the problem was solved.
In your shell:
sudo apt-get -y build-dep libcurl4-gnutls-dev
sudo apt-get -y install libcurl4-gnutls-dev
Sunday, August 3, 2014
R which Function
which(x, arr.ind = FALSE, useNames = TRUE)
arrayInd(ind, .dim, .dimnames = NULL, useNames = FALSE)
x
: logical vector or array. NAs are allowed and omitted (treated as if FALSE)arr.ind
: logical; should array indices be returned when x is an array?ind
: integer-valued index vector, as resulting from which(x).dim
: integer vector.dimnames
: optional list of character dimnames(.), of which only .dimnames[[1]] is useduseNames
: logical indicating if the value of arrayInd() should have (non-null) dimnames at all> BOD
Time demand 1 1 8.3 2 2 10.3 3 3 19.0 4 4 16.0 5 5 15.6 6 7 19.8
> which(BOD$demand == 16)
[1] 4
> x <- matrix(1:9,3,3) > x
[,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9
> which(x %% 3 == 0, arr.ind=TRUE)
row col [1,] 3 1 [2,] 3 2 [3,] 3 3
> which(x %% 3 == 0, arr.ind=FALSE)
[1] 3 6 9
The do.call function
R has an interesting function called do.call. This
function allows you to call any R function, but instead of writing
out the arguments one by one, you can use a list to hold the
arguments of the function. While it may not seem useful on the
surface, a simple example will help to show how powerful do.call
is.
Suppose we have three comma-separated text files that have information on the same three variables. Here's a look at the first few lines in one of the files:
Suppose we have three comma-separated text files that have information on the same three variables. Here's a look at the first few lines in one of the files:
a,b,x,y
b,B,2.49778634403711,-0.351307445767206
b,A,-0.594683138631719,1.19629936975021
b,D,1.14857619580259,0.653315728121014
c,A,0.957476532595248,0.935608419299617
It's easy to read each one in with
read.csv, and then to call the rbind (combine by
rows) function to make one big data frame. (Remember that rbind
will only work if all the data frames being combined have the same variable
names.)> one = read.csv('1.csv')
> nrow(one)
[1] 21
> two = read.csv('2.csv')
> nrow(two)
[1] 25
> three = read.csv('3.csv')
> nrow(three)
[1] 27
> big = rbind(one,two,three)
> nrow(big)
[1] 73
As I said, that was pretty easy. But now suppose we have
20 csv files that we want to read and combine. We could do what we
did with the three files, but, not only would it get tiring, there's
a chance of making an error when we have to type so many commands.
In the past, when we've had problems like this, sapply was able
to help. Let's try it here, by writing a function that will take a
number, create a filename by pasting .csv at the end, and reading
in the data:> allframes = sapply(1:20,function(x)read.csv(paste(x,'csv',sep='.')))
> head(allframes)
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
a factor,21 factor,25 factor,27 factor,25 factor,27 factor,21 factor,24
b factor,21 factor,25 factor,27 factor,25 factor,27 factor,21 factor,24
x Numeric,21 Numeric,25 Numeric,27 Numeric,25 Numeric,27 Numeric,21 Numeric,24
y Numeric,21 Numeric,25 Numeric,27 Numeric,25 Numeric,27 Numeric,21 Numeric,24
[,8] [,9] [,10] [,11] [,12] [,13] [,14]
a factor,28 factor,23 factor,23 factor,22 factor,26 factor,24 factor,23
b factor,28 factor,23 factor,23 factor,22 factor,26 factor,24 factor,23
x Numeric,28 Numeric,23 Numeric,23 Numeric,22 Numeric,26 Numeric,24 Numeric,23
There were no errors, but the result certainly is strange
looking! While we haven't talked about it before, the "s" in sapply
stands for simplify, and the problem that we've just seen is that
sapply tried too hard to simplify our result. It created an
odd matrix, where each element represents one of the columns of one of
the files we read in. Fortunately, there's a function that's closely related
to sapply called lapply. The difference between sapply and
lapply is that lapply will never try to simplify its
results. It will always return a list, the same length as its first
argument, with each element of the list resulting in the function we
passed to lapply operating on one element of the first argument.
In our case, calling lapply instead of sapply will give
us a list of length 20, where each element is the result of calling
read.csv on one of the 20 files. This is where do.call
comes in. Instead of having to pass 20 data frames to rbind, we
can use do.call to pass all 20 of them to rbind, since they
are in a list, and that's exactly what do.call is looking for.> allframes = lapply(1:20,function(x)read.csv(paste(x,'csv',sep='.')))
> sapply(allframes,nrow)
[1] 21 25 27 25 27 21 24 28 23 23 22 26 24 23 25 29 28 30 27 29
> answer = do.call(rbind,allframes)
> nrow(answer)
[1] 507
We can combine all the data frames without storing them
separately or passing them individually to rbind.
Difference between `=` and `<-` in R
- The operators <- and = assign into the environment in which they are evaluated.
- The operator <- can be used anywhere.
- The operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.
Thursday, July 31, 2014
Install Google Earth in Ubuntu 14.04 64bit
Install Google Earth (with the required 32bit
dependencies) in Ubuntu 14.04 (or 13.10) 64bit:
sudo apt-get install libfontconfig1:i386 libx11-6:i386 libxrender1:i386 \
libxext6:i386 libgl1-mesa-glx:i386 libglu1-mesa:i386 libglib2.0-0:i386 libsm6:i386
cd /tmp && wget http://dl.google.com/dl/earth/client/current/google-earth-stable_current_i386.deb
sudo dpkg -i google-earth-stable_current_i386.deb
sudo apt-get install -f
How to install Adobe Reader on Ubuntu
1. Download the DEB package:
2. Install Gdebi to handle the DEB package. Press Ctrl+Alt+T on keyboard to open the terminal. When it opens, paste the command below and run:
3. Now install the package via Gdebi. It’ll also install the dependencies.
4. Adobe Reader is still missing libraries after installation. Run the command below to install them:
2. Install Gdebi to handle the DEB package. Press Ctrl+Alt+T on keyboard to open the terminal. When it opens, paste the command below and run:
sudo apt-get install gdebi
3. Now install the package via Gdebi. It’ll also install the dependencies.
cd ~/Downloads && sudo gdebi AdbeRdr9.5.5-1_i386linux_enu.deb
sudo apt-get install libgtk2.0-0:i386 libnss3-1d:i386 libnspr4-0d:i386 lib32nss-mdns* libxml2:i386 libxslt1.1:i386 libstdc++6:i386
Tuesday, July 29, 2014
Form FastQ to FastA
awk 'NR % 4 == 1 {print ">" $0 } NR % 4 == 2 {print $0}' my.fastq > my.fasta
awk 'BEGIN{P=1}{if(P==1||P==2){gsub(/^[@]/,">");print}; if(P==4)P=0; P++}' Head-80k-ChIA-PET.fastq > Head-80k-ChIA-PET.fasta
awk 'BEGIN{P=1}{if(P==1||P==2){gsub(/^[@]/,">");print}; if(P==4)P=0; P++}' Head-80k-ChIA-PET.fastq > Head-80k-ChIA-PET.fasta
Sunday, July 27, 2014
Crises
The crises I am facing are real, they are serious and they are many, they can not be solved easily or in a short span of time, but I have never been more confident than today that I will solve them.
Saturday, July 26, 2014
宝宝最近辛苦了
今天宝宝忙了一整天,宝宝为了我能专心忙自己的事情,她做家务劳累到头晕,下午那么热的天气还帮我收拾房间,做饭。知道自己累的不行,躺在床上休息了好长时间才缓过来。昨天晚上宝宝为了给我做黑椒牛柳,一直忙到晚上10点多,周五的晚上啊,宝宝也是累的不行。宝宝本来身体虚弱,但是为了我能专心科研,专心申请绿卡,宝宝真的在全力以赴的支持我。
最近有太多值得我一辈子铭记的感动。
我到现在还记得我拔牙的那天晚上,天气非常非常热,宝宝回来就已经热的受不了了,但是把我送到空调卧室休息后,她自己盯着湿热的天气给我煮粥,直到我睡了一觉醒来,发现宝宝满头大汗的在炉子旁边,身上的衣服都汗湿了。
无论什么时候我都要记得,宝宝是我需要用一辈子好好疼爱,好好回报的女人。宝宝谢谢你,谢谢你为我付出这么多,我爱你。
Happiness
Happiness is someone to love, something to do, and something to hope for.
Friday, July 25, 2014
You Deserve Better
Cherish what you have now, and always remember, you deserve better.
ubuntu下安装谷歌拼音输入法(ibus)
下面简单介绍下怎么在ubuntu下安装谷歌拼音输入法(ibus)。
一、安装依赖包
sudo apt-get install cmake build-essential opencc mercurial ibus
hg clone http://code.google.com/p/libgooglepinyin.ibus-wrapper/ ibus-googlepinyin
cd ibus-googlepinyin
mkdir build; cd build
cmake .. -DCMAKE_INSTALL_PREFIX=/usr
make
sudo make install
pkill -f ibus-daemon ; ibus-daemon -d -x
ibus-setup
Monday, July 21, 2014
Easiest way to install Oracle Java on Ubuntu.
Easiest way to install Oracle Java on Ubuntu.
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer
Sunday, July 13, 2014
爱体现在很多方面
我觉得自己对老婆不够好,很多方面需要改进。
尤其是自己最近的外观,真的非常非常差劲。
爱体现在很多方面,让老婆无时无刻不体会到我的爱。
尤其是自己最近的外观,真的非常非常差劲。
爱体现在很多方面,让老婆无时无刻不体会到我的爱。
Monday, July 7, 2014
Mass Law on High Beams
High Beams in Darkness
- High beam headlights allow you to see more than three times as far as ordinary headlights. Massachusetts law requires that you only use your high beams in dark or remote areas where it is difficult or impossible to see the road otherwise. When driving in fog, you are required to use your low beams rather than your high beams as high beams will reflect back at you and further reduce your driving vision.
High Beams and Other Drivers
- Massachusetts law stipulates that you must lower your high beams when you are within 500 feet of an oncoming driver. You must also dim your brights within 350 feet of cars moving in the same direction, from people or other "substantial" objects, or inside a Massachusetts Turnpike tunnel. You may remind an oncoming driver to dim his high beams by briefly flicking your own brights on and off.
"Dangerous or Dazzling Light"
- The Massachusetts Complaint Manual, Chapter 540, Section 22.05, cites as a violation the fact that a driver failed to "dim the headlamps of such vehicle so that no dangerous or dazzling light [is] measured 75 feet or more ahead of the lamps." This is true for those super-bright aftermarket Halogen lights, even if they're not used as high beams. Also illegal are flashing lights that may cause others to mistake your car for a police vehicle.
Penalties
- Generally, the fine for a first high beam offense is $35. A second offense is $75, and a third is $150. Be aware that, according to Massachusetts traffic law, any offense involving "improper use of headlights" is subject to a fine.
Dim High Beams
We start off with the basic question: Is it ever illegal to use your high-beam headlights?
Indeed, it is.
The Code of Massachusetts Regulations, Chapter 540, Section 22, "Failure to Dim," says you must flick off your high beams when you're within 500 feet of a car approaching in the opposite direction -- a considerable distance.
You're also supposed to kill your high beams whenever "substantial" objects, such as other cars or people, are visible within a distance of 350 feet, or whenever you're in a Massachusetts Turnpike Authority tunnel.
"The operator shall regulate the headlamps so that no dangerous or dazzling light shall" shine, the law says.
The general fine is $35 for a first offense, $75 for a second, and $150 for a third, though the oncoming car rule doesn't apply to cars traveling on divided highways, said Lieutenant Dana Pagley, commander of the State Police traffic program section.
23 Photos Of Animals And Their Parents That Will Melt Your Heart.
23.
22.
21.
20.
19.
18.
17.
16.
15,
14.
13.
12.
11.
10.
9.
8.
7.
6.
5.
4.
3.
2.
1.
God help those who help themselves.
God help those who help themselves.
天助自助者。
Dr. Zhou's paper has been rated as highly accessed.
Dr. Zhou's paper has been rated as highly accessed.
Please access the paper at, http://www.biologydirect.com/content/9/1/5
Please access the paper at, http://www.biologydirect.com/content/9/1/5
Saturday, July 5, 2014
Learning C from Java
This is a list of differences between Java and C, and assumes that the reader knows less about the latter. It's worth familiarising yourself with all the points, even if you don't fully understand them, then you may be aware of the cause of any problem you might encounter.
Many features of C, particularly its standard library facilities, are not dealt with in any great depth, since you can look those up in help files or manual pages, or a good reference book.
Item 39:
Item 40: Pointers to
Item 41:
Item 47:
Many features of C, particularly its standard library facilities, are not dealt with in any great depth, since you can look those up in help files or manual pages, or a good reference book.
- Item 1: Portability
- Item 2: Ease of development
- Item 3: Speed
- Item 4: Primitive types
- Item 5: Comments
- Item 6: Limited encapsulation
- Item 7: Structures instead of classes
- Item 8: Enumerations
- Item 9: Unions
- Item 10: Single namespace for functions and global variables
- Item 11: Lack of function name overloading
- Item 12: Type aliasing
- Item 13: Declarations and definitions
- Item 14: Functions and their prototypes
- Item 15: Global objects
- Item 16: Local objects
- Item 17: Scope
- Item 18: Empty parameter lists
- Item 19: Program modularity
- Item 20: Preprocessing
- Item 21: File inclusion
- Item 22: Macros
- Item 23: Conditional compilation
- Item 24: Pointers instead of references
- Item 25: Pointer types
- Item 26: Null and undefined pointers
- Item 27: Dangling pointers
- Item 28: Passing arguments by reference
- Item 29: Pointers to structures and unions
- Item 30: Pointers to functions
- Item 31: Pointers to pointers
- Item 32: Generic pointers
- Item 33: Arrays and pointer arithmetic
- Item 34: Initialising arrays
- Item 35: Array-pointer relationship
- Item 36: Passing arrays to functions
- Item 37: Array length
- Item 38: Arrays as function parameters
- Item 39:
const
instead offinal
- Item 40: Pointers to
const
objects - Item 41:
const
pointers - Item 42: Inline functions
- Item 43: Characters and strings
- Item 44: Wide characters
- Item 45: Dynamic memory management
- Item 46: Lack of exceptions
- Item 47:
main()
function - Item 48: Standard library facilities
Item 1: Portability
Java source and binaries are entirely portable, since the source format is standardized, and the binaries run on a software emulation of a standardized processor (JVM).
In C, binaries are not usually portable from one platform to another, because they use the platform's native hardware processor directly. However, C source can be portable with little modification if it adheres to an ISO C standard, e.g., C90 (ISO/IEC 9899:1990), C95 (ISO/IEC 9899:1995), C99 (ISO/IEC 9899:1999) or C11 (ISO/IEC 9899:2011) so long as the additional libraries it uses are also portable.
In C, binaries are not usually portable from one platform to another, because they use the platform's native hardware processor directly. However, C source can be portable with little modification if it adheres to an ISO C standard, e.g., C90 (ISO/IEC 9899:1990), C95 (ISO/IEC 9899:1995), C99 (ISO/IEC 9899:1999) or C11 (ISO/IEC 9899:2011) so long as the additional libraries it uses are also portable.
Related topics
- Item 2: Ease of development
- Item 3: Speed
Item 2: Ease of development
Java is a very safe language, in that when you do something wrong, you get a relatively clear indication of what you did. If you attempt to access beyond the bounds of an array, or do anything else wrong, you get an immediate and diagnostic failure. If you lose all references to an object, it gets cleaned up by the garbage collector. There's no way to attempt to access inaccessible or unallocated memory.
Not so with C. A C program will happily access beyond the bounds of an array, possibly resulting in an immediate crash of the program (with little hint of where it was when it happened), no effect, or a delayed effect, as corrupted data is only detected later when accessed. Dynamic memory management is under manual control, and if you forget to deallocate something, the memory is wasted until reclaimed when the program exits. It's also very easy to deallocate memory, but continue to use it accidentally, again with unpredictable results.
In C, these activities require greater responsibility from the programmer.
Not so with C. A C program will happily access beyond the bounds of an array, possibly resulting in an immediate crash of the program (with little hint of where it was when it happened), no effect, or a delayed effect, as corrupted data is only detected later when accessed. Dynamic memory management is under manual control, and if you forget to deallocate something, the memory is wasted until reclaimed when the program exits. It's also very easy to deallocate memory, but continue to use it accidentally, again with unpredictable results.
In C, these activities require greater responsibility from the programmer.
Related topics
- Item 1: Portability
- Item 3: Speed
Item 3: Speed
C is usually a compiled language, i.e., a compiler translates it into the native machine code of a specific target platform, so that platform's hardware processor can interpret it directly, yielding a considerable speed advantage. Java is also compiled, but its target platform is a virtual machine, the JVM, and it must be interpreted by an emulation of that machine, which itself will be a native machine-code program running on the physical processor.
One would therefore expect Java programs to be slower than C programs, and that was probably true when Java first appeared. However, modern JVMs take several steps to improve execution speed:
So, is C still faster than Java? It depends so much on things like program longevity and the type of activity, that there's no simple answer, and you will choose a language based on other needs.
One would therefore expect Java programs to be slower than C programs, and that was probably true when Java first appeared. However, modern JVMs take several steps to improve execution speed:
- Java bytecode can be converted to native code by the JVM. Not all code is converted, but the JVM will try to identify the most used pieces of code.
- The JVM can also in-line methods dynamically.
- The JVM can be careful about loading only parts of the (rather large) standard library that are actually used.
So, is C still faster than Java? It depends so much on things like program longevity and the type of activity, that there's no simple answer, and you will choose a language based on other needs.
Related topics
- Item 1: Portability
- Item 2: Ease of development
Item 4: Primitive types
In C, the primitive types are referred to using a combination of the keywords
Note also that there is no boolean type. Instead, the test conditions of
In C99, there is a boolean type
char
, int
, float
, double
, signed
,unsigned
, long
, short
and void
. The allowable combinations are listed below, but their meanings depend on the compiler and platform in use, unlike Java.unsigned char
- The narrowest unsigned integral type, typically (and always at least) 8 bits wide
signed char
- The narrowest signed integral type, of the same width as
unsigned char
char
- An integral type equivalent to one or other of the signed/unsigned variants, but its signedness is implementation-dependent — C treats it as a distinct type, though.
unsigned short
- An unsigned integral type at least as wide as
unsigned char
, typically (and always at least) 16 bits short
- A signed integral type of the same width as
unsigned short
unsigned
- An unsigned integral type at least as wide as
unsigned short
, and wider than thechar
types — 16- or 32-bit widths are common. int
- A signed integral type of the same size as
unsigned
unsigned long
- An unsigned integral type at least as wide as
unsigned
, typically (and always at least) 32 bits long
- A signed integral type of the same size as
unsigned long
unsigned long long
- In C99, an unsigned integral type at least as wide as
unsigned long
, typically (and always at least) 64 bits long long
- In C99, a signed integral type of the same size as
unsigned long long
float
- A single-precision floating-point type
double
- A double-precision floating-point type
long double
- An extended double-precision floating-point type
void
- An empty type — It has no values, and cannot be accessed. As in Java, C functions with no return value are defined to return
void
. Unlike Java, a function with no parameters hasvoid
in its parameter list.
int
(for example) means the same as a Java int
. Furthermore, C's signed types do not have to use two's-complement notation, and Java does not have unsigned types.Note also that there is no boolean type. Instead, the test conditions of
if
, while
and for
statements, and the operands of the logical operators (!
, &&
and ||
), are integer expressions with a boolean interpretation: zero means false, non-zero means true. The relational operators (==
, !=
, <=
, >=
, <
and >
) and logical operators return 0
for false and 1
for true.In C99, there is a boolean type
bool
(which is really just a very small integer type) and symbolic values true
and false
(i.e. just 1 and 0), but the other integer types work just as well as before.Item 5: Comments
Java allows the use of these forms of comment:
In both C and Java, you might disable large sections of temporarily unwanted code by using comments, although that can be problematic because comments do not nest. However, as C uses a preprocessor [Item 20], it has a more robust method:
/* a multiline comment */ // a single-line commentPrior to C99, C does not permit the single-line form.
In both C and Java, you might disable large sections of temporarily unwanted code by using comments, although that can be problematic because comments do not nest. However, as C uses a preprocessor [Item 20], it has a more robust method:
/* enabled code */ #if 0 /* disabled code */ #endif /* enabled code */
Item 6: Limited encapsulation
Languages like Java and C++ were developed out of C to support (i.a.) better encapsulation and information hiding. C only provides very basic support, and otherwise expects enough discipline from the programmer to avoid breaking any intended encapsulation.
There are no classes [Item 7] and no packages [Item 10] in C, so there is nothing for C functions to belong to, and they must be carefully named to avoid clashes. C structures [Item 7] encapulate several data as a unit, but do not restrict access, so there is no abstraction.
The use of [Item 21] and separate modules [Item 19] can provide some hiding of internals. An empty structure type might be used in the published header, while its full declaration would appear in the only source file that needed it, or in an unpublished header if needed by several. Functions and globals local to a module can be hidden from other modules with
Here's a fairly robust template for abstract types in C. First, write a header declaring (say) a type for a handle to access a very simple database:
Now write a source file to complete the structure type, and define the functions:
There are no classes [Item 7] and no packages [Item 10] in C, so there is nothing for C functions to belong to, and they must be carefully named to avoid clashes. C structures [Item 7] encapulate several data as a unit, but do not restrict access, so there is no abstraction.
The use of [Item 21] and separate modules [Item 19] can provide some hiding of internals. An empty structure type might be used in the published header, while its full declaration would appear in the only source file that needed it, or in an unpublished header if needed by several. Functions and globals local to a module can be hidden from other modules with
static
.Here's a fairly robust template for abstract types in C. First, write a header declaring (say) a type for a handle to access a very simple database:
/* file db.h */ #ifndef db_included #define db_included /* pointer to incomplete structure type */ typedef struct db_handle *dbref; /* a constructor */ dbref db_open(const char *addr); /* methods */ int db_get(dbref, const char *key); /* etc */ /* a destructor */ void db_close(dbref); #endifNote that C does not have any notion of ‘constructor’ or ‘method’. They are just ordinary functions alike.
Now write a source file to complete the structure type, and define the functions:
/* file db.c */ /* Include the header, so we ensure that our definitions and declarations are consistent. */ #include "db.h" struct db_handle { /* . . . */ }; /* UseAs a result, the internal structure of your database handle can change over time without affecting its users, as they can't see inside it. The functions declared withstatic
for internal state and private functions... */ static void normalize_key(char *to, const char *from) { /* . . . */ } dbref db_open(const char *addr) { /* Allocate astruct db_handle
, and initialize it... */ } int db_get(dbref db, const char *key) { /* Use info indb
to access an entry... */ } void db_close(dbref) { /* Release memory... */ }
static
are not visible outside db.c, so they won't clash with identically named functions in other parts of the program. However, the compiler will not force a user of your library to initialize a dbref
correctly with db_open
, or to release it after use correctly with db_close
. He is expected to have enough self-discipline to do that himself.Further reading
- Item 7: Structures instead of classes
- Item 10: Single namespace for functions and global variables
- Item 11: Lack of function name overloading
Item 7: Structures instead of classes
C does not allow you to declare class types (as you can in Java using the
Members of a C structure are accessed using the
class
construct), but you can declare C structures using the struct
construct. A C structure is like a Java class that only contains public data members — there must be no functions, and all parts are visible to any code that knows the declaration. For example:struct point { int x, y; };This declares a type called
struct point
(NB: ‘struct
’ is part of the name; point
is known as the structure type's tag).Members of a C structure are accessed using the
.
operator, as class members can be in Java:struct point location; location.x = 10; location.y = 13;A structure object may be initialised where it is defined:
struct point location = { 10, 13 }; /* okay; initialisation (part of definition) */ location = { 4, 5 }; /* illegal; assignment (not part of definition) */In C99, you can create anonymous structure objects to perform compound assignement:
location = (struct point) { 4, 5 }; /* legal in C99 */
In C99, a structure initialisation can specify which members are being set:struct point location = { .y = 13, .x = 10 }; /* legal in C99 */
Unlike Java, where class variables are references to objects, C structure variables are the objects themselves. Assigning one to another causes copying of the members:struct point a = { 1, 2 }; struct point b; b = a; /* copiesa.x
tob.x
, anda.y
tob.y
*/ b.x = 10; /* does not affecta.x
*/
Background
- Item 6: Limited encapsulation
Item 8: Enumerations
An enumeration is a range of (usually) distinct symbolic constants.
Until Java 1.5, an enumeration was simply an informal grouping of static final variables:
Java 1.5 introduced a specific concept for enumerations:
C has a concept with a similar syntax, but with semantics rather more like static finals:
The first symbol is assigned the value
If a new type is not required, the tag can be omitted:
C
Until Java 1.5, an enumeration was simply an informal grouping of static final variables:
public static final int RED = 0; public static final int REDAMBER = 1; public static final int GREEN = 2; public static final int AMBER = 3;(Java also has a class
java.util.Enumeration
, which serves a different, unrelated purpose.)Java 1.5 introduced a specific concept for enumerations:
public enum LightState { RED, REDAMBER, GREEN, AMBER }These are distinct instances of a class type, and don't correspond to integer values (apart from their order).
C has a concept with a similar syntax, but with semantics rather more like static finals:
enum light { RED, REDAMBER, GREEN, AMBER };This defines a new type
enum light
, and defines the symbols RED
for 0
, REDAMBER
for 1
, GREEN
for 2
, and AMBER
for 3
.The first symbol is assigned the value
0
, and each subsequent symbol is assigned the next integer. However, a symbol can be assigned a particular value:enum light { RED = 3, REDAMBER, GREEN = 1, AMBER };This also implies that
REDAMBER
is 4
, and that AMBER
is 2
.If a new type is not required, the tag can be omitted:
enum { RED, REDAMBER, GREEN, AMBER };The symbols can be used in any expression, and may be assigned to any integral type, not just the
enum
type. For this reason, the tag is rarely used.C
enum
s are no more sophisticated than that. In contrast to Java, the symbols are not objects, and cannot take parameters.Item 9: Unions
C allows an area of memory to be occupied by data of several types, though only one at a time, using a union. Unions are syntactically similar to structures:
Members of a C union are accessed using the
union number { char c; int i; float f; double d; };This declares a type called
union number
(NB: ‘union
’ is part of the name; number
is known as the union's tag).Members of a C union are accessed using the
.
operator, just as structure members are accessed:union number n; int j; n.i = 10; j = n.i;Only the member to which a value was last assigned contains valid information to be read. There is no way to determine that member implicitly, so the programmer must take steps to identify it, for example, by using a separate variable to indicate the type:
union number n; enum { CHAR, INT, FLOAT, DOUBLE } nt; n.i = 10; nt = INT; switch (nt) { case CHAR: /* accessJava does not have unions, although it is possible for a reference to refer to any class derived from its own class. A reference of typen.c
*/ break; case INT: /* accessn.i
*/ break; case FLOAT: /* accessn.f
*/ break; case DOUBLE: /* accessn.d
*/ break; }
java.lang.Object
can refer to any class of object, since all classes are originally derived fromjava.lang.Object
.Item 10: Single namespace for functions and global variables
Each class in Java defines a namespace which allows functions and variables in separate, unrelated classes to share the same name. When identifying a function or variable in Java, the namespace must be expressed, or implied using an
In C, all functions are global, and must share a single namespace (i.e. one per program). Global variables can also be declared and defined, and they also share that namespace. Care must be taken in choosing names for functions in large projects, and often a strategy of using a common prefix for groups of related functions is employed. For example,
Note that other namespaces exist in a C progam: a single namespace is shared by the tags of all structures, unions and enumerations; each structure and union holds a unique namespace for its members; each block statement holds a namespace for local variables.
import
directive. For example, the method java.lang.Integer.toString()
is distinct from java.lang.Long.toString()
. Java packages similarly allow distinct classes and interfaces to share the same name. For example, the name Object
could refer to either java.lang.Object
or org.omg.CORBA.Object
.In C, all functions are global, and must share a single namespace (i.e. one per program). Global variables can also be declared and defined, and they also share that namespace. Care must be taken in choosing names for functions in large projects, and often a strategy of using a common prefix for groups of related functions is employed. For example,
WSA
prefixes most of the WinSock functions.Note that other namespaces exist in a C progam: a single namespace is shared by the tags of all structures, unions and enumerations; each structure and union holds a unique namespace for its members; each block statement holds a namespace for local variables.
Background
- Item 6: Limited encapsulation
Item 11: Lack of function name overloading
In Java, two functions in the same namespace may share the same name if their parameter types are sufficiently different. In C, this is simply not the case, and all function names must be unique.
void myfunc(int a)
{
/* ... */
}
void myfunc(float b) /* error: myfunc
already defined */
{
/* ... */
}
Background
- Item 6: Limited encapsulation
Item 12: Type aliasing
New names or aliases for existing types may be created using
Note that a
There is no equivalent of type aliasing in Java.
typedef
. For example:typedef int int32_t;This allows
int32_t
to be used anywhere in place of int
. Such aliases are often used to hide implementation- or platform-specific details, or to allow the choice of a widely-used type to be changed easily.typedef
s are also useful for expressing complex compound types. For example, a prototype for the standard-library function signal
has the following, rather cryptic form (in ISO C):void (*signal(int signum, void (*handler)(int)))(int);Erm, what? It becomes a little clearer when POSIX (an Operating System standard which incorporates the C standard) declares it:
typedef void (*sighandler_t)(int); sighandler_t signal(int signum, sighandler_t handler);Now we can see that the function's second parameter has the same type as its return value, and that that type is, in fact, a pointer-to-function type.
Note that a
typedef
is syntactically similar to a variable declaration, with the new type name appearing in the place of the variable name.There is no equivalent of type aliasing in Java.
Item 13: Declarations and definitions
C programs are built from collections of functions (which have behaviour) and objects (which have values; variables are objects), the natures of which are indicated by their types. C compilers read through source files sequentially, looking for names of types, objects and functions being referred to by other types, objects and functions.
A declaration of a type, object or function tells the compiler that a name exists and how it may be used, and so may be referred to later in the file. If the compiler encounters a name that does not have a preceding declaration, it may generate an error or a warning because it does not understand how the name is to be used.
In contrast, a Java compiler can look forward or back, or even into other source files, to find definitions for referenced names.
A definition of an object or function tells the compiler which module the object or function is in (see Program modularity [Item 19]). For an object, the definition may also indicate its initial value. For a function, the definition gives the function's behaviour.
A declaration of a type, object or function tells the compiler that a name exists and how it may be used, and so may be referred to later in the file. If the compiler encounters a name that does not have a preceding declaration, it may generate an error or a warning because it does not understand how the name is to be used.
In contrast, a Java compiler can look forward or back, or even into other source files, to find definitions for referenced names.
A definition of an object or function tells the compiler which module the object or function is in (see Program modularity [Item 19]). For an object, the definition may also indicate its initial value. For a function, the definition gives the function's behaviour.
Further reading
- Item 14: Functions and their prototypes
- Item 15: Global objects
- Item 16: Local objects
- Item 17: Scope
Item 14: Functions and their prototypes
In Java, the use of a function may appear earlier than its definition. In C, all functions being used in a source file EM(should) be declared somewhere earlier than their invocations in that file, allowing the compiler to check if the call's arguments match the function's formal parameters. A function declaration (or prototype) looks like a function definition, but its body (the code between and including the braces (‘
{
’ and ‘}
’)) is replaced by a semicolon (syntactically similar to anative
method, or an interface method, in Java). If the compiler finds a function invocation before any declaration, it will try to infer a declaration from the invocation, and this may not match the true definition. A proper declaration can be inferred from a function definition, should that be encountered first./* a declaration; parameter names may be omitted */
int power(int base, int exponent);
/* From here until the end of the file, we can make calls to power()
,
even though the definition hasn't been encountered. */
/* a definition; parameter names do not need to match declaration */
int power(int b, int e)
{
int r = 1;
while (e-- > 0)
r *= b;
return r;
}
Background
- Item 13: Declarations and definitions
Item 15: Global objects
Global objects also have distinct declarative and definitive forms. A definition may be accompanied by an initialiser, e.g.:
int globval = 34; /* initialized */ int another; /* initialized with 0 */…while a declaration should not have an initialiser, and should be preceded by
extern
:extern int globval; extern int another;(
extern
can also appear before a function declaration, but it is optional.)Background
- Item 13: Declarations and definitions
Item 16: Local objects
For local objects in C, the definition and declaration are not distinguished. Unlike Java, all local variables must be defined at the beginning of their enclosing block, before any statements are reached. This restriction does not apply in C99.
{ int x; /* a definition */ x = 10; /* a statement */ int y; /* illegal; follows a statement */ }Furthermore, an iteration variable in a
for
loop cannot be declared within the initialisation of the statement:{ for (int x = 0; x < 10; x++) { /* illegal */ /* ... */ } }This restriction does not apply in C99.
Background
- Item 13: Declarations and definitions
Item 17: Scope
All declarations have scope, which is the part of the program in which the declared name has the meaning it is declared to have. ‘File scope’ means from the declaration to the end of the file, and applies to types, functions and global objects.
‘Block scope’ means from the declaration to the end of the block statement in which it is declared. This always applies to local objects (including formal parameters), but can also apply to types, functions and global objects. All of the following declarations have block scope, and can be used by the trailing statements, but not by statements beyond the block:
‘Block scope’ means from the declaration to the end of the block statement in which it is declared. This always applies to local objects (including formal parameters), but can also apply to types, functions and global objects. All of the following declarations have block scope, and can be used by the trailing statements, but not by statements beyond the block:
{ /* a local type */ typedef int MyInteger; /* a local variable */ MyInteger x; /* global variable */ extern int y; /* function (CODE(extern) is implicit) */ int power(int base, int exponent); /* statements... */ }Unlike Java, a local variable in an inner block may hide one in an outer block by having the same name:
{ int x; { int x; /* hides the other */ } /* first one visible again */ }
Background
- Item 13: Declarations and definitions
Item 18: Empty parameter lists
In Java, a function that takes no arguments is expressed using
()
. In C, such a function should be expressed with (void)
in its declaration and definition. However, it is still invoked with ()
:/* prototype/declaration */ int myfunc(void); /* definition */ int myfunc(void) { /* ... */ } /* invocation */ myfunc();The form
()
is permitted in declarations, but it means ‘unspecified arguments’ rather than ‘no arguments’. This tells the compiler to abandon type-checking of arguments where that function is invoked. It comes from an obsolete pre-standard version of C, and is not recommended.Item 19: Program modularity
Java programs, particularly large ones, are usually built in a modular fashion that supports code re-use. The source code is spread over several source files (.java), and is used to generate Java byte-code in class files (.class) which are identified by the class they represent, so in Java, there is a direct relationship between the name of a class and the file containing the code for that class. These are combined at run-time to produce the executing program. Java's standard library of utilities for file access, GUIs, internationalisation, etc, is a practical example of such modular programming.
A large C program may also be split into several source files (usually with a .c extension), and separate compilation of each of these produces an object file of (usually) the same name with a different extension (.o or .obj). These are the modules of C that can be combined to form an executable program. An object file contains named representations of the functions and global data defined in its source file, and allows them to refer to other functions and data by name, even if in a separate module. In C, there doesn't have to be any relationship between the names of functions and variables and the names of the modules that contain them.
A final executable program is produced by supplying all the relevant modules (as object files) to a linker (which is often built into the compiler). This attempts to resolve all the referred names into the memory addresses required by the generated machine code, and linking will fail if some names cannot be resolved, or if there are two representations of the same name.
For example, the object file generated from the code below would contain references to the names pow (because it is invoked as a function) and errno (because it is accessed as a global variable). The file would also provide a representation of the name func (because the source contains a definition of that function).
Other pre-compiled libraries may also exist (e.g. to support sockets), but it will normally be necessary to link with them explicitly to use them.
Here is an illustration of a program built from several components:
The source code consists of four source files (foo.c, bar.c, baz.c, quux.c) and three header files for preprocessing ("yan.h", "tan.h", "tither.h"; see File inclusion [Item 21]). The program also uses some header files (<wibble.h>,<wobble.h>) from an additional library. Compiling each of the source files in turn generates the object files foo.o, bar.o,baz.o, quux.o, and these are linked with an archive of pre-compiled objects (libwubble.a) from the library to produce an executable program myprog.
A large C program may also be split into several source files (usually with a .c extension), and separate compilation of each of these produces an object file of (usually) the same name with a different extension (.o or .obj). These are the modules of C that can be combined to form an executable program. An object file contains named representations of the functions and global data defined in its source file, and allows them to refer to other functions and data by name, even if in a separate module. In C, there doesn't have to be any relationship between the names of functions and variables and the names of the modules that contain them.
A final executable program is produced by supplying all the relevant modules (as object files) to a linker (which is often built into the compiler). This attempts to resolve all the referred names into the memory addresses required by the generated machine code, and linking will fail if some names cannot be resolved, or if there are two representations of the same name.
For example, the object file generated from the code below would contain references to the names pow (because it is invoked as a function) and errno (because it is accessed as a global variable). The file would also provide a representation of the name func (because the source contains a definition of that function).
extern int errno;
void func(void)
{
double pow(double, double);
double x = 3.0, y = 12.7, r;
int e;
r = pow(x, y);
e = errno;
/* ... */
}
Like Java, C comes with a standard library of general-purpose support routines, an implementation of which is supplied with your compiler. Its source code is not usually required, since it has already been compiled into object files for your system, and these will be used automatically when linking.Other pre-compiled libraries may also exist (e.g. to support sockets), but it will normally be necessary to link with them explicitly to use them.
Here is an illustration of a program built from several components:
Item 20: Preprocessing
Each C source file undergoes a lexical preprocessing stage which serves several purposes, including conditional compilation and macro expansion. The main purpose is to allow declarations of commonly used types, global data and functions to be conveniently and consistently made available to modules which need to access them. In general, the preprocessor is able to insert, remove or replace text from the source code as it is supplied to the compiler. (The original source code doesn't change.)
There is no equivalent of preprocessing in Java, but its purposes don't usually apply to Java anyway.
There is no equivalent of preprocessing in Java, but its purposes don't usually apply to Java anyway.
Further reading
- Item 21: File inclusion
- Item 22: Macros
- Item 23: Conditional compilation
Item 21: File inclusion
When a large C program is split over several modules, code in one module might need to make references to named code in another, or two modules might need to refer to the same type declaration consistently. The usual way to achieve these is to precede the reference with a declaration that shows what the name means. Some example declarations:
Header files containing declarations for the standard library are also available to the preprocessor. These are normally accessed with a variant of the
Do not put definitions of functions or variables in header files — it may result in multiple definitions of the same name within one program, so linking will fail. Header files should normally only contain types, function prototypes, variable declarations, and macro definitions. Note that inline functions [Item 42] are exceptional.
/* This declares the typeIt would be tedious to repeat such declarations in each source file that requires them, particularly if they need to be modified as the program develops. Instead, these could be placed in a separate file (usually with a .h extension), and inserted automatically by the preprocessor when it encounters anstruct point
. */ struct point { int x, y; }; /* This declares the global variableerrno
. */ extern int errno; /* this declares the functiongetchar
. */ int getchar(void);
#include
directive embedded in the source code, for example:#include "mydecls.h"These header files are also preprocessed, and so may contain further
#include
(or other) directives.Header files containing declarations for the standard library are also available to the preprocessor. These are normally accessed with a variant of the
#include
directive:/* Include declarations for input/output routines. */
#include <stdio.h>
You should normally use the ""
form for your own headers rather than <>
.Do not put definitions of functions or variables in header files — it may result in multiple definitions of the same name within one program, so linking will fail. Header files should normally only contain types, function prototypes, variable declarations, and macro definitions. Note that inline functions [Item 42] are exceptional.
Background
- Item 20: Preprocessing
Item 22: Macros
The preprocessor allows macros to be defined which serve a number of purposes:
- Some macros are used to hold constants or expressions:
#define PI 3.14159 double pi_twice = PI * 2;
PI
will be replaced by the numeric value wherever it is used. - Some macros take arguments:
#define MAX(A,B) ((A) > (B) ? (A) : (B))
…that provide a convenient way to emulate functions without the overhead of a real function call. (See a good book on C for the limitations of this.) - Some macros are merely defined to exist:
#define JOB_DONE
…and are used in conditional compilation [Item 23].
Background
- Item 20: Preprocessing
Item 23: Conditional compilation
The preprocessor allows code to be compiled selectively, depending on some condition. For example, if we assume that the macro
__unix__
is defined only when compiling for a UNIX system, and that the macro __windows__
is defined only when compiling for a Windows system, then we could provide a single piece of code containing two possible implementations depending on the intended target:int file_exists(const char *name) { #if defined(__unix__) /* Use UNIX system calls to find out if the file exists. */ #elif defined(__windows__) /* Use Windows system calls to find out if the file exists. */ #else /* Don't know what to do - abort compilation. */ #error "No implementation for your platform." #endif }The most common use of conditional compilation, though, is to prevent the declarations in a header file from being made more than once, should the file be inadvertently
#include
d more than once:/* in the file mydecls.h */
#if !defined(mydecls_header)
#define mydecls_header
typedef int myInteger;
#endif
You should routinely protect all your header files in this way.Background
- Item 20: Preprocessing
Item 24: Pointers instead of references
All variables of non-primitive types in Java are references. C has no concept of ‘reference’, but instead has pointers, which Java does not. They are similar, but you can do much more with pointers, with a correspondingly greater risk of mistakes.
A pointer is an address in memory of some ordinary data. A variable may be of pointer type, i.e. it holds the address of some data in memory.
The
A pointer is an address in memory of some ordinary data. A variable may be of pointer type, i.e. it holds the address of some data in memory.
/* We'll assume we're inside some block statement, as in a function. */ int i, j; /*i
andj
are integer variables. */ int *ip; /*ip
is a variable which can point to an integer variable. */ i = 10; j = 20; /* values assigned */ ip = &i; /*ip
points toi
. */ *ip = 5; /* Indirectly assign5
toi
. */ ip = &j; /*ip
points toj
. */ *ip += 7; /*j
now contains27
. */ i += *ip; /*i
now contains32
. */
&
operator obtains the address of a variable. (The syntax ensures that there is no conflict with the bit-wise ‘and’ operator.) The *
operator dereferences the pointer. (Again, the syntax ensures that there is no conflict with the multiplication operator.) A dereferenced pointer can be used on the left-hand side of an assignment, i.e. it is a modifiable lvalue (SQ(el-value)), as in the two examples above.Further reading
- Item 25: Pointer types
- Item 26: Null and undefined pointers
- Item 27: Dangling pointers
- Item 28: Passing arguments by reference
- Item 29: Pointers to structures and unions
- Item 30: Pointers to functions
- Item 31: Pointers to pointers
- Item 32: Generic pointers
Item 25: Pointer types
For every type, there is a pointer type. Since there is an
But
int
type, there is also a pointer-to-int
type, written int *
.float *
is the pointer-to-float
type. When assigning a pointer value to a variable, or comparing two pointer values, the types must match. Given these declarations:int i, j; float f; int *ip; float *fp;…then
i
is of type int
, so the expression &i
must be of type int *
.ip
is also of type int *
, so you can assign &i
to it. &j
is of type int *
, so it can be compared with &i
, and so on.But
&f
is of type float *
, so it cannot be assigned to ip
, or compared with ip
, &i
or &j
.Background
- Item 24: Pointers instead of references
Item 26: Null and undefined pointers
A valid value for a pointer is null (it equals
It is permissible to use pointers as integer expressions treated as boolean expressions to detect a null pointer. (Null means ‘false’ in this context). For example:
If a pointer variable has not been given a value, it could be pointing anywhere, or be null. Do not dereference such an undefined pointer.
0
), indicating that it points to no object. Do not dereference a null pointer.Many of the standard header files define a macro for a null pointer, NULL
, which many programmers may prefer.#include <stdlib.h> int *ip; ip = NULL;
int *ip; if (ip) { /* CODE(ip) is not null. */ } if (!ip) { /* CODE(ip) is null. */ }Direct comparisons are also possible (e.g.
ip != NULL
).If a pointer variable has not been given a value, it could be pointing anywhere, or be null. Do not dereference such an undefined pointer.
Background
- Item 24: Pointers instead of references
Item 27: Dangling pointers
In Java, an object will remain in existence so long as there is a reference to it. In C, an object may go out of existence even if there are pointers to it — the programmer is entirely responsible for ensuring that pointers contain valid addresses (either
0
, or the address of an existing object) when used. This badly written function returns a pointer to an integer variable:int *badfunc(void)
{
int x = 18;
return &x; /* Bad - x
won't exist after the call has finished. */
}
The pointer returned by badfunc()
is invalid.Background
- Item 24: Pointers instead of references
Item 28: Passing arguments by reference
In Java, all primitive types are passed to functions by value — the function is unable to change values of variables in the invoking context. All class types are passed by reference — the function can alter the public contents of the referenced object.
In C, almost all types are passed by value, and so no variables supplied as arguments can be altered by a function. It can only alter its local copies of the variables. However, by passing a pointer to the variable, the function is able to dereference its copy of the pointer, and indirectly assign to the variable. Consider these two functions which are intended to swap the values of two variables:
In C, almost all types are passed by value, and so no variables supplied as arguments can be altered by a function. It can only alter its local copies of the variables. However, by passing a pointer to the variable, the function is able to dereference its copy of the pointer, and indirectly assign to the variable. Consider these two functions which are intended to swap the values of two variables:
void badswap(int a, int b) { int tmp = b; b = a; a = tmp; /*This reports:a
andb
are swapped but they're only copies. */ } void goodswap(int *ap, int *bp) { int tmp = *bp; *bp = *ap; *ap = tmp; } /* Assume we're in a function body. */ int x = 10, y = 4; /* Print state of variables. */ printf("1: x = %d y = %d ", x, y); badswap(x, y); /*x
andy
are copied, and the copies are swapped sox
andy
are unchanged. */ printf("2: x = %d y = %d ", x, y); goodswap(&x, &y); /* Pointers tellgoodswap()
where we storex
andy
. */ printf("3: x = %d y = %d ", x, y);
1: x = 10 y = 4 2: x = 10 y = 4 3: x = 4 y = 10…indicating that
badswap
had no effect on the variables given as arguments.Background
- Item 24: Pointers instead of references
Item 29: Pointers to structures and unions
A pointer to a variable of structure type may exist. Accessing a member of the structure is straight-forward: dereference the pointer, and apply the
.
operator. However, the syntax requires parentheses to ensure the correct meaning, but a short form also exists (and is widely used) for convenience:struct point loc;
struct point *locp = &loc;
(*locp).x = 10; /* correct */
*locp.x = 10; /* incorrect; same as *(locp.x)
*/
locp->x = 10; /* correct, shorter form */
Syntactically, pointers to unions are accessed identically.Background
- Item 24: Pointers instead of references
Item 30: Pointers to functions
Functions also have addresses, for which there are pointer-to-function types expressing the parameters and return type. The pointers can be passed to or returned from other functions just as other data can.
void goodswap(int *, int *); void (*swapfunc)(int *, int *); /* a pointer calledSince pointers to functions are just values like any other, they can be passed to and returned from functions, so that ‘behaviour’ itself becomes just another form of data.swapfunc
*/ int x, y; swapfunc = &goodswap; /* Now it points to a function with matching parameters. */ (*swapfunc)(&x, &y); /* Invokesgoodswap(&x, &y)
. */
Background
- Item 24: Pointers instead of references
Item 31: Pointers to pointers
A pointer may point to variable which itself holds another pointer, and this is expressed in the pointer's type:
int i; /*The fact that the pointed-to object also holds a pointer does not fundamentally change the behaviour of the pointer that points to it. It just allows a further level of indirection — in practice, you rarely need more than a couple of levels.i
holds an integer. */ int *ip = &i; /*ip
points toi
. */ int **ipp = &ip; /*ipp
points toip
. */ int ***ippp = &ipp; /*ippp
points toipp
. */ /* et cetera */
Background
- Item 24: Pointers instead of references
Item 32: Generic pointers
It is sometimes necessary to store or pass pointers without knowing what type they point to. For this, you can use the generic pointer type
void *
. You can convert between the generic pointer type and other pointer types (except pointer-to-function types) whenever you need to:int x; int *xp, *yp; void *vp; xp = &x; vp = xp; Types are compatible. later... yp = vp; Types are compatible.A generic pointer cannot be dereferenced, nor can pointer arithmetic [Item 33] be applied to it.
x = *vp; /* error: cannot dereferenceThe generic pointer type simply allows you to tell the compiler that you're taking responsibility for a pointer's interpretation, and so no error messages or warnings are to be reported when assigning. It is the programmer's responsibility to ensure that the pointer value is interpreted as the correct type.void *
*/ vp++; /* error: cannot do arithmetic onvoid *
*/
int *ip; float *fp; void *vp; fp = ip; /* error: incompatible types */ vp = ip; /* okay */ fp = vp; /* no compiler error, but is misuse */Generic pointers are used with dynamic memory management [Item 45], among other things.
Background
- Item 24: Pointers instead of references
Item 33: Arrays and pointer arithmetic
Arrays in Java are object types whose elements are accessed only by integer offset. In C, arrays are groups of variables of the same type guaranteed to be in adjacent memory. Allocation for dynamic arrays is handled by the programmer. An array of integers may look like this:
int array[10]; /* numbered 0
to 9
*/
int i = 6;
array[3] = 12;
array[i] = 13;
Further reading
- Item 34: Initialising arrays
- Item 35: Array-pointer relationship
- Item 36: Passing arrays to functions
- Item 37: Array length
- Item 38: Arrays as function parameters
Item 34: Initialising arrays
Arrays may be initialised when defined:
In C99, you can specify which elements of an array are initialised:
int myArray[4] = { 9, 8, 7, 6 };The size is optional in this case, since the compiler sees that there are four elements in the initialiser. The initialiser must not be bigger than the size if specified, but it can be smaller. Either way, the size must be known at compile time — it can not be an expression in terms of the values of other objects or function calls. In C99, this restriction does not exist.
In C99, you can specify which elements of an array are initialised:
int myArray[4] = { [2] = 7, [0] = 9, [1] = 8, [3] = 6 };
Background
- Item 33: Arrays and pointer arithmetic
Item 35: Array-pointer relationship
The address of an array element can be taken, and simple arithmetic can be applied to it. Adding one to the address makes it point to the next element in the array. Subtracting one instead makes it point to the previous element.
By definition,
int myArray[4] = { 9, 8, 7, 6 }; int *aep = &myArray[2]; int x, i; *(aep + 1) = 2; /* SetmyArray[3]
to2
. */ *(aep - 1) += 11; /* SetmyArray[1]
to19
. */ x = *(aep - 2); /* Setx
to9
. */
*(aep + i)
is equivalent to aep[i]
, and in many contexts, an array name such as myArray
evaluates to the address of the first element, which is how expressions such as myArray[2]
work (it becomes *(myArray + 2)
). The code above could be written as:int myArray[4] = { 9, 8, 7, 6 }; int *aep = &myArray[2]; int x, i; aep[1] = 2; /* SetNote that an array name such asmyArray[3]
to2
. */ aep[-1] += 11; /* SetmyArray[1]
to19
. */ x = aep[-2]; /* Setx
to9
. */
myArray
can not be made to point elsewhere:int myArray[4]; int i; int *ip; ip = myArray; /* Okay:myArray
is a legal expression;ip
now points tomyArray[0]
. */ myArray = &i; /* Error:myArray
is not a variable. */
Background
- Item 33: Arrays and pointer arithmetic
Item 36: Passing arrays to functions
Arrays are effectively passed to functions by reference. The array name evaluates to a pointer to the first element, so the function's parameter has a type of ‘pointer-to-element-type’. For example, given the function:
Note that the programmer must take steps to indicate the length of the array, in this case by defining the function to take a length argument. (An alternative would be to identify a special value within the array to mark its end.) The second call only has elements 2 to 8 set (an array of length 7).
void fill_array_with_square_numbers(int *first, int length) { int i; for (i = 0; i < length; i++) first[i] = i * i; }…we could write code such as:
int squares[4], moresquares[10]; void fill_array_with_square_numbers(int *first, int length); fill_array_with_square_numbers(squares, 4); fill_array_with_square_numbers(moresquares + 2, 7);The second call only fills part of the array
moresquares
.Background
- Item 33: Arrays and pointer arithmetic
Item 37: Array length
If the declaration of an array is visible, one can find its length by dividing its total size by the size of one element:
However, this technique doesn't work if the argument to
int squares[4]; int len = sizeof squares / sizeof squares[0];Because
squares
above is the name of an array, we can obtain its length using sizeof squares
, which yields the total size as a number of char
s. sizeof squares[0]
yields the size (in char
s) of one element, and since all the elements are of the same size, the ratio of these two sizeof
s is the number of elements in the array:void fill_array_with_square_numbers(int *first, int length); int squares[4]; fill_array_with_square_numbers(squares, sizeof squares / sizeof squares[0]);(For arrays of
char
s, the divisor can be omitted, since sizeof(char)
is defined to be 1
.)However, this technique doesn't work if the argument to
sizeof
is only a pointer that happens to point to an element of an array, rather than an array name. Consider that such a pointer looks identical to a pointer to a single object, as far as the compiler is concerned — they don't contain any information about the length. This is why the example function above requires the length as a separate argument: within the function, sizeof first
would only give the size of a pointer to an integer, not the length of the array.Background
- Item 33: Arrays and pointer arithmetic
Item 38: Arrays as function parameters
Note that a function parameter of array type isn't treated as an array, but as a pointer. (The array syntax is allowed, but only pointer semantics are implemented.) The following two declarations are equivalent:
void fill_array_with_square_numbers(int *first, int length); void fill_array_with_square_numbers(int first, int length);Within the definition of this function,
sizeof first
will still equal sizeof(int *)
, even if we place a length inside the square brackets (such a value is ignored anyway).Background
- Item 33: Arrays and pointer arithmetic
Item 39: const
instead of final
Java uses the keyword
final
to indicate ‘variables’ which can only be assigned to once (usually where they are declared). C uses the keyword const
with an object declaration to indicate a constant object that can (and must) be initialised, but cannot subsequently be assigned to — it is not a variable, but it still has an address and a size, so you can write &obj
orsizeof obj
.double sin(double); /* mathematical function sine */ const double pi = 3.14159; double val; val = sin(pi); /* legal expression */ pi = 3.0; /* illegal; not a modifiable lvalue */
Further reading
- Item 40: Pointers to
const
objects - Item 41:
const
pointers
Item 40: Pointers to const
objects
const
is useful when declaring functions that take pointers or arrays as arguments, but do not modify the dereferenced contents:int sum(const int *ar, int len) { int s = 0, i; for (i = 0; i < len; i++) s += ar[i]; return s; } int array[] = { 1, 2, 4, 5 }; int total = sum(array, 4);The
const
assures the caller that the invocation will not attempt to assign to *array
(or array[1]
, array[2]
, etc), even though the elements of array
are modifiable in other contexts.Background
- Item 39:
const
instead offinal
Item 41: const
pointers
Pointers themselves can be declared
const
just like other objects. In these cases, the pointer can't be made to point elsewhere, but does not prevent modification of what it points. Careful positioning of the keyword const
is required to distinguish constant pointers from pointers to constants:int array = { 1, 2, 4, 5 }; int *ip = array; /* a pointer to an integer */ int *const ipc = array; /* a constant pointer to an integer */ const int *const icpc = array; /* a constant pointer to a constant integer */ ipc[0] = ipc[1] + ipc[2]; /* okay */ ip += 2; /* okay */ ipc += 1; /* wrong; pointer is constant */ icpc[1] += 4; /* wrong; pointed-to object is constant */This example shows a modifiable array whose members are being accessed through four pointers with slightly different types.
Background
- Item 39:
const
instead offinal
Item 42: Inline functions
C99 supports inline functions. The programmer can indicate to the compiler that a function's speed is critical by marking it
Inline function definitions can (and often should) appear in header files [Item 21] instead of their prototypes [Item 14]. A normal (‘external’) definition must still be provided — for example, some part of your program may try to obtain a pointer [Item 30] to the function, and only a normal definition can provide that.
If the inline definition is in scope, an equivalent external definition can be generated from it by simply re-declaring the function with
Java doesn't have explicit inline functions, but virtual machines are permitted to inline functions automatically at runtime.
inline
:inline int square(int x) { return x * x; }If this definition is in scope, and you make a call to it, the compiler may choose not to translate the C call into a machine-code call, but instead replace it with a copy of the function, thus avoiding the overhead of true call.
Inline function definitions can (and often should) appear in header files [Item 21] instead of their prototypes [Item 14]. A normal (‘external’) definition must still be provided — for example, some part of your program may try to obtain a pointer [Item 30] to the function, and only a normal definition can provide that.
If the inline definition is in scope, an equivalent external definition can be generated from it by simply re-declaring the function with
extern
:extern int square(int x);If the inline definition isn't in scope, you could provide a normal definition which doesn't actually match the inline definition — but this could lead to confusing behaviour.
Java doesn't have explicit inline functions, but virtual machines are permitted to inline functions automatically at runtime.
Item 43: Characters and strings
A Java variable of type
Java strings are objects of class
Strings in C are just arrays of, or pointers to,
Utilities for handling character strings are declared in
char
can hold any 16-bit Unicode character. In C, the char
type can represent any character in a character set that depends on the type of system or platform for which the program is compiled. This is usually a variation of US ASCII, but it doesn't have to be, so beware. In particular, it could be a multibyte encoding, where a larger set of characters are represented by several char
objects, e.g. UTF-8. A basic set of characters, however, are always represented as single char
s.Java strings are objects of class
LINK_javadoc(java/lang/String.html,java.lang.String)
orLINK_javadoc(java/lang/StringBuilder.html,java.lang.StringBuilder)
, and represent sequences of char
.Strings in C are just arrays of, or pointers to,
char
, and don't exist as a formal type. Functions which handle strings typically assume that the string is terminated with a null character '\0'
, rather than being passed length parameter. A character array can be initialised like other arrays:char word[] = { 'H', 'e', 'l', 'l', 'o', '!', '\0' }; char another[] = "Hello!";Note that the second initialiser is a shorter form of the first, including the terminating null character. Such a string literal can also appear in an expression. It evaluates to a pointer to the first character.
const char *ptr; ptr = "Hello!";
ptr
now points to an anonymous, statically allocated array of characters. Attempting to write to a string literal like this has undefined behaviour, so the use of const
ensures that such attempts are detected while compiling.Utilities for handling character strings are declared in
<string.h>
. For example, the function to copy a string from one place to another is declared as:char *strcpy(char *to, const char *from);…and may be used like this:
#include <string.h> char words[100]; strcpy(words, "Madam, I'm Adam.");Like many of the other
<string.h>
functions, strcpy
assumes that you have already allocated sufficient space to store the string.Further reading
- Item 44: Wide characters
Item 45: Dynamic memory management
Dynamic memory management is built into Java through its
You can find out the amount of memory needed to store an object of a particular type using
new
keyword and its garbage collector. In C, it is available through two functions in <stdlib.h>
which are declared as:void *malloc(size_t s); /* Reserve memory for(s
char
s. */ void free(void *); /* Release memory reserved withmalloc()
. */
size_t
is an alias for an unsigned integral type.)malloc(s)
returns a pointer to the start of a block of memory big enough for s char
s. It returns a generic pointer which can be assigned to a pointer variable of any type. The memory is not initialised. All such allocated memory must be released when it is no longer required, by passing a pointer to its start to free()
. Only pointer values returned by malloc()
can be passed to free()
.You can find out the amount of memory needed to store an object of a particular type using
sizeof(type)
. For an array, multiply this by the number of elements required in the array.long *lp; long *lap; lp = malloc(sizeof(long)); lap = malloc(sizeof(long) * 10); /* Now we can access*lp
as a long integer, andlap[0]
..lap[9]
form an array. */ free(lap); free(lp); /* Now we can't. */
malloc()
returns a null pointer (0
) if it cannot allocate the requested amount of memory.Item 46: Lack of exceptions
Java supports exceptions to cover application-defined mistakes as well as more serious system or memory-access errors, such as accessing beyond the bounds of an array.
In C, application-defined error conditions are normally expressed through careful definition of the meaning of values returned by functions. More serious errors, such as an attempt to access memory that hasn't been allocated in some way, may go unnoticed, because the behaviour is undefined. Write-access to such memory may cause corruption of critical hidden data, which only results in an error at a later stage, so the original cause of the error may be difficult to trace. Just because some activity is illegal in C, it doesn't mean that you will necessarily be told about it when you do it, either by the compiler or by the running program.
In C, application-defined error conditions are normally expressed through careful definition of the meaning of values returned by functions. More serious errors, such as an attempt to access memory that hasn't been allocated in some way, may go unnoticed, because the behaviour is undefined. Write-access to such memory may cause corruption of critical hidden data, which only results in an error at a later stage, so the original cause of the error may be difficult to trace. Just because some activity is illegal in C, it doesn't mean that you will necessarily be told about it when you do it, either by the compiler or by the running program.
Item 47: main()
function
In a Java application, execution begins in a static method (
void main(String[])
) of a specified class. In C, execution also begins at a function called main
, but it has the following prototype:int main(int argc, char **argv);The parameters represent an array of character strings that form the command that ran the program.
argv[0]
is usually the name of the program, argv[1]
is the first argument, argv[2]
is the second, …, argv[argc - 1]
is the last, andargv[argc]
is a null pointer. For example, the command:myprog wibbly wobbly…may cause
main
to be invoked as if by:char a1[] = "myprog"; char a2[] = "wibbly"; char a3[] = "wobbly"; char *argv[4] = { a1, a2, a3, NULL }; main(3, argv);The parameters are optional (you can replace them with a single
void
), but main
always returns int
in any portable program. Returning 0
tells the environment that the program completed successfully. Other values (implementation-defined) indicate some sort of failure. <stdlib.h>
defines the macros EXIT_SUCCESS
and EXIT_FAILURE
as symbolic return codes.Item 48: Standard library facilities
Java comes with a rich and still-developing set of classes to support I/O, networking, GUIs, etc, to access a process's environment.
Similarly, the C language has a core of facilities to access its environment. These functions, types and macros form C's Standard Library. However, it is necessarily limited in order to support maximum portability. Here are some obvious omissions:
The headers of the C Standard Library are briefly summarised below:
Similarly, the C language has a core of facilities to access its environment. These functions, types and macros form C's Standard Library. However, it is necessarily limited in order to support maximum portability. Here are some obvious omissions:
- GUI
- Networking
- Collections and containers
- Multithreading (but added in C11)
The headers of the C Standard Library are briefly summarised below:
<stddef.h>
- Some essential macros and additional type declarations
<stdlib.h>
- Access to environment; dynamic memory allocation; miscellaneous utilities
<stdio.h>
- Streamed input and output of characters
<string.h>
- String handling
<ctype.h>
- Classification of characters (upper/lower case, alphabetic/numeric etc)
<limits.h>
- Implementation-defined limits for integral types
<float.h>
- Implementation-defined limits for floating-point types
<math.h>
- Mathematical functions
<assert.h>
- Diagnostic utilities
<errno.h>
- Error identification
<locale.h>
- Regional/national variations in character sets, time formats, etc
<stdarg.h>
- Support for functions with variable numbers of arguments
<time.h>
- Representations of time, and clock access
<signal.h>
- Handling of exceptional run-time events
<setjmp.h>
- Restoration of execution to a previous state
<iso646.h>
- Alphabetic names for operators
<wchar.h>
- Manipulation of wide-character streams and strings
<wctype.h>
- Classification of wide characters (upper/lower case, alphabetic/numeric etc)
<stdbool.h>
- The boolean type and constants
<complex.h>
- The complex types and constants
<inttypes.h>
<stdint.h>
- Integer types of specific or minimum widths
<fenv.h>
- Access to the floating-point environment
<tgmath.h>
- Type-generic mathematics functions
Subscribe to:
Posts (Atom)