简体   繁体   English

将ptr分配给char指针

[英]Assign ptr to char pointer

I would like to find out how to get this code to work, my printf in the main function will not print the "test" string. 我想了解如何使此代码正常工作,我在main函数中的printf将不会打印“ test”字符串。

#include <stdio.h>

int main()
{
char b[10];
test(b);
printf("from main func: %s\n", b);
}

int test(char* buf)
{
char len[] = "test";
char *pt = len;

printf("printing ptr: %s\n", pt);

buf = pt;

printf("from test func: %s\n", buf);

return 1;
}

First of you need to have a prototype for the test function or place it above main. 首先,您需要具有test功能的原型或将其放置在main之上。

#include <stdio.h>
#include <string.h>

int test(char *);

int main()
{
char b[10];
test(b);
printf("from main func: %s\n", b);
}

int test(char* buf)
{
char len[] = "test";
char *pt = len;

printf("printing ptr: %s\n", pt);

strcpy(buf, pt);

printf("from test func: %s\n", buf);

return 1;
}

Also you should never try to pass a local variable to a function. 另外,您永远不要尝试将局部变量传递给函数。 It will not work, thus you have to use strcpy(buf, pt); 它不起作用,因此您必须使用strcpy(buf, pt); instead of pointing the local variable len to buf . 而不是将局部变量len buf

Instead of assigning pt to buf you need to copy the string to buf : 无需将pt分配给buf,您需要将字符串复制到buf

strcpy(buf, pt);

Here is a safer version of your code: 这是代码的安全版本:

#include <assert.h>
#include <stdio.h>
#include <string.h>

#define LEN(arr) (sizeof (arr) / sizeof (arr)[0])

void test(char *buf, int bufLen)
{
    char len[] = "test";
    char *pt = len;

    assert(bufLen > strlen(len));

    printf("printing ptr: %s\n", pt);
    strcpy(buf, pt);
    printf("from test func: %s\n", buf);
}


int main()
{
    char b[10];

    test(b, LEN(b));
    printf("from main func: %s\n", b);
    return 0;
}

You cannot use buf = pt; 您不能使用buf = pt; in C. The reason being is that C sees "test" as a list of individual characters. 原因是C将“测试”视为单个字符的列表。 like 't', 'e', 's', 't'. 例如“ t”,“ e”,“ s”,“ t”。 Like an array of integers, you could not have something like... 像整数数组一样,您不能有类似...

int myArray[5] = { 0, 1, 2, 3, 4 }; int myArray [5] = {0,1,2,3,4};

and then have something like... 然后有类似...

int newArray[5] = myArray... that just wouldn't work, well, an array of characters is no different. int newArray [5] = myArray ...那是行不通的,嗯,字符数组没有什么不同。 You need to copy each character over to the new array, just like you would with an array of ints. 您需要将每个字符复制到新数组中,就像使用int数组一样。 You could write your own function to do this, or use one of the built in functions that are available like strcpy() which will copy them for you. 您可以编写自己的函数来执行此操作,也可以使用诸如strcpy()之类的可用内置函数之一为您复制它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM