小编B.L*_*.Li的帖子

为什么C中的字符串用'const'声明?

例如,为什么不:

char *s= "example";
Run Code Online (Sandbox Code Playgroud)

代替:

const char *s= "example";
Run Code Online (Sandbox Code Playgroud)

我知道const使它不可更改,但为什么在编译第一个时会收到错误?

此外,该概念如何适用

int * x;
Run Code Online (Sandbox Code Playgroud)

VS

const int *x;
Run Code Online (Sandbox Code Playgroud)

我看到第二个使用了更多,使用"cons int*"是好的做法吗?

c string pointers const

3
推荐指数
1
解决办法
95
查看次数

我不确定为什么这个程序不会编译

这是我的计划:

#include<stdio.h>
#define COL 3;

void copy_row(int arr1[][COL], int rows, int arr2[], int r);

void copy_row(int arr1[][COL], int rows, int arr2[], int r){
  int i;
  if(r >= rows || r < 0)
    return;

  for(i = 0; i < COL; i++){
    arr1[r][i] = &arr2[i];
  }
}

int main(void){

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试使用gcc编译它时,它会在"之前"中显示"error:expected']';' 令牌"在第4行和第6行.

另外,参考for循环,将"arr1 [r] [i] = arr2 [i];" 做与"arr1 [r] [i] =&arr2 [i];"相同的事情?哪个(更)正确?

c arrays pointers prototype

1
推荐指数
1
解决办法
65
查看次数

realloc期间的分段错误

首先请允许我为格式化和困难的代码道歉.我是C和Stack的新手.这里的大多数混乱代码可能与问题无关,但必须包含在上下文中.

在第一次调用realloc之后,下面的代码会遇到分段错误(在注释中注明).return_file->target_line只是一个3D数组,i是3D数组第一维的元素计数.所以我在它上面调用realloc来存储额外的2D数组(类型char **).

NULL 故意省略了内存分配的返回b/c开发协议明确规定所有内存分配都会成功(我对此有疑问).

我正在使用自己的内存检查程序.我得到的错误代码是:

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7ac63fb in reallochook () from /lib64/libc.so.6
Run Code Online (Sandbox Code Playgroud)

我已经看了很长时间,但似乎无法找到问题所在.

Mockfile *read_mockfile(const char filename[]) {
  Mockfile *return_file = NULL;
  FILE *input;

  if(filename != NULL && (input = fopen(filename, "r")) != NULL) {
    char **split_tmp, line[MAX] = {0};

    return_file = malloc(sizeof(Mockfile));
    return_file->rule_count = 0;

    /*read lines*/
    while(fgets(line, MAX, input) != NULL){
      if(line[0] != '#' && line[0] != '\n'){
        int j, i = return_file->rule_count;
        split_tmp = split(line); …
Run Code Online (Sandbox Code Playgroud)

c dynamic-memory-allocation

-1
推荐指数
1
解决办法
569
查看次数