指针编程问题 ---- 字符串前端和后端地址大小比较

内核编译和嵌入式产品的设计与开发
回复
chenxitwo
帖子: 31
注册时间: 2011-08-13 20:03

指针编程问题 ---- 字符串前端和后端地址大小比较

#1

帖子 chenxitwo » 2015-06-24 10:10

标题可能说的不清楚,详情如下:

代码: 全选

pstr_end = pstr + strlen(pstr) - 1;
pstr_work = pstr;
debug("pstr_work=0x%lx, pstr_end=0x%lx \n", pstr_work, pstr_end);
pstr指向一个字符串。最后程序的输出是:pstr_work=0x6a3674, pstr_end=0x76

这与我的原意相悖,我开始是认为 pstr_end > pstr_work, 所以请教大家造成这样结果的原因是什么?
头像
qgymib
帖子: 539
注册时间: 2010-04-02 16:44
系统: openSUSE 13.2 x64

Re: 指针编程问题 ---- 字符串前端和后端地址大小比较

#2

帖子 qgymib » 2015-06-24 13:36

请贴出完整的程序,并说明在什么平台下。尝试了一下没有什么问题,怀疑是你的pstr指向的不是字符串(末尾没有'\0')。

如下是我的代码:

代码: 全选

void standString(){
    char* pstr = "hello";
    char* pstr_end;
    char* pstr_work;
    
    pstr_end = pstr + strlen(pstr) - 1;
    pstr_work = pstr;
    printf("pstr_work=0x%lx, pstr_end=0x%lx \n", pstr_work, pstr_end);
}
在cygwin gcc 4.9.2 x64下的结果

代码: 全选

pstr_work=0x100403030, pstr_end=0x100403034 
正在建设中的个人博客
chenxitwo
帖子: 31
注册时间: 2011-08-13 20:03

Re: 指针编程问题 ---- 字符串前端和后端地址大小比较

#3

帖子 chenxitwo » 2015-06-24 14:26

完整代码

代码: 全选

BOOL str_toupper(char *pstr)
{
	char *pstr_work = NULL, pstr_end = NULL;
	
	if(!pstr)
	{
		error("char pointer is null!\n");
		return FALSE;
	}
	
	pstr_end = pstr + strlen(pstr) - 1;
	pstr_work = pstr;
debug("pstr_work=0x%lx, pstr_end=0x%lx \n", pstr_work, pstr_end);
	while(pstr_work <= pstr_end)
	//int len = strlen(pstr);
	//while(len-- > 0)
	{
		*pstr_work = toupper(*pstr_work);
		pstr_work++;
	}
debug("pstr=%s\n", pstr);

	return TRUE;
}
输出:

代码: 全选

[str_toupper]:35: pstr_work=0x6a4324, pstr_end=0x26 
[str_toupper]:43: pstr=yes

这个函数是将字符串中的小写转换成大写。系统linux,内核版本3.0.1 处理器是ARM架构的。
还有可以肯定pstr是指向一个字符串,不存在末尾没有'\0',之前这个函数我在其他平台用得很好。
现在我想知道哪些情况会导致出现这样情况,出现这样情况的原因是什么?
chenxitwo
帖子: 31
注册时间: 2011-08-13 20:03

Re: 指针编程问题 ---- 字符串前端和后端地址大小比较

#4

帖子 chenxitwo » 2015-06-24 15:29

我找到原因了,犯了个低级错误
char *pstr_work = NULL, pstr_end = NULL; 应该改为
char *pstr_work = NULL, *pstr_end = NULL;
回复