我发布了一个关于我之前在这个问题中遇到的一些指针问题的问题: C int 指针分段错误几种情况,无法解释行为
从一些评论中,我被引导相信以下几点:
#include <stdlib.h>
#include <stdio.h>
int main(){
int *p;
*p = 1;
printf("%d\n", *p);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
是未定义的行为。这是真的?我一直这样做,我什至在我的 C 课程中看到过。但是,当我这样做时
#include <stdlib.h>
#include <stdio.h>
int main(){
int *p=NULL;
*p = 1;
printf("%d\n", *p);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在打印p(行之后*p=1;)的内容之前,我遇到了段错误。这是否意味着我应该在malloc任何时候为要指向的指针分配值时一直在ing?
如果是这样,那为什么char *string = "this is a string"总是有效?
我很困惑,请帮忙!
I keep getting a compiler issue when trying to use a struct I defined in a header file.
我有两个文件main.c:
#include <stdio.h>
#include <stdlib.h>
#include "node.h"
int main(){
struct NODE node;
node.data = 5;
printf("%d\n", node.data);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
以及node.h:
#ifndef NODE
#define NODE
struct NODE{
int data;
struct NODE *next;
};
#endif
Run Code Online (Sandbox Code Playgroud)
我正在写一个小程序来用C进行一些模块化编程,但是却遇到了以下编译器错误:
node.h:5:21: error: expected ‘{’ before ‘*’ token
struct NODE *next;
^
Run Code Online (Sandbox Code Playgroud)
我得到了main.c编译,做我想它的时候,我定义做了什么struct,直接在文件中main.c,但由于某种原因,它不会工作,如果我把一个头文件中的定义,然后尝试把它列入main.c。这非常令人沮丧,我敢肯定这是一件小事,但是有人可以告诉我为什么这不起作用吗?从我一直在阅读的书中,我应该能够做到这一点,不是吗?
非常感谢!
我是一名学习 C 的学生,我一直在使用字符串数组和 malloc()。
我有以下代码,它应该使用动态创建的字符串加载一个字符串数组(静态创建的)(如果我的术语与我拥有的代码不一致,请原谅/纠正我)。
问题是,一旦我释放该内存,就会出现以下错误: free(): invalid pointer
这是代码:
#include <stdio.h>
#include <stdlib.h>
#define RAM_SIZE 5
char* ram [RAM_SIZE];
int next_free_cell = 0;
void freeAndNullRam(){
for (int i = 0 ; i < RAM_SIZE ; i++){
printf("%d\n", i);
free(ram[i]);
ram[i] = NULL;
}
}
int main(int argc, const char *argv[])
{
for (int i= 0; i < RAM_SIZE; i++){
ram[i] = (char*)malloc(sizeof(char*)*5);
ram[i] = "aaaa";
}
for (int i= 0; i < RAM_SIZE; i++){
int empty = (ram[i] ==NULL); …Run Code Online (Sandbox Code Playgroud)