C string 問題

想問下如果我 pass 條string 去 一個function
個 function 會return 1 個 data structure ,入面裝左條 string 既 ptr
想問下 咁做係咪 唔得? 因為條string 係local variable ,d memory 可能會比人 rewrite?
  1. int main(){
  2.       saveString("HELLO");
  3. }
  4. struct x saveString(char * s){
  5.       struct x temp;
  6.       temp.string = s;
  7.       return x;
  8. }
複製代碼

根據一本C PROGRAMMING 本書講其實係無問題。
The only legal operations on a structure are copying it or assigning to it as a unit, taking its address with &, and accessing its members , Copy and assignment include passing arguments to functions and returning values from functions as well.
  1. /* makepoint: make a point from x and y components */
  2. struct point makepoint(int x, int y)
  3. {
  4. struct point temp;
  5. temp.x = x;
  6. temp.y = y;
  7. return temp;
  8. }
複製代碼

TOP

回復 1# tonald


    it's should be ok because the whole structure is copied and returned, but if you return the address of the variable, pointer to structure or array, then that should be a trouble.
btw, line 7 should be return temp :p

TOP

In C, "string" is actually a pointer to a char array which is assumed to contain a '\0' somewhere to indicate its termination.  Hence, the declaration of "string" is "char *" (pointer to char... or a memory address which de-reference back to a char).

Since your function returns the whole struct, these memory addresses can be returned as part of the struct.  As for whether these memory addresses is still occupied by the data your want, it is your program's responsibility.

TOP

樓主係問緊可行性 定係 安全性 ?

TOP

提示: 作者被禁止或刪除 內容自動屏蔽

TOP