user-0 提问: C语言的char *和string / Bus Error的问题

回复:
user: user-1
content: 这里我想象了一下，不知道原因是不是因为C语言的stack结构，导致该string被其他的变量值“挤”在了中间？？？  是不是在C中，char *类型的变量基本不要拿来作为string，要用string需要用char a[100] 这种规定好了长度的char数组才行啊？？？(如果是这样的话，数组长度固定，为了满足需求，只能写一个很大的数字，造成空间上的浪费。。。。)  -------------------------------------- 必须分配空间，不过你可以预算下或者用程序计算下你需要分配的长度，然后再定义数组。

user: user-1
content: 1 eg1 :helloworld是在常量区，p只是一个指针指向这一块常量区   eg2:必须为a分配内存，char a[10]，这样a分配了10个char字节，然后在接收你的输入 2 没什么问题，你是写错了吧，下面这样。  void getUsrName(char **p){ #ifdef WIN32     *p=getenv("USERNAME"); #else     *p=getenv("USER"); #endif }

user: user-2
content: void getUsrName(char **p){ #ifdef WIN32     *p=getenv("USERNAME"); #else     *p=getenv("USER"); #endif }    int functionXXX(....){     char *p;     getUsrName(&p)    //只是想在这列让p的值=系统用户名     ........// 接下来会有若干步操作,只要不修改p指向的内容     printf("%s",p)     return EXIT_SUCCESS; }  GETENV Section: POSIX Programmer's Manual (P) Updated: 2003  --------------------------------------------------------------------------------    NAME getenv - get value of an environment variable    SYNOPSIS #include <stdlib.h>    char *getenv(const char *name);      DESCRIPTION The getenv() function shall search the environment of the calling process (see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables) for the environment variable name if it exists and return a pointer to the value of the environment variable. If the specified environment variable cannot be found, a null pointer shall be returned. The application shall ensure that it does not modify the string pointed to by the getenv() function.   The string pointed to may be overwritten by a subsequent call to getenv(), setenv(), or unsetenv(), but shall not be overwritten by a call to any other function in this volume of IEEE Std 1003.1-2001.   If the application modifies environ or the pointers to which it points, the behavior of getenv() is undefined.   The getenv() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.     RETURN VALUE Upon successful completion, getenv() shall return a pointer to a string containing the value for the specified name. If the specified name cannot be found in the environment of the calling process, a null pointer shall be returned.   The return value from getenv() may point to static data which may be overwritten by subsequent calls to getenv(), setenv(), or unsetenv().   On XSI-conformant systems, the return value from getenv() may point to static data which may also be overwritten by subsequent calls to putenv().     ERRORS No errors are defined.   The following sections are informative.     EXAMPLES    Getting the Value of an Environment Variable The following example gets the value of the HOME environment variable.     #include <stdlib.h> ... const char *name = "HOME"; char *value;   value = getenv(name);      APPLICATION USAGE None.     RATIONALE The clearenv() function was considered but rejected. The putenv() function has now been included for alignment with the Single UNIX Specification.   The getenv() function is inherently not reentrant because it returns a value pointing to static data.   Conforming applications are required not to modify environ directly, but to use only the functions described here to manipulate the process environment as an abstract object. Thus, the implementation of the environment access functions has complete control over the data structure used to represent the environment (subject to the requirement that environ be maintained as a list of strings with embedded equal signs for applications that wish to scan the environment). This constraint allows the implementation to properly manage the memory it allocates, either by using allocated storage for all variables (copying them on the first invocation of setenv() or unsetenv()), or keeping track of which strings are currently in allocated space and which are not, via a separate table or some other means. This enables the implementation to free any allocated space used by strings (and perhaps the pointers to them) stored in environ when unsetenv() is called. A C runtime start-up procedure (that which invokes main() and perhaps initializes environ) can also initialize a flag indicating that none of the environment has yet been copied to allocated storage, or that the separate table has not yet been initialized.   In fact, for higher performance of getenv(), the implementation could also maintain a separate copy of the environment in a data structure that could be searched much more quickly (such as an indexed hash table, or a binary tree), and update both it and the linear list at environ when setenv() or unsetenv() is invoked.   Performance of getenv() can be important for applications which have large numbers of environment variables. Typically, applications like this use the environment as a resource database of user-configurable parameters. The fact that these variables are in the user's shell environment usually means that any other program that uses environment variables (such as ls, which attempts to use COLUMNS ), or really almost any utility ( LANG , LC_ALL , and so on) is similarly slowed down by the linear search through the variables.   An implementation that maintains separate data structures, or even one that manages the memory it consumes, is not currently required as it was thought it would reduce consensus among implementors who do not want to change their historical implementations.   The POSIX Threads Extension states that multi-threaded applications must not modify environ directly, and that IEEE Std 1003.1-2001 is providing functions which such applications can use in the future to manipulate the environment in a thread-safe manner. Thus, moving away from application use of environ is desirable from that standpoint as well.     FUTURE DIRECTIONS None.     SEE ALSO exec() , putenv() , setenv() , unsetenv() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables, <stdlib.h>     COPYRIGHT Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .  --------------------------------------------------------------------------------

user: user-3
content: 1、直接初始化，a会被放在常量区，其内容不能被改写； 2、用之前可以现malloc分配内存，strcpy可以进行字符串赋值。  引用 楼主 soul376 的回复:CSDN论坛真是有爱啊， 小弟最近在写一个跟string有关的程序 对C语言中的string和char * / char[]有各种疑惑  第一个问题： C语言中，可以直接对指向char的指针变量进行赋值操作吗？  eg1:这个貌似正常  char *a="hello world";   eg2:这个一般来说会出现bus error  char *a; .........//中间若干步其他操作 scanf("%s",a)   这里我想象了一下，不知道原因是不是因为C语言的stack结构，导致该string被其他的变量值“挤”在了中间？？？  是不是在C中，char *类型的变量基本不要拿来作为string，要用string需要用char a[100] 这种规定好了长度的char数组才行啊？？？(如果是这样的话，数组长度固定，为了满足需求，只能写一个很大的数字，造成空间上的浪费。。。。)   问题2：这是我最近写的一个利用getenv()获得用户名的function，由于考虑到了Windows和Linux的兼容问题，我套用了外部函数，代码如下：  void getUsrName(char **p){ #ifdef WIN32     userName=getenv("USERNAME"); #else     (*userName)=getenv("USER"); #endif }   int functionXXX(....){     char *p;     getUsrName(&p)    //只是想在这列让p的值=系统用户名     ........// 接下来会有若干步操作     printf("%s",p)     return EXIT_SUCCESS; }   我现在很担心这个代码会不会也有类似的风险(BUS ERROR), 或者有其他的问题？ 求高人指点(真心不太想写一个长度很长的char p[xx] 数组，感觉浪费空间，而且长度上不好拿捏。。。。)

user: user-4
content: eg2这样写有问题吗？ char *a; char ca[10] = "123456"; a = ca; printf("%s\n",a);  是你没理解指针，不是这代码不行。

user: user-5
content: 你第一个写法就有问题，编译器没警告？ 应当写成： const char* var = "XXXXX";  你第二个写法没有分配内存。 简单来说，楼主完全没有理解指针与内存分配的概念。