用char * p定义字符串是否正确;并在以后分配值?

时间:2015-01-25 16:41:54

标签: c string pointers dynamic

我想创建一个字符串而不知道它的确切维度,这是正确的还是会产生不可预测的行为?

char *p;
p="unknow string size";

如果这是错的,我怎么能创建类似的东西,并用string.h fucntion修改它?

[编辑]我再次阅读答案,并不完全清楚,我的第一个怀疑是: 这两个代码是否等于?

char *p="unknow string size"

char *p;
p="unknow string size";

3 个答案:

答案 0 :(得分:2)

C中唯一的解决方案是使用realloc函数

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *s = malloc(1);
    printf("Enter a string: \t"); // It can be of any length
    int c;
    int i = 0;
    while((c = getchar()) != '\n' && c != EOF)
    {
        s[i++] = c;
        s = realloc(s, i+1);
    }
    s[i] = '\0';
    printf("Entered string: \t%s", s);
    free(s);
    return 0;
}  
  

这两个代码是否等于?

char *p="unknown string size"
     

char *p;
p="unknown string size";  

没有。第一个代码段将p声明为char的指针,并将其初始化为指向字符串文字"unknown string size"。在第二个代码段中,p被定义为指向char的指针,然后对其进行分配。

答案 1 :(得分:0)

这取决于你没有分配值,y指向存储"unknow string size"的地址,所以你应该知道,例如你不能修改字符串。

如果您不想修改字符串,那么它没问题,但您还应该保护指针以尝试写入该内存位置,因为这将是未定义的行为,您可以这样做< / p>

const char *p;
p = "unknow string size";

这不会阻止您修改字符串,但是您需要显式地转换const限定符来执行此操作。

如果您打算稍后修改字符串,那么这不是这样做的方法,在这种情况下你应该这样做

char *p;
size_t length;

length = strlen("unknow string size");
p = malloc(1 + length);
if (p == NULL)
    memoryAllocationProblemDoNotContinue();
strcpy(p, "unknow string size");
 .
 .
 .
 /* use p here */
 .
 .
 .
 free(p);

答案 2 :(得分:0)

I would write the function like this:

#include <stdio.h> // printf(), getline()
#include <stdlib.h>
#include <string.h> // strlen()

int main(void)
{
    char *s = NULL;

    printf("Enter a string: \t"); // It can be of any length
    fflush(stdout);

    getline(&s, 0, stdin); // note: first param is **char

    if( NULL != s )
    { // then getline successful

        // trim trailing newline
        if( '\n' == s[strlen(s)-1] ) s[strlen(s)-1] = '\0'; 

        printf("Entered string: \t%s", s);
        free(s);
    }  // end if
    return 0;
} // end function: main
相关问题