简体   繁体   English

将char数组分配给char *

[英]Assigning a char array to a char*

I'm trying to write a function that prefixes a string with its length. 我正在尝试编写一个以字符串长度作为前缀的函数。 I can't seem to assign a char[] to a char *. 我似乎无法将char []分配给char *。 Mysteriously, if I print out some debugging code before the assignment, it works. 奇怪的是,如果我在分配作业之前打印出一些调试代码,它将起作用。

char *prefixMsgWLength(char *msg){
  char *msgWLength;
  int msgLength = strlen(msg);

  if (msgLength == 0){
    msgWLength = "2|";
  }
  else{

    int nDigits = floor(log10(abs(msgLength))) + 1;
    int nDigits2 = floor(log10(abs(msgLength + nDigits + 1))) + 1;

    if (nDigits2 > nDigits){
      nDigits = nDigits2;
    }

    msgLength += nDigits + 1;

    char prefix[msgLength];
    sprintf(prefix, "%d|", msgLength);

    strcat(prefix, msg);
    // if I uncomment the below, msgWLength is returned correctly
    // printf("msg: %s\n", prefix);
    msgWLength = prefix;
  }
  return msgWLength;
}

The problem in your code is 您的代码中的问题是

 msgWLength = prefix;

here, you're assigning the address of a local variable ( prefix ) to the pointer and you try to return it. 在这里,您正在为指针分配一个局部变量的地址( prefix ),然后尝试return它。

Once the function finishes execution, the local variables will go out of scope and the returned pointer will be invalid. 函数完成执行后,局部变量将超出范围,返回的指针将无效。

You need to make prefix as a pointer and allocate memory dynamically, if you want it to retain it's existence after returning from the function. 如果希望从函数返回后保留它的存在 ,则需要将prefix作为指针并动态分配内存。

String reallocation to the exact length can be very cumbersome in C. You'd probably be much better off just using a sufficiently large buffer. 在C语言中,将字符串重新分配为确切长度可能非常麻烦。仅使用足够大的缓冲区可能会更好。 Here, I use limits.h to determine the size of a line buffer according to the system ( LINE_MAX ): 在这里,我使用limits.h根据系统( LINE_MAX )确定行缓冲区的大小:

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

int main()
{
    /* Our message */
    char const msg[] = "Hello, world!";
    /* Buffer to hold the result */
    char buffer[LINE_MAX];

    /* Prefix msg with length */
    snprintf(buffer, LINE_MAX, "%lu|%s", strlen(msg)+1, msg);

    /* Print result */
    printf("%s\n", buffer);

    return 0;
}

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

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