功能修改c中的typedef字符串,引用,指针,

时间:2015-10-26 00:32:38

标签: c

所以,我的品牌打击C. C. C#为我做垃圾收集,所以我不需要担心这些东西。这给我带来了几天的问题,而且我没有找到任何真正的示例代码,其中传递引用和指针作为参数显然是明确的。

我也明白按价值传递物品被认为是不好的做法,但我甚至无法掌握传递和引用事物的概念。

陈述目标:在另一个函数中设置类型定义字符串的值,不带类型函数或任何返回值。

传递指针和参考功能的任何基本解释都会有所帮助。 "编程C"书上说要做这样的事情:

swap(int *a, int *b){
  //swap
}

//main
int a, b;
swap(&a,&b);

如果可以使用我的代码示例的某些外观来完成?

提前非常感谢!

代码:

#include <stdio.h>

//yes I'm aware that I need to set the array size
//to be larger than string length + 1 to account for "\0"
//this is a contrived, overly simplistic example for the sake
// of hopefully getting a very clear basic example

typedef char * string;

void func2(string *str){ 
  str = "blah"
  //currently, my code here does not change the value of str
  //as declared in main
  //have tried multiple different formats
  //i.e. func2(&str)
  //func2(str)
  //func2(*str)
  //etc
  //*str in this context I thought should be a pointer to the value of str passed from func
  //or perhaps str should be... not exactly sure what is going on and why 
  //this is so difficult
}
void func(string *str){
  str = "blah blah";
  //also trying
  //*str = "blah"
  //under the impression that this is now a char *** type? or char ** type?
  //in my code, str may be passed to a func2(str); 
  //where it may be manipulated again
  //it is my understanding that passing func2(&str) would
  //pass in the address of a pointer, which I don't want
  //or passing func2(*str) would pass a pointer to a pointer
  // which i also don't want.
}

main(){
   string str;
   //pass location of str in memory
   funct(&str);

   //this code will print the str set in func, but not when modified in func2
   printf("%s", str);
}

1 个答案:

答案 0 :(得分:1)

对代码进行最少的修改,您可能需要这样的内容:

#include <stdio.h>

typedef char * string;

void func2(string *str){
    *str = "blah";
}

void func1(string *str){ 
    func2(str);
}

int main(){
    string str;

    func1(&str);
    puts(str);

    func2(&str);
    puts(str);

    return 0;
}

编译并测试好了。