strcpy

error: function returns address of local variable

佐手、 提交于 2019-11-26 02:01:22
问题 I\'m beginner with C and I am learning on my own. I am creating the following function: char *foo(int x){ if(x < 0){ char a[1000]; char b = \"blah\"; x = x - 1; char *c = foo(x); strcpy(a, b); strcat(a, c); return a; } blah ... } I am basically trying to return an appended string, but I get the following error: \"error: function returns address of local variable\", any suggestions, how to fix this? 回答1: The local variables have a lifetime which extends only inside the block in which it is

Why should you use strncpy instead of strcpy?

别等时光非礼了梦想. 提交于 2019-11-26 00:08:22
问题 Edit: I\'ve added the source for the example. I came across this example: char source[MAX] = \"123456789\"; char source1[MAX] = \"123456789\"; char destination[MAX] = \"abcdefg\"; char destination1[MAX] = \"abcdefg\"; char *return_string; int index = 5; /* This is how strcpy works */ printf(\"destination is originally = \'%s\'\\n\", destination); return_string = strcpy(destination, source); printf(\"after strcpy, dest becomes \'%s\'\\n\\n\", destination); /* This is how strncpy works */

How to correctly assign a new string value?

半腔热情 提交于 2019-11-25 22:33:48
问题 I\'m trying to understand how to solve this trivial problem in C, in the cleanest/safest way. Here\'s my example: #include <stdio.h> int main(int argc, char *argv[]) { typedef struct { char name[20]; char surname[20]; int unsigned age; } person; //Here i can pass strings as values...how does it works? person p = {\"John\", \"Doe\",30}; printf(\"Name: %s; Age: %d\\n\",p.name,p.age); // This works as expected... p.age = 25; //...but the same approach doesn\'t work with a string p.name = \"Jane\

C++ 数据结构

自古美人都是妖i 提交于 2019-11-25 19:29:48
一、C++ 数据结构 C/C++ 数组允许定义可存储相同类型数据项的变量,但是结构是 C++ 中另一种用户自定义的可用的数据类型,它允许您存储不同类型的数据项。 结构用于表示一条记录,假设您想要跟踪图书馆中书本的动态,您可能需要跟踪每本书的下列属性: Title :标题 Author :作者 Subject :类目 Book ID :书的 ID 1.1 定义结构 为了定义结构,您必须使用 struct 语句。struct 语句定义了一个包含多个成员的新的数据类型,struct 语句的格式如下: struct type_name { member_type1 member_name1 ; member_type2 member_name2 ; member_type3 member_name3 ; . . } object_names ; type_name 是结构体类型的名称,member_type1 member_name1 是标准的变量定义,比如 int i; 或者 float f; 或者其他有效的变量定义。在结构定义的末尾,最后一个分号之前,您可以指定一个或多个结构变量,这是可选的。下面是声明一个结构体类型 Books,变量为 book: struct Books { char title [ 50 ] ; char author [ 50 ] ; char subject