help with pointers? c

Tags
c error 73 memory management pain in the ass pointers segfault 
Labels
Members allowed to view this conversation
Everyone

void *

Last year Suspended

Need guides on learning how pointers work and when I should be using them… is the main reason why im not learning c.

void *

Last year Suspended

here's what I got so far:

#include <stdio.h>

int main(void) {
char message [] = "The raids will never stop";
char * message_POINTER = message;

while(1) {
char characTer = *(message_POINTER++);
if(characTer == '\0') break;
else {
printf("%c", characTer);
}
}

printf("\n");
return 9;
}


idk how to read code


Pointers are pretty self-explanatory. "When to use pointers" should be whenever you can, in my opinion.


This can be simplified to:

#include <stdio.h>

int main(void) {
  char message [] = "The raids will never stop";
  printf("%s\n", message);
  return 0;
}

I don't know why you're returning 9 (returning 0 is the standard thing to do), you really don't need to print a string character by character. Did you get this code from somewhere else or did you write it yourself? In any case the %s formatting tag will print any valid (null-terminated) string so there is no need for whatever it is that was going on before.

If you did want to loop through a string character by character, you would just index it like an array. E.g:

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

int main() {
  char message[] = "The raids will never stop";
  for (int i = 0; i < strlen(message); i++) {
    printf("%c", message[i]);
  }
  printf("\n");
  return 0;
}

Ultimately it isn't that complicated, and it's best to not make it complicated needlessly. Maybe a language like python would be more your speed, but C isn't difficult when you know what you're doing.

One last thing, you generally use pointers when you want to be able to dynamically allocate and de-allocate memory (variables). I.E. writing efficient programs that only use memory when it's needed and free it up immediately once they're done with it.


just use phppythonscript


Hey! You need to log in or create an account to do anything on this forum.

4,758 posts - 1,411 conversations - 0 members online

  • Display avatars