This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've just been introduced to pointers in C, and have been playing around with them to try and get more familiar with them.
Can someone explain to my why the code below doesn't compile?
int *high = (int *)malloc(sizeof(int)),*low = (int *)malloc(sizeof(int));
*high = 100;
*low = 0;
If you have #included stdlib.h it should compile.
To ensure that your code is correct, replace it with this:
#include <stdlib.h>
int *high = malloc(sizeof(int));
int *low = malloc(sizeof(int));
if(high == NULL || low == NULL)
{
// no memory, error handling here
}
*high = 100;
*low = 0;
...
free(high);
free(low);
Wrapping the code like shown below whould make it compile and work as expected:
#include <stdlib.h>
int main()
{
int *high = malloc(sizeof(int)),*low = malloc(sizeof(int));
*high = 100;
*low = 0;
return 0;
}
Anyway, the code lacks error checking on system calls. Always check the return value of system calls, In the case of malloc() a value of NULL would be returned if memory could not have been allocated as requested. In such case the line
*high = 100;
would most likely cause the program to crash, as dereferencing *NULL provokes undefined behavior.
In C it is not necessary to cast functions returning a value of void*. Even more it is not recommended to do so, as doing so might hide errors, for example if protoyping for the function in question is missing, the error/warning which would be given by the compiler without casting is surpressed if using casting.
Related
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
So I'm calling heapsort on an array in C.
My heapsort function looks like this:
void heapSort(int keys[], int numKeys){
...
int tmp[numKeys];
for(int i=0; i<numKeys; i++){
tmp[i] = maxVaue(h);
deleteMax(h);
}
*keys = tmp;
}
What I'm trying to do is change keys to point to the new array, as the function return type is void. Is there any way to do this with pointers, or do I need to just memcpy the array?
Arrays are not directly assignable, and also you can't use tmp outside the function, since it's out of scope when the function returns. You must use memcpy().
If you want to change what keys points to, you'll have to declare it as int **. And use explicit dynamic allocation (use of malloc) rather than a C99 Variable-Length array.
void heapSort(int **keys, int numKeys){
int tmp = malloc(sizeof(int)*numKeys);
...
free(*keys);
*keys = tmp;
}
int main(){
int *keys = malloc(sizeof(int)*numKeys);
...
heapSort(&keys, numKeys)
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm having some trouble using memcpy in that when the memcpy operation is performed I get:
"ÍÍWF03-021913.datýýýý««««««««þ"
when I should get:
"WF03-021913.datýýýý««««««««þ"
I don't know where these leading "ÍÍ" are coming from.
Code:
note: lpszFileName = "WF03-021913.dat"
typedef struct {
BYTE cbRequestType;
BYTE cbFileName;
char* szFileName;
} UFTP_GET_FILE_INFO_REQUEST;
BOOL Uftp_BuildFileInfoRequest(PUFTP_REQUEST request, LPCTSTR lpszFileName)
{
UFTP_GET_FILE_INFO_REQUEST *fileInfo;
int fileNameLen;
if (lpszFileName == NULL) {
ASSERT( 0 );
return FALSE;
}
fileNameLen = strlen( lpszFileName );
if (fileNameLen == 0)
return FALSE;
request->dwRequestSize = sizeof(UFTP_GET_FILE_INFO_REQUEST) -
sizeof(void*) + fileNameLen;
request->RequestBuffer = malloc( request->dwRequestSize );
if ( !request->RequestBuffer ) {
TRACE0("Failed to allocate RequestBuffer");
return FALSE;
}
fileInfo = (UFTP_GET_FILE_INFO_REQUEST*) request->RequestBuffer;
fileInfo->cbRequestType = UFTP_GET_FILE_INFO;
fileInfo->cbFileName = fileNameLen;
memcpy(&fileInfo->szFileName, lpszFileName, fileNameLen);
return TRUE;
}
I'm only guessing here, but my guess is that fileInfo->szFileName is a pointer. This means that &fileInfo->szFileName is a pointer to a pointer, so you copy to a complete other area of memory.
Also, you don't copy the terminating '\0' character needed. You need fileNameLen + 1 for that, both when allocating and when copying.
If you really want it all in contiguous memory, you should probably change the structure to end with a character-array of size zero (may not be supported by your compiler, then use an array of size 1) and use sizeof(UFTP_GET_FILE_INFO_REQUEST) + fileNameLen + 1 as the size to allocate. Then you can use the array as a normal string array.
And if you fix those problems, you have yet another problem: You don't initialize the pointer to point to allocated memory. This means it will point to some random memory.
All of these errors will lead to undefined behavior, and I would say you are lucky it didn't crash.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have 2 questions.
I want to create an array of files in C. But I'm not sure whether I have to malloc the size before or not.Can I just use FILE** files as an array or do I have to malloc them before. And if I have to make space, do I need to reserve 4 bytes (x86)?
I have the variable "char extra[8] = { 0xAE00AF00B000B100 };" and I want to assign it to the end of another char array[24]. Is there a faster way of doing that without having to type in every value by hand or using a for loop.
char extra[8] = { 0xAE00AF00B000B100 };
// index is a random place in the string
name[index] = '\0';
i = 0;
if (index > 16) {
for (i = 24-index; i < 8; i++) {
index++;
name[index] = extra[i];
}
}
else {
name[17] = 0xAE;
name[18] = 0x00;
name[19] = 0xAF;
name[20] = 0x00;
name[21] = 0xB0;
name[22] = 0x00;
name[23] = 0xB1;
name[24] = 0x00;
}
I need to add those extra bytes btw.
I want to create an array of files in C. But I'm not sure whether I
have to malloc the size before or not.Can I just use FILE** files as
an array or do I have to malloc them before. And if I have to make
space, do I need to reserve 4 bytes (x86)?
If you need to have an array of files, it is possible to use an array of pointers as follow:
#include <stdio.h>
FILE *array[NB_FILES];
Or you can do it dynamically if NB_FILES is only known at runtime.
#include <stdio.h>
#include <stdlib.h>
FILE **array = malloc(nb_files * sizeof *array);
I have the variable "char extra[8] = { 0xAE00AF00B000B100 };" and I want to assign it to the end of another char array[24]. Is there a faster way of doing that without having to type in every value by hand or using a for loop.
The standard C library provides the function memcpy, which is a builtin on many compiler (so it will be faster than a for loop).
#include <string.h>
char array[24];
char extra[8];
memcpy(array + sizeof array - sizeof extra - 1, extra, sizeof extra);
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have aproblem with this code, it compiles ok. But it crashes imidiately after memory could not be written error.
Debugger says the problem is in the line *grid = (grid_t**)malloc(sizeof(grid_t)*GRID_HEIGHT); , i must be missing something obvious.
I'm trying to create a pointer to a 2D struct.
#define GRID_WIDTH 12
#define GRID_HEIGHT 22
typedef struct
{
int piece;
int edge;
}grid_t;
grid_t*** grid;
*grid = (grid_t**)malloc(sizeof(grid_t)*GRID_HEIGHT);
for(int i = 0 ; i < GRID_HEIGHT ; i++)
{
*grid[i] = (grid_t*)malloc(sizeof(grid_t)*GRID_WIDTH);
}
You dereference an unallocated pointer:
grid_t*** grid;
*grid = (grid_t**)malloc(sizeof(grid_t)*GRID_HEIGHT);
grid is not allocated when you do *grid, so it's undefined behavior.
If you want to dynamically allocate two-dimensional structs, you first need to allocate enough memory for pointers (grid_t*) in the first level:
grid_t** grid;
grid = malloc(sizeof(*grid) * GRID_HEIGHT);
Then you can allocate each element with a loop:
for(int i = 0 ; i < GRID_HEIGHT ; i++)
{
grid[i] = malloc(sizeof(**grid) * GRID_WIDTH);
// ...then you can do grid[i]->piece = 42; etc..
}
Now, from what I can see, you probably don't even need dynamic allocation. If you don't need malloc, don't use it, just use good ol' arrays instead:
grid_t grid[GRID_HEIGHT][GRID_WIDTH];
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've discovered function pointers in C recently and I'm trying to get it working fine but I'm just pulling my hair on this!!!
I have a pointer to a function returning a string:
(char *) (*)() (*bar)().
But I want an array of 6 pointers to function on this but I can't get it working.
I keep getting compiler errors probably with parentheses stuff it's really messy. I've tried something like this but doesn't work:
(((char)(*))((*))(((*)((foo))))([(6)]));
I need help to do this array am I doing something wrong?
This is how you define a pointer to a function which return a string :
(char *) (*myFuncPtr)() = myFunc
Array :
(char *) (*myFuncPtr[6])();
myFuncPtr[0] = myFunc
etc...
Follow giorashc's answer or use a simple typedef:
#include <stdio.h>
typedef const char * (*szFunction)();
const char * hello(){ return "Hello";}
const char * world(){ return "world";}
const char * test(){ return "test";}
const char * demo(){ return "demo";}
const char * newline(){ return "\n";}
const char * smiley(){ return ":)";}
int main()
{
unsigned int i = 0;
szFunction myFunctions[6];
myFunctions[0] = hello;
myFunctions[1] = world;
myFunctions[2] = test;
myFunctions[3] = demo;
myFunctions[4] = newline;
myFunctions[5] = smiley;
for(i = 0; i < 6; ++i)
printf("%s\n",myFunctions[i]());
return 0;
}
Ideone demo
It doesn't look like your initial example is valid. To define a function pointer f that return a pointer to a character array, you should use the following syntax.
char* (*f)() = &func1
If you want an array of function pointers, use the syntax below
char* (*arrf[6])() = { &func1, &func2, &func3, &func4, &func5, &func6 }
Here's also a link to a useful old course handout on function pointers.