由买买提看人间百态

topics

全部话题 - 话题: char
首页 上页 1 2 3 4 5 6 7 8 9 10 下页 末页 (共10页)
g*****1
发帖数: 998
1
来自主题: JobHunting版 - 请教一道c/c++题 (转载)
【 以下文字转载自 Programming 讨论区 】
发信人: guagua1 (), 信区: Programming
标 题: 请教一道c/c++题
发信站: BBS 未名空间站 (Fri Jan 27 22:47:12 2012, 美东)
char *m()
{
char str[50];
strcpy(str,"how are you");
return str;
}
int main()
{
char s[50];
strcpy(s,m());
printf("%s",s);
//cin.get();
return 0;
}
为什么结果可以正确输出呢?我知道return by pointer可以make copy,可是return之
后storage不是free了吗?
另外,为什么下面这个就只能由一部分正确输出?
char *m()
{
char str[20];
strcpy(str,"how are you");
return str;
}
int main()
{

printf("%s",m());
//cin.get();... 阅读全帖
z*****n
发帖数: 447
2
来自主题: JobHunting版 - 最新某公司onsite面试题
const char* p;
p is a regular pointer pointing to a const char. You cannot change the
content (*p), but can change p to point another const char.
char* const p;
char const* p;
These two are identical. p is a const pointer pointing to char. You can
change (*p), but you cannot change p to point to another char.
f*******t
发帖数: 7549
3
来自主题: JobHunting版 - amazon面试题目讨论贴2
#include
#include
#include
#define ENTRYNOTFOUND 0
#define ENTRYFOUND 1
#define NOTCOMPLETE 2
struct Trie;
void FindWords(Trie *root);
struct Trie
{
Trie();
~Trie();
Trie *children[26];
bool isEnd;
};
Trie::Trie()
{
for(int i = 0; i < 26; i++)
children[i] = NULL;
isEnd = false;
}
Trie::~Trie()
{
for(int i = 0; i < 26; i++) {
if(children[i]) {
delete children[i];
children[i] = NULL;
}
}
}
... 阅读全帖
h*****g
发帖数: 312
4
来自主题: JobHunting版 - 攒人品之facebook电面面经
写了一个,有错误请指正~~
//copy on write
class String
{
private:
char *str;
int len;
public:
String():str(0),len(0)
{

}
String(char *p)
{
len=strlen(p);
char *tm=new char(len+2);
memset(tm,0,len+2);
str=tm+1;
strncpy(str,p,len+1);
}
String(const String &ms)
{
len=ms.len;
str=ms.str;
++(str[-1]);
}
Strin... 阅读全帖
h*****g
发帖数: 312
5
来自主题: JobHunting版 - 攒人品之facebook电面面经
写了一个,有错误请指正~~
//copy on write
class String
{
private:
char *str;
int len;
public:
String():str(0),len(0)
{

}
String(char *p)
{
len=strlen(p);
char *tm=new char(len+2);
memset(tm,0,len+2);
str=tm+1;
strncpy(str,p,len+1);
}
String(const String &ms)
{
len=ms.len;
str=ms.str;
++(str[-1]);
}
Strin... 阅读全帖
c**********e
发帖数: 2007
6
这个Strategy design pattern的例子为什么人为得弄得这么复杂?
#include
#include
#include
using namespace std;
class Strategy;
class TestBed
{
public:
enum StrategyType
{
Dummy, Left, Right, Center
};
TestBed()
{
strategy_ = NULL;
}
void setStrategy(int type, int width);
void doIt();
private:
Strategy *strategy_;
};
class Strategy
{
public:
Strategy(int width): width_(width){}
void format()
{
char line[80], wo... 阅读全帖
w****x
发帖数: 2483
7
来自主题: JobHunting版 - 说好得FG面经,回馈板上GGJJ
//Print strings with certain prefix in a sorted string array
void GetIndex(const char* strs[], int nBeg, int nEnd, char chr, int nPos,
OUT int& index1, int& index2);
void PrintComPrefix(const char* strs[], int n, const char* szPre)
{
assert(strs && szPre && n > 0);
const char* p = szPre;
int nIndex1 = 0;
int nIndex2 = n-1;
while (*p != 0 && nIndex1 >= 0)
{
GetIndex(strs, nIndex1, nIndex2, *p, p-szPre, nIndex1, nIndex2);
p++;
}
if (nIndex1 >= 0 ... 阅读全帖
w****x
发帖数: 2483
8
//Print strings with certain prefix in a sorted string array
void GetIndex(const char* strs[], int nBeg, int nEnd, char chr, int nPos,
OUT int& index1, int& index2);
void PrintComPrefix(const char* strs[], int n, const char* szPre)
{
assert(strs && szPre && n > 0);
const char* p = szPre;
int nIndex1 = 0;
int nIndex2 = n-1;
while (*p != 0 && nIndex1 >= 0)
{
GetIndex(strs, nIndex1, nIndex2, *p, p-szPre, nIndex1, nIndex2);
p++;
}
if (nIndex1 >= 0 ... 阅读全帖
D********g
发帖数: 650
9
来自主题: JobHunting版 - 贡献一道G家的面试题
我的code:
先扫一遍找到A的个数和B的个数
然后再扫一遍处理A
再扫一遍处理B
code里处理A和B的算法不太一样,第二种更好一点。另外,有没有包子?
/*input is assumed to end at '\0' and input is assumed to be long enough to
hold the
* transformed string
* */
static char[] deleteADoubleB(final char[] input) {
if (input == null || input.length == 0) {
return input;
}
int aCount = 0, bCount = 0, originalLen = 0;
for (int i = 0; i < input.length; ++i) {
if (input[i] == 'A') {
aCount ... 阅读全帖
w****x
发帖数: 2483
10
来自主题: JobHunting版 - 发几个面试题
/*
Serialize/DeSerialize a tree
*/
struct NODE
{
int nVal;
vector vec;
NODE(int n) : nVal(n) {}
};
void _inner_serial(NODE* pNode, char*& p)
{
if (NULL == pNode)
return;
*p++ = pNode->vec.size();
*p++ = pNode->nVal;
for (vector::iterator it = pNode->vec.begin();
it != pNode->vec.end(); it++)
_inner_serial(*it, p);
}
const char* Serialize(NODE* pRoot, char mem[])
{
if (NULL == mem || NULL == pRoot)
return NULL;
char... 阅读全帖
l****c
发帖数: 838
11
来自主题: JobHunting版 - C的fscanf的问题 (转载)
You should read in the string and parse.
You don't know how long the first part string is or how long the number is.
So if you define:
char tempprice[10];
char ticker[10];
You have the risk of buffer overflow.
Here is my solution. I debug it as I wrote it, so it is not optimized.
it is pure C. You can get result with 2 lines of perl or python code
============================
#include
#include
#include
int main()
{
char *str = "GOOD|89.34";
char *ptoken, *... 阅读全帖
w****x
发帖数: 2483
12
来自主题: JobHunting版 - 刚才重新回顾了一下那题
struct NODE
{
vector vecGUID;
NODE* nodes[256];

NODE() { memset(nodes, 0, sizeof(nodes)); }
};
void _inner_get_guid(NODE* pNode, const char* str, int k, vector& vec)
{
if (NULL == pNode)
return;
if (k <= 0)
{
vec = pNode->vecGUID;
return;
}
_inner_get_guid(pNode->nodes[*str], str+1, k-1, vec);
}
vector getGUID(const char* str, NODE* pRoot, int k)
{
vector vecRet;
if (NULL == pRoot || NULL == str || *str == 0 ... 阅读全帖
w****x
发帖数: 2483
13
来自主题: JobHunting版 - 上一道我以前喜欢出的题目吧

const char* getNum(const char* q, int& res)
{
const char* p = q;
if (NULL == p) return NULL;
res = 0;
while (*p != '.' && *p != 0)
res = 10*res + *p++ - '0';
if (*p == '.') p++;
return p;
}
bool lessThan(const char* str1, const char* str2)
{
if (NULL == str1 || NULL == str2)
return false;
const char* p1 = str1;
const char* p2 = str2;
while (*p1 != 0 && *p2 != 0)
{
int x,y;
p1 = getNum(p1, x);
p2 = getNum(p2, y);... 阅读全帖
k***g
发帖数: 58
14
来自主题: JobHunting版 - 50行code能解决addbinary 问题么
贴个我的
public String addBinary(String a, String b) {
char[] ca = a.toCharArray();
char[] cb = b.toCharArray();
char[] c = new char[Math.max(ca.length, cb.length)];

int i=ca.length-1, j=cb.length-1, k=c.length-1;
int carry = 0;
while (i>=0 && j>=0) {
int x = ca[i--]-'0';
int y = cb[j--]-'0';
c[k--] = (char) (x^y^carry + '0');
carry = x&y | x&carry | y&carry;
}

while (i>=0) {
int x = ca[i--]-'0';
c[k--] =... 阅读全帖
Q*******e
发帖数: 939
15
来自主题: JobHunting版 - 50行code能解决addbinary 问题么
翻译成C.
void
addBinary(char *arr1, char *arr2)
{
int i,j;
int len1 = 0, len2 = 0, len3;
char tmp, carry=0;
char *arrR;
char *arrT1 = arr1;
char *arrT2 = arr2;
while (*arrT1++) len1++;
while (*arrT2++) len2++;
len3 = (len1 > len2) ? len1 : len2;
arrR = (char*) malloc(len3 + 2);
len1--; len2--;
len3 = 0;
while ((len1>=0) || (len2>=0) || carry) {
tmp = carry;
if (len1 >= 0) tmp += (arr1[len1--] - '0');
if (len2 >= 0) tmp += (... 阅读全帖
w****x
发帖数: 2483
16
/*
Serialize/DeSerialize a tree
*/
struct NODE
{
int nVal;
vector vec;
NODE(int n) : nVal(n) {}
};
void _inner_serial(NODE* pNode, char*& p)
{
if (NULL == pNode)
return;
*p++ = pNode->vec.size();
*p++ = pNode->nVal;
for (vector::iterator it = pNode->vec.begin();
it != pNode->vec.end(); it++)
_inner_serial(*it, p);
}
const char* Serialize(NODE* pRoot, char mem[])
{
if (NULL == mem || NULL == pRoot)
return NULL;
char... 阅读全帖
w****x
发帖数: 2483
17
/*
Serialize/DeSerialize a tree
*/
struct NODE
{
int nVal;
vector vec;
NODE(int n) : nVal(n) {}
};
void _inner_serial(NODE* pNode, char*& p)
{
if (NULL == pNode)
return;
*p++ = pNode->vec.size();
*p++ = pNode->nVal;
for (vector::iterator it = pNode->vec.begin();
it != pNode->vec.end(); it++)
_inner_serial(*it, p);
}
const char* Serialize(NODE* pRoot, char mem[])
{
if (NULL == mem || NULL == pRoot)
return NULL;
char... 阅读全帖
w****x
发帖数: 2483
18
来自主题: JobHunting版 - 发一个刚面的startup面经
直接贴Google doc了
Given a word, print out all the combinations of words from the letters that
make it. For example:
bad: abd adb bda dab dba
void _inner_print(char str[], int len, int pos)
{
if (pos == len)
{
cout< return;
}
for (int i = pos; i < len; i++)
{
swap(str[pos], str[i]);
_inner_print(str, len, pos+1);
swap(str[pos], str[i]);
}
}
Input: bad
step 1: 3, i = 0 - bad
step 2.: 3, i = 1 - abd
step 2.: 3, i = 2 - dabchar
void... 阅读全帖
f*******t
发帖数: 7549
19
来自主题: JobHunting版 - 2道算法题。 求教大家!
找出了一年多前写的逆波兰处理算数表达式的代码,强烈建议有兴趣的自己实现一下:
#include
#include
#include
#include
#define BUFFSIZE 1024
using namespace std;
struct Token {
bool isNum;
int num;
char op;
Token();
Token(const Token& t);
};
Token::Token()
{
isNum = false;
num = 0;
op = 0;
}
Token::Token(const Token& t)
{
isNum = t.isNum;
num = t.num;
op = t.op;
}
Token *getToken(const char expr[], int& idx)
{
Token *res = NULL;
while(expr[idx] == ' ')
... 阅读全帖
e******i
发帖数: 106
20
来自主题: JobHunting版 - 问一道题的优化以及时间复杂度
这是在career cup 上看到的题:
Given a hashmap M which is a mapping of characters to arrays of substitute
characters, and an input string S, return an array of all possible mutations
of S (where any character in S can be substituted with one of its
substitutes in M, if it exists).
What is the time complexity? What is the space complexity? Can you optimize
either?
Example input:
M = { f: [F, 4], b: [B, 8] }
S = fab
Expected output:
[fab, Fab, 4ab, faB, FaB, 4aB, fa8, Fa8, 4a8]
这是我的解法,用backtrack... 阅读全帖
j**7
发帖数: 143
21
来自主题: JobHunting版 - 微软onsite SDET 面经
第三题的答案:
public class InfixToPostfix {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String infix="4*((5+6)*7";
infix="3+(1*2)";
String postfix=toPostfix(infix);
System.out.println(postfix);
System.out.println(evaluate(postfix));
}

//evaluate a postfix equation
static int evaluate(String postfix)
{
Stack st=new Stack阅读全帖
y****n
发帖数: 743
22
我的方法:通过一个顺序无关的校验码,找到“疑似”字串,在对“疑似”进行甄别。
public static int GetCode(char c)
{
return c * (c ^ 23405) % 74259;
}
public static bool IsPermut(string a, string b)
{
List chars = new List(a.ToArray());
foreach (char ch in b)
if (chars.Contains(ch))
chars.Remove(ch);
else
return false;
return true;
}
public static void FindPermut(string a, string b)
{
if (a.Length >= b.Length)
{
int codeSumB = 0;
for (int i = 0; i < b.Length; i++)
codeSumB += Get... 阅读全帖
x********i
发帖数: 92
23
来自主题: JobHunting版 - G家电面题
感觉对y的处理比较复杂. 我纯新手...写了一个代码, 望斧正
然后对于大小写的处理, 我就是创建一个新数组, 然后把所有的都转换成小写字母.
我运行了题目里给出的所有字符串, 结果都是正确的, 然后test了一个空字符串, 返回
为0. 求问还需要做什么样的test啊? 感觉很多代码写出来自己都不知道对不对, 因为
没有完善的test方案, 求指点...新手跪谢了
#define VOWELY 0
#define CONSOY 1
int vowelProduct(const char* newstr){
int length = strlen(newstr);
const char* consolant = "bcdfghjklmnpqrstvwxz";
const char* vowels = "aeiou";
int i;
int yFlag;
int score=0;
char* current;
char* yTest;
int point[26] = {0};
int tempScore=0;... 阅读全帖
J**9
发帖数: 835
24
来自主题: JobHunting版 - G家电面题
This is another question that seems easy but hard to code precisely.
Here's my version in C:
///1) Convert the string into all lower cases either in place or into
another buffer;
///2) First pass to check which ones are vowels;
///3) Second pass to sum up the products.
///4) Space O(n); Time O(n)
/** convert a string to lowercase in place */
char* hkStringTolower(char *str)
{
if(!str) return NULL;
char *s=str;
while(*s)
{
*s = tolower(*s);
s++;
}
return st... 阅读全帖
e*******i
发帖数: 56
25
来自主题: JobHunting版 - 最郁闷的facebook面试+面经。
Here is c++ version. Have to admit is over 15 lines.
Any suggestions to improve?
/*****************************************/
#include
#include
#include
using namespace std;
void maxRep(char *s)
{
int maxFreq=0;
int counter=0;
vector charList;
vector freqList;

char target=*s;
do{
if(*s!=target)
{
if( counter>=maxFreq && isalpha(target) )
{
maxFreq=counter;
charList.push_back(target);
... 阅读全帖
e*******i
发帖数: 56
26
来自主题: JobHunting版 - 求G加一题的线性解法
No map is needed. Source is as following:
///////////////
#include
using namespace std;
int findLongest(char *s, char **start)
{

if(!s) return 0;
char first, second;
char *beginOfPreviousChar;
int currMax=0;
char *curr=s;
first=*s;
*start=s;
while(*curr)
{
if(*curr!=first) break;
currMax++;
curr++;
}
if( !*curr ) return currMax; //end of string
else
{
second=*curr;
beginOfPreviousChar=curr... 阅读全帖
l********7
发帖数: 3
27
public static int find (String s){
Map hm = new HashMap();
char[] chars = s.toCharArray();
int length = 0;
for(int i = 0; i < chars.length; i++){
if (!hm.containsKey(chars[i])){
hm.put(chars[i], i);
length++;
}
else{
int tmp = i - hm.get(chars[i]);
if (tmp > length) length = tmp;
hm.put(chars[i], i);
... 阅读全帖
r*c
发帖数: 167
28
来自主题: JobHunting版 - G家电面
第一题要用binary search?
试写了一下,借用二爷的原代码
#include "stdafx.h" //cause I am using VC++
#include
#include
#include
using namespace std;
class Solution{
public:
Solution(unordered_mapmap){
_map = map;
_size = _map.size();
unordered_map::iterator it = _map.begin();
while(it != _map.end())
_vec.push_back(it++->first);
}

bool Prob() //borrowed from LeetCode
{
return r... 阅读全帖
s********u
发帖数: 1109
29
这是readline那个题我参照网上的代码写的。比这个要复杂一些,因为一个line的字符
是不确定的。
#define MAX_LEN 4096
int read(char* buf, int len);
char *readLine(){

static bool EOF = false;
char *str = NULL;
int i, size = 0;

static int currentPos = MAX_LEN;

static char* buffer = new char[MAX_LEN];

while(!EOF || currentPos != MAX_LEN ){

// buffer is not empty, handle buffer first
if(currentPos != MAX_LEN){

for(i = currentPos; i < MAX_LEN; i++)
... 阅读全帖
s********u
发帖数: 1109
30
来自主题: JobHunting版 - 请教一个fb面试问题
老题了吧,不过老要写错,尤其是那个read4写read的更恶心。
#define MAX_LEN 4096
int read(char* buf, int len);
char *readLine(){

static bool EOF = false;
char *str = NULL;
int i, size = 0;

static int currentPos = MAX_LEN;

static char* buffer = new char[MAX_LEN];

while(!EOF || currentPos != MAX_LEN ){

// buffer is not empty, handle buffer first
if(currentPos != MAX_LEN){

for(i = currentPos; i < MAX_LEN; i++)
if( buffer[i] ==... 阅读全帖
a*****f
发帖数: 6
31
leetcode上ValidNumber这道题有点烦,因为它的需求不明确
试了很多次,下面的代码通过了测试,供参考
public class Solution {
enum Token {Empty, Sign, Float, Int, IntWithSign, Invalid};

int findFirst(char[] s, char c, int p1, int p2) {
for (int i = p1; i <= p2; i ++)
if (s[i] == c) return i;

return -1;
}

int findLast(char[] s, char c, int p1, int p2) {
for (int i = p2; i >= p1; i --)
if (s[i] == c) return i;

return -1;
}

Tok... 阅读全帖
m*********t
发帖数: 527
32
来自主题: JobHunting版 - 贡献一道G家onsite题吧
忘了这茬子了。试了一下,下面这个东西可以算出来正确的路经,但是如果没有解的话
就死循环了。。。
#include
#include
#include
#include
#include
using namespace std;
unordered_map > dag;
int edge_count = 0;
stack history;
const char beg = 'A';
const char end = 'F';
bool DFS(char w) {
assert(edge_count >= 0);
if (dag.find(w) == dag.end()) {
return false;
}
auto& edges = dag.at(w);
auto itr = edges.begin();
while (itr != edges.end()) {
... 阅读全帖
m******n
发帖数: 51
33
来自主题: JobHunting版 - Zenefits面经
一进门 就已经有4个人坐在sofa等. 其中两个国人.问了一下都是来面试的. (Other两
人穿西装的应该是面Sales)
共面4个人 前三个人直接考题在白板写. 面试前连我的履历都没看过.
第四个人有看过我的履历
#1考古题http://www.mitbbs.com/article_t/JobHunting/33007237.html
#2考古题http://www.mitbbs.com/article_t/JobHunting/32931597.html
#3
String “abaca”
has following prefixes
a
ab
aba
abac
abaca
has following surfixes
a
ca
aca
baca
abaca
Calculate how many prefixes have the same distinct chars as the surfixes
For exmple
[Prefixes => distinct chars]
a => a
ab => ab
aba => ab
abac => abc
abaca =>a... 阅读全帖
C********s
发帖数: 7
34
来自主题: JobHunting版 - A家店面栽在一个老中手里
准确的说,并不是编译器智能高了,而是不同的编译器在不同的平台上有自由的选择
char的实现的权利,所以不能对char做这个假设。
比如在我的机器上用GCC,你的这段代码就不work。
stackoverflow上最精确的一段描述:
The C standard does not specify if plain char is signed or unsigned.
In fact, the standard defines three distinct types: char, signed char, and
unsigned char. If you #include and then look at CHAR_MIN, you can
find out if plain char is signed or unsigned (if CHAR_MIN is less than 0 or
equal to 0), but even then, the three types are distinct as far as the
standard is conc... 阅读全帖
b*********t
发帖数: 170
35
下午店面一个烙印,之前看了一下简历,印度某大学毕业,然后来美国读了个硕士,简
历上写着C/C++精通。
我问了一个跟字符串数组有关的题目,这个哥们上来就用char * words,然后告诉我
words[0]就是第一个string,以此类推。我很无语的提醒他,char*可以用来存一个
string,但words[0]是一个char,不是string,于是他马上换成char[],我说这跟char
*一样。然后他沉默了半分钟,说那我就不知道了
虽然我心里万马奔腾,但我看了看时间才过了10分钟,我总不能就这样挂电话吧,于是
我告诉他,我建议你用vector,代码写起来简单,他说我从来没有用过vector
(我心中那个翻腾啊,说好的C++精通呢?),于是我说那你就用char**或者char[][]
吧。
然后他就开始写代码,一开始我还盯着屏幕看他写code,5分钟之后我彻底放弃了。5分
钟的时间他一共写了8行,定义了5个局部变量,写了两个嵌套的for,最里面一个空空
的while。我当时心里一直在无力的呐喊,“说好的C精通呢?精通C语言的关键字吗?
”。我纠结了一下,我是否要给... 阅读全帖
f******y
发帖数: 14
36
来自主题: BuildingWeb版 - how to upload a local file to web server?
下面是c语言的,
你不必仔细看,这是cgihtml的一部分,你在网上搜索cgihtml,
保证可以搞到全部代码,
其实上在文件是非常基本的功能,网上肯定有,找就是了
int parse_form_encoded(llist* entries)
{
long content_length;
entrytype entry;
node* window;
FILE *uploadfile;
char *uploadfname, *tempstr, *boundary;
char *buffer = (char *)malloc(sizeof(char) * BUFSIZ + 1);
char *prevbuf = (char *)malloc(sizeof(char) + BUFSIZ + 1);
short isfile,done,start;
int i,j;
int bytesread,prevbytesread;
int buffersize;
int numentries = 0;
#ifdef WINDOWS
setmode(f
j*******a
发帖数: 101
37
来自主题: Programming版 - reverse words, not the Microsoft one!!!
i wrote one. it works well.
#include
using namespace std;
char* reverse_word (char* str);
int main(int argc, char** argv){
char str[] = "this is very beautiful ";
cout <<"["< cout << "["<< reverse_word(str)<<"]"< char str2[] = "jokeslala rejected some 100k offers ";
cout <<"["< cout << "["<< reverse_word(str2)<<"]"<
system("pause");
return 0;
}
char* reverse_word (char* str){
if (str =
b*********n
发帖数: 1258
38
#include
using namespace std;
void* strcopy(char* in_str){
char* out_str;
if(out_str=(char*)malloc(sizeof(in_str)+1)){
out_str=(char*)memcpy(out_str,in_str,sizeof(in_str)+1);
return out_str;
}else{
cout << "Insufficient Memory" << endl;
return NULL;
}
}
int main(int argc, char* argv[])
{
char* a="abcdefghijklmn";
cout << (char*)strcopy(a) << endl;
return 0;
}
s*****r
发帖数: 773
39
来自主题: Programming版 - 这段代码为何要这样做?
一个整数转化为字符串的函数
不太理解里面为什么要用到log
希望大家指点一二
char* itoa(int n) {
char *s =NULL;
char *p;
int nz;

int mf = 0;
if(n>=0) {
nz=log(n)/log(10);

s=(char*)calloc(nz+1,sizeof(char));
p=s;
}else{
if(n==INT_MIN) {
mf=1;
n=-INT_MAX;
}
nz=log(-n)/log(10);
n=-n;
s=(char *)calloc(nz+2,sizeof(char));
p=s;
*p='-';
p++;
}
int pt=pow(10,nz);

while(pt>=1){

if(pt==1&&mf)
*p=(n/pt)+'0'+1;
else
*p=(n/pt)+'0';
p++;
c***d
发帖数: 996
40
来自主题: Programming版 - [合集] 一个指针的小问题
☆─────────────────────────────────────☆
hapyrockets (hapyrockets) 于 (Thu Sep 27 19:16:35 2007) 提到:
下面的语句:
const char str3[] = "abc";
const char str4[] = "abc";
const char* str5 = "abc";
const char* str6 = "abc";
为什么
str3 == str4 -> false
str5 == str6 -> true
都是const, 我觉得 compiler让str3, str4, str5, str6都指向一个地址也未尝不可啊

☆─────────────────────────────────────☆
Pontiff (树) 于 (Thu Sep 27 19:26:08 2007) 提到:
再说一遍,数组不是指针

下面的语句:
const char str3[] = "abc";
const char str4[] = "abc";
const char*
y**********0
发帖数: 425
41
来自主题: Programming版 - 这个程序怎么解决
编写函数int index(char *s, char *t),返回字符串t 在字符串s中出现的最左边的
位置,
如果在s中没有与t匹配的子串,就返回-1。
#include
#include
int index(char *s,char *t)
{
int i,j,k;
for(i=0;s[i]!='\0';i++)
for(j=i,k=0;t[k]!='\0' && s[j]==t[k];j++,k++);
if(t[k]=='\0')
return i;
return -1;
}
void main()
{
int n;
char str1[20],str2[20];
gets(str1);
gets(str2);
n=index(str1,str2);
cout< }
始终得不到正确答案,是Index的问题。
答案的Index程序是这样的:得到了正确的答案。不知道为什么?
int ... 阅读全帖
m****s
发帖数: 1481
42
我需要读取一个数据文件,然后把读出来的数据放到不同的变量里,因为这些变量的长
度不确定,所以都是临时根据长度分配内存,code如下:
... main(){
...
...
int *a,length_a;
double *d,length_d;
char *c,length_c;
FILE *fp;
... 打开文件代码...
...读文件,获取变量a,d,c的长度...
a= new int[length_a];
d= new double[length_d];
c= new char[length_c];
...计算,处理...
delete[] a;
delete[] d;
delete[] c;
}
这种最基本的方法运行没问题。
现在因为我要load的变量很多,所以我想把loading用一个函数来做。如果只有一个变
量,我可以把它的pointer定义在main里面,然后用一个函数读取文件,在函数里
declare一个临时pointer,分配内存,赋值,然后返回这个pointer。
但是如果多个变量的情况怎么做呢?
我先试了把多个变量的指针传递给子函数,在子函数里declare... 阅读全帖
d****n
发帖数: 1637
43
来自主题: Programming版 - c字符串内存分配问题
malloc, calloc, realloc are in HEAP
alloca is in STACK
#####example####
buffered IO with char input
################
n=0;m=1024
char *s=(char *)calloc(m, sizeof(char));
char c;
while((c=getch())!=EOF){
if(n==m) s=(char *)realloc(s, (m<<=1),sizeof(char) );
*(s+(n++))=c;
}
*(s+n)='\0';
printf("%s\n", s);
free(s);
g*****1
发帖数: 998
44
来自主题: Programming版 - 请教一道c/c++题
char *m()
{
char str[50];
strcpy(str,"how are you");
return str;
}
int main()
{
char s[50];
strcpy(s,m());
printf("%s",s);
//cin.get();
return 0;
}
为什么结果可以正确输出呢?我知道return by pointer可以make copy,可是return之
后storage不是free了吗?
另外,为什么下面这个就只能由一部分正确输出?
char *m()
{
char str[20];
strcpy(str,"how are you");
return str;
}
int main()
{

printf("%s",m());
//cin.get();
return 0;
}
然后上面char str[20];改成比如char str[50],输出就完全是乱得了
d****n
发帖数: 1637
45
来自主题: Programming版 - 请教一道c/c++题
this makes the array safe.
char *m()
{
Static char str[50];
strcpy(str,"how are you");
return str;
}
或者这样 thread safe
char * m(){
char *ret=(char *)malloc(sizeof(char)*20);
strcpy(str, "I am good");
return str;
}
main(){
char * str=m();

printf("%s\n",str);
free(str);
}
g***l
发帖数: 2753
46
来自主题: Programming版 - 请教一个C++中function pointer的问题。
老大的这个方法是可行的。可是又出现新的问题了。
我定义了如下接口:
template
dec_base* new_object()
{
return new T;
}
typedef dec_base* (*ObjectGenerator)();
static std::map generator_map;
template
void register_dec_handle(int tag_id)
{
generator_map.insert(make_pair(tag_id,new_object));
}
如果把以上代码跟 main() 代码放在一个main.cpp里面,编译链接都没有问题。但是如
果把以上代码放在另外一个单独的sample.cpp里面,在另外一个main.cpp中的main()调用
register_dec_handle()的时间,gcc就会报告
g++ main.cpp sample.cpp -o sample.exe
main.cpp: 在函数‘int main(... 阅读全帖
p*********t
发帖数: 2690
47
fun1()在返回一个局部变量的地址,所以输出的是這個地址的值,因为fun1()的局部变
量在函数结束时消失,那个地址可能又被分配了新的值,所以是乱码。
要想输出abc,可以在fun1()的str设为static,这样即使fun1()函数结束,str[]还是在
内存存在。
char *fun1() {
static char str[]="ABC";
return (str);
}

有下面这段code, 为什么fun1()输出乱码, 而fun2()输出正确: ABC.
====== code ============
#include
int main() {
char *fun1(), *fun2();
printf("%s\n%s\n", fun1(), fun2());
return 0;
}
char *fun1() {
char str[]="ABC";
return (str);
}
char *fun2() {
char (*str)[]="ABC";
return (str);
... 阅读全帖
O*******d
发帖数: 20343
48
来自主题: Programming版 - recurvion真的很难懂~~
recursion和写loop一样,需要有起始值和终止条件。还要有变化值使终止条件可以达
到。 可以从简单练习做起。 例如遍历多叉树,比如把一个folder里的所有folder和文
件的名字都印出来。再简单的练习可以把一段句子反转。
void Reverse(char* begin, char* end)
{
if(end > begin)
{
char temp = *begin;
*begin = *end;
*end = temp;
Reverse(begin + 1, end - 1);
}
}
char str[] = "ABCDEFG";
Reverse(str, str + strlen(str) - 1);
如果写成循环
char* begin = str;
char* end = str+ strlen(str) - 1;
while(end > begin)
{
char temp = *begin;
*begin = *end;
*end = temp;
begin++;
end--;
}
这里的关键是一旦终... 阅读全帖
k***p
发帖数: 115
49
来自主题: Programming版 - 请教boost::any compile错误。
我的compiler是gcc 4.7。 多谢
$g++ testAny.cpp -o testAny
testAny.cpp: In function ‘void AnyTesting3()’:
testAny.cpp:66:54: error: no match for ‘operator=’ in ‘myPropertySet.std:
:map<_Key, _Tp, _Compare, _Alloc>::operator[], boost
::any, std::less >, std::allocator std::basic_string, boost::any> > >((* & std::basic_string(((
const char*)"BarrType"), (*(const std::allocator*)(& std::allocator<
char>()))))) = (BarrierType)... 阅读全帖
S*A
发帖数: 7142
50
real 19m21.306s
user 19m19.382s
sys 0m1.902s
这个是单线程做4000x100000, 每行30 random ASCII string。
配额合前面的 python 生成的数据文件使用。
这个 diff 的强度比较高了,我的破笔记本是老版MBA。
才19 分钟。如果加多线程,快点的 CPU, 例如 4 thread 个
就可以 5 分钟左右了。
我想要拼过这个速度恐怕很难了。
BTW, lcs code 是网上的改的。
发包子吧。
/* Dynamic Programming implementation of LCS problem */
#include
#include
#include
#include
#include
#include

/* Utility function to get max of 2 integers */
static inline int max(... 阅读全帖
首页 上页 1 2 3 4 5 6 7 8 9 10 下页 末页 (共10页)